Explore.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. import React from 'react';
  2. import { hot } from 'react-hot-loader';
  3. import _ from 'lodash';
  4. import { DataSource } from 'app/types/datasources';
  5. import {
  6. ExploreState,
  7. ExploreUrlState,
  8. QueryTransaction,
  9. ResultType,
  10. QueryHintGetter,
  11. QueryHint,
  12. } from 'app/types/explore';
  13. import { TimeRange } from '@grafana/ui';
  14. import { DataQuery } from 'app/types/series';
  15. import store from 'app/core/store';
  16. import {
  17. DEFAULT_RANGE,
  18. calculateResultsFromQueryTransactions,
  19. ensureQueries,
  20. getIntervals,
  21. generateKey,
  22. generateQueryKeys,
  23. hasNonEmptyQuery,
  24. makeTimeSeriesList,
  25. updateHistory,
  26. } from 'app/core/utils/explore';
  27. import { DataSourcePicker } from 'app/core/components/Select/DataSourcePicker';
  28. import TableModel from 'app/core/table_model';
  29. import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
  30. import { Emitter } from 'app/core/utils/emitter';
  31. import * as dateMath from 'app/core/utils/datemath';
  32. import Panel from './Panel';
  33. import QueryRows from './QueryRows';
  34. import Graph from './Graph';
  35. import Logs from './Logs';
  36. import Table from './Table';
  37. import ErrorBoundary from './ErrorBoundary';
  38. import { Alert } from './Error';
  39. import TimePicker, { parseTime } from './TimePicker';
  40. const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
  41. interface ExploreProps {
  42. datasourceSrv: DatasourceSrv;
  43. onChangeSplit: (split: boolean, state?: ExploreState) => void;
  44. onSaveState: (key: string, state: ExploreState) => void;
  45. position: string;
  46. split: boolean;
  47. splitState?: ExploreState;
  48. stateKey: string;
  49. urlState: ExploreUrlState;
  50. }
  51. /**
  52. * Explore provides an area for quick query iteration for a given datasource.
  53. * Once a datasource is selected it populates the query section at the top.
  54. * When queries are run, their results are being displayed in the main section.
  55. * The datasource determines what kind of query editor it brings, and what kind
  56. * of results viewers it supports.
  57. *
  58. * QUERY HANDLING
  59. *
  60. * TLDR: to not re-render Explore during edits, query editing is not "controlled"
  61. * in a React sense: values need to be pushed down via `initialQueries`, while
  62. * edits travel up via `this.modifiedQueries`.
  63. *
  64. * By default the query rows start without prior state: `initialQueries` will
  65. * contain one empty DataQuery. While the user modifies the DataQuery, the
  66. * modifications are being tracked in `this.modifiedQueries`, which need to be
  67. * used whenever a query is sent to the datasource to reflect what the user sees
  68. * on the screen. Query"react-popper": "^0.7.5", rows can be initialized or reset using `initialQueries`,
  69. * by giving the respec"react-popper": "^0.7.5",tive row a new key. This wipes the old row and its state.
  70. * This property is als"react-popper": "^0.7.5",o used to govern how many query rows there are (minimum 1).
  71. *
  72. * This flow makes sure that a query row can be arbitrarily complex without the
  73. * fear of being wiped or re-initialized via props. The query row is free to keep
  74. * its own state while the user edits or builds a query. Valid queries can be sent
  75. * up to Explore via the `onChangeQuery` prop.
  76. *
  77. * DATASOURCE REQUESTS
  78. *
  79. * A click on Run Query creates transactions for all DataQueries for all expanded
  80. * result viewers. New runs are discarding previous runs. Upon completion a transaction
  81. * saves the result. The result viewers construct their data from the currently existing
  82. * transactions.
  83. *
  84. * The result viewers determine some of the query options sent to the datasource, e.g.,
  85. * `format`, to indicate eventual transformations by the datasources' result transformers.
  86. */
  87. export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
  88. el: any;
  89. exploreEvents: Emitter;
  90. /**
  91. * Set via URL or local storage
  92. */
  93. initialDatasource: string;
  94. /**
  95. * Current query expressions of the rows including their modifications, used for running queries.
  96. * Not kept in component state to prevent edit-render roundtrips.
  97. */
  98. modifiedQueries: DataQuery[];
  99. /**
  100. * Local ID cache to compare requested vs selected datasource
  101. */
  102. requestedDatasourceId: string;
  103. scanTimer: NodeJS.Timer;
  104. /**
  105. * Timepicker to control scanning
  106. */
  107. timepickerRef: React.RefObject<TimePicker>;
  108. constructor(props) {
  109. super(props);
  110. const splitState: ExploreState = props.splitState;
  111. let initialQueries: DataQuery[];
  112. if (splitState) {
  113. // Split state overrides everything
  114. this.state = splitState;
  115. initialQueries = splitState.initialQueries;
  116. } else {
  117. const { datasource, queries, range } = props.urlState as ExploreUrlState;
  118. const initialDatasource = datasource || store.get(LAST_USED_DATASOURCE_KEY);
  119. initialQueries = ensureQueries(queries);
  120. const initialRange = { from: parseTime(range.from), to: parseTime(range.to) } || { ...DEFAULT_RANGE };
  121. // Millies step for helper bar charts
  122. const initialGraphInterval = 15 * 1000;
  123. this.state = {
  124. datasource: null,
  125. datasourceError: null,
  126. datasourceLoading: null,
  127. datasourceMissing: false,
  128. exploreDatasources: [],
  129. graphInterval: initialGraphInterval,
  130. graphResult: [],
  131. initialDatasource,
  132. initialQueries,
  133. history: [],
  134. logsResult: null,
  135. queryTransactions: [],
  136. range: initialRange,
  137. scanning: false,
  138. showingGraph: true,
  139. showingLogs: true,
  140. showingStartPage: false,
  141. showingTable: true,
  142. supportsGraph: null,
  143. supportsLogs: null,
  144. supportsTable: null,
  145. tableResult: new TableModel(),
  146. };
  147. }
  148. this.modifiedQueries = initialQueries.slice();
  149. this.exploreEvents = new Emitter();
  150. this.timepickerRef = React.createRef();
  151. }
  152. async componentDidMount() {
  153. const { datasourceSrv } = this.props;
  154. const { initialDatasource } = this.state;
  155. if (!datasourceSrv) {
  156. throw new Error('No datasource service passed as props.');
  157. }
  158. const datasources = datasourceSrv.getExternal();
  159. const exploreDatasources = datasources.map(ds => ({
  160. value: ds.name,
  161. name: ds.name,
  162. meta: ds.meta,
  163. }));
  164. if (datasources.length > 0) {
  165. this.setState({ datasourceLoading: true, exploreDatasources });
  166. // Priority for datasource preselection: URL, localstorage, default datasource
  167. let datasource;
  168. if (initialDatasource) {
  169. datasource = await datasourceSrv.get(initialDatasource);
  170. } else {
  171. datasource = await datasourceSrv.get();
  172. }
  173. await this.setDatasource(datasource);
  174. } else {
  175. this.setState({ datasourceMissing: true });
  176. }
  177. }
  178. componentWillUnmount() {
  179. this.exploreEvents.removeAllListeners();
  180. clearTimeout(this.scanTimer);
  181. }
  182. async setDatasource(datasource: any, origin?: DataSource) {
  183. const { initialQueries, range } = this.state;
  184. const supportsGraph = datasource.meta.metrics;
  185. const supportsLogs = datasource.meta.logs;
  186. const supportsTable = datasource.meta.tables;
  187. const datasourceId = datasource.meta.id;
  188. let datasourceError = null;
  189. // Keep ID to track selection
  190. this.requestedDatasourceId = datasourceId;
  191. try {
  192. const testResult = await datasource.testDatasource();
  193. datasourceError = testResult.status === 'success' ? null : testResult.message;
  194. } catch (error) {
  195. datasourceError = (error && error.statusText) || 'Network error';
  196. }
  197. if (datasourceId !== this.requestedDatasourceId) {
  198. // User already changed datasource again, discard results
  199. return;
  200. }
  201. const historyKey = `grafana.explore.history.${datasourceId}`;
  202. const history = store.getObject(historyKey, []);
  203. if (datasource.init) {
  204. datasource.init();
  205. }
  206. // Check if queries can be imported from previously selected datasource
  207. let modifiedQueries = this.modifiedQueries;
  208. if (origin) {
  209. if (origin.meta.id === datasource.meta.id) {
  210. // Keep same queries if same type of datasource
  211. modifiedQueries = [...this.modifiedQueries];
  212. } else if (datasource.importQueries) {
  213. // Datasource-specific importers
  214. modifiedQueries = await datasource.importQueries(this.modifiedQueries, origin.meta);
  215. } else {
  216. // Default is blank queries
  217. modifiedQueries = ensureQueries();
  218. }
  219. }
  220. // Reset edit state with new queries
  221. const nextQueries = initialQueries.map((q, i) => ({
  222. ...modifiedQueries[i],
  223. ...generateQueryKeys(i),
  224. }));
  225. this.modifiedQueries = modifiedQueries;
  226. // Custom components
  227. const StartPage = datasource.pluginExports.ExploreStartPage;
  228. // Calculate graph bucketing interval
  229. const graphInterval = getIntervals(range, datasource, this.el ? this.el.offsetWidth : 0).intervalMs;
  230. this.setState(
  231. {
  232. StartPage,
  233. datasource,
  234. datasourceError,
  235. graphInterval,
  236. history,
  237. supportsGraph,
  238. supportsLogs,
  239. supportsTable,
  240. datasourceLoading: false,
  241. initialDatasource: datasource.name,
  242. initialQueries: nextQueries,
  243. logsHighlighterExpressions: undefined,
  244. showingStartPage: Boolean(StartPage),
  245. },
  246. () => {
  247. if (datasourceError === null) {
  248. // Save last-used datasource
  249. store.set(LAST_USED_DATASOURCE_KEY, datasource.name);
  250. this.onSubmit();
  251. }
  252. }
  253. );
  254. }
  255. getRef = el => {
  256. this.el = el;
  257. };
  258. onAddQueryRow = index => {
  259. // Local cache
  260. this.modifiedQueries[index + 1] = { ...generateQueryKeys(index + 1) };
  261. this.setState(state => {
  262. const { initialQueries, queryTransactions } = state;
  263. const nextQueries = [
  264. ...initialQueries.slice(0, index + 1),
  265. { ...this.modifiedQueries[index + 1] },
  266. ...initialQueries.slice(index + 1),
  267. ];
  268. // Ongoing transactions need to update their row indices
  269. const nextQueryTransactions = queryTransactions.map(qt => {
  270. if (qt.rowIndex > index) {
  271. return {
  272. ...qt,
  273. rowIndex: qt.rowIndex + 1,
  274. };
  275. }
  276. return qt;
  277. });
  278. return {
  279. initialQueries: nextQueries,
  280. logsHighlighterExpressions: undefined,
  281. queryTransactions: nextQueryTransactions,
  282. };
  283. });
  284. };
  285. onChangeDatasource = async option => {
  286. const origin = this.state.datasource;
  287. this.setState({
  288. datasource: null,
  289. datasourceError: null,
  290. datasourceLoading: true,
  291. queryTransactions: [],
  292. });
  293. const datasourceName = option.value;
  294. const datasource = await this.props.datasourceSrv.get(datasourceName);
  295. this.setDatasource(datasource as any, origin);
  296. };
  297. onChangeQuery = (value: DataQuery, index: number, override?: boolean) => {
  298. // Null value means reset
  299. if (value === null) {
  300. value = { ...generateQueryKeys(index) };
  301. }
  302. // Keep current value in local cache
  303. this.modifiedQueries[index] = value;
  304. if (override) {
  305. this.setState(state => {
  306. // Replace query row by injecting new key
  307. const { initialQueries, queryTransactions } = state;
  308. const query: DataQuery = {
  309. ...value,
  310. ...generateQueryKeys(index),
  311. };
  312. const nextQueries = [...initialQueries];
  313. nextQueries[index] = query;
  314. this.modifiedQueries = [...nextQueries];
  315. // Discard ongoing transaction related to row query
  316. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  317. return {
  318. initialQueries: nextQueries,
  319. queryTransactions: nextQueryTransactions,
  320. };
  321. }, this.onSubmit);
  322. } else if (this.state.datasource.getHighlighterExpression && this.modifiedQueries.length === 1) {
  323. // Live preview of log search matches. Can only work on single row query for now
  324. this.updateLogsHighlights(value);
  325. }
  326. };
  327. onChangeTime = (nextRange: TimeRange, scanning?: boolean) => {
  328. const range: TimeRange = {
  329. ...nextRange,
  330. };
  331. if (this.state.scanning && !scanning) {
  332. this.onStopScanning();
  333. }
  334. this.setState({ range, scanning }, () => this.onSubmit());
  335. };
  336. onClickClear = () => {
  337. this.onStopScanning();
  338. this.modifiedQueries = ensureQueries();
  339. this.setState(
  340. prevState => ({
  341. initialQueries: [...this.modifiedQueries],
  342. queryTransactions: [],
  343. showingStartPage: Boolean(prevState.StartPage),
  344. }),
  345. this.saveState
  346. );
  347. };
  348. onClickCloseSplit = () => {
  349. const { onChangeSplit } = this.props;
  350. if (onChangeSplit) {
  351. onChangeSplit(false);
  352. }
  353. };
  354. onClickGraphButton = () => {
  355. this.setState(
  356. state => {
  357. const showingGraph = !state.showingGraph;
  358. let nextQueryTransactions = state.queryTransactions;
  359. if (!showingGraph) {
  360. // Discard transactions related to Graph query
  361. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph');
  362. }
  363. return { queryTransactions: nextQueryTransactions, showingGraph };
  364. },
  365. () => {
  366. if (this.state.showingGraph) {
  367. this.onSubmit();
  368. }
  369. }
  370. );
  371. };
  372. onClickLogsButton = () => {
  373. this.setState(
  374. state => {
  375. const showingLogs = !state.showingLogs;
  376. let nextQueryTransactions = state.queryTransactions;
  377. if (!showingLogs) {
  378. // Discard transactions related to Logs query
  379. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs');
  380. }
  381. return { queryTransactions: nextQueryTransactions, showingLogs };
  382. },
  383. () => {
  384. if (this.state.showingLogs) {
  385. this.onSubmit();
  386. }
  387. }
  388. );
  389. };
  390. // Use this in help pages to set page to a single query
  391. onClickExample = (query: DataQuery) => {
  392. const nextQueries = [{ ...query, ...generateQueryKeys() }];
  393. this.modifiedQueries = [...nextQueries];
  394. this.setState({ initialQueries: nextQueries }, this.onSubmit);
  395. };
  396. onClickSplit = () => {
  397. const { onChangeSplit } = this.props;
  398. if (onChangeSplit) {
  399. const state = this.cloneState();
  400. onChangeSplit(true, state);
  401. }
  402. };
  403. onClickTableButton = () => {
  404. this.setState(
  405. state => {
  406. const showingTable = !state.showingTable;
  407. if (showingTable) {
  408. return { showingTable, queryTransactions: state.queryTransactions };
  409. }
  410. // Toggle off needs discarding of table queries
  411. const nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table');
  412. const results = calculateResultsFromQueryTransactions(
  413. nextQueryTransactions,
  414. state.datasource,
  415. state.graphInterval
  416. );
  417. return { ...results, queryTransactions: nextQueryTransactions, showingTable };
  418. },
  419. () => {
  420. if (this.state.showingTable) {
  421. this.onSubmit();
  422. }
  423. }
  424. );
  425. };
  426. onClickLabel = (key: string, value: string) => {
  427. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  428. };
  429. onModifyQueries = (action, index?: number) => {
  430. const { datasource } = this.state;
  431. if (datasource && datasource.modifyQuery) {
  432. const preventSubmit = action.preventSubmit;
  433. this.setState(
  434. state => {
  435. const { initialQueries, queryTransactions } = state;
  436. let nextQueries: DataQuery[];
  437. let nextQueryTransactions;
  438. if (index === undefined) {
  439. // Modify all queries
  440. nextQueries = initialQueries.map((query, i) => ({
  441. ...datasource.modifyQuery(this.modifiedQueries[i], action),
  442. ...generateQueryKeys(i),
  443. }));
  444. // Discard all ongoing transactions
  445. nextQueryTransactions = [];
  446. } else {
  447. // Modify query only at index
  448. nextQueries = initialQueries.map((query, i) => {
  449. // Synchronize all queries with local query cache to ensure consistency
  450. // TODO still needed?
  451. return i === index
  452. ? {
  453. ...datasource.modifyQuery(this.modifiedQueries[i], action),
  454. ...generateQueryKeys(i),
  455. }
  456. : query;
  457. });
  458. nextQueryTransactions = queryTransactions
  459. // Consume the hint corresponding to the action
  460. .map(qt => {
  461. if (qt.hints != null && qt.rowIndex === index) {
  462. qt.hints = qt.hints.filter(hint => hint.fix.action !== action);
  463. }
  464. return qt;
  465. })
  466. // Preserve previous row query transaction to keep results visible if next query is incomplete
  467. .filter(qt => preventSubmit || qt.rowIndex !== index);
  468. }
  469. this.modifiedQueries = [...nextQueries];
  470. return {
  471. initialQueries: nextQueries,
  472. queryTransactions: nextQueryTransactions,
  473. };
  474. },
  475. // Accepting certain fixes do not result in a well-formed query which should not be submitted
  476. !preventSubmit ? () => this.onSubmit() : null
  477. );
  478. }
  479. };
  480. onRemoveQueryRow = index => {
  481. // Remove from local cache
  482. this.modifiedQueries = [...this.modifiedQueries.slice(0, index), ...this.modifiedQueries.slice(index + 1)];
  483. this.setState(
  484. state => {
  485. const { initialQueries, queryTransactions } = state;
  486. if (initialQueries.length <= 1) {
  487. return null;
  488. }
  489. // Remove row from react state
  490. const nextQueries = [...initialQueries.slice(0, index), ...initialQueries.slice(index + 1)];
  491. // Discard transactions related to row query
  492. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  493. const results = calculateResultsFromQueryTransactions(
  494. nextQueryTransactions,
  495. state.datasource,
  496. state.graphInterval
  497. );
  498. return {
  499. ...results,
  500. initialQueries: nextQueries,
  501. logsHighlighterExpressions: undefined,
  502. queryTransactions: nextQueryTransactions,
  503. };
  504. },
  505. () => this.onSubmit()
  506. );
  507. };
  508. onStartScanning = () => {
  509. this.setState({ scanning: true }, this.scanPreviousRange);
  510. };
  511. scanPreviousRange = () => {
  512. const scanRange = this.timepickerRef.current.move(-1, true);
  513. this.setState({ scanRange });
  514. };
  515. onStopScanning = () => {
  516. clearTimeout(this.scanTimer);
  517. this.setState(state => {
  518. const { queryTransactions } = state;
  519. const nextQueryTransactions = queryTransactions.filter(qt => qt.scanning && !qt.done);
  520. return { queryTransactions: nextQueryTransactions, scanning: false, scanRange: undefined };
  521. });
  522. };
  523. onSubmit = () => {
  524. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  525. // Keep table queries first since they need to return quickly
  526. if (showingTable && supportsTable) {
  527. this.runQueries(
  528. 'Table',
  529. {
  530. format: 'table',
  531. instant: true,
  532. valueWithRefId: true,
  533. },
  534. data => data[0]
  535. );
  536. }
  537. if (showingGraph && supportsGraph) {
  538. this.runQueries(
  539. 'Graph',
  540. {
  541. format: 'time_series',
  542. instant: false,
  543. },
  544. makeTimeSeriesList
  545. );
  546. }
  547. if (showingLogs && supportsLogs) {
  548. this.runQueries('Logs', { format: 'logs' });
  549. }
  550. this.saveState();
  551. };
  552. buildQueryOptions(query: DataQuery, queryOptions: { format: string; hinting?: boolean; instant?: boolean }) {
  553. const { datasource, range } = this.state;
  554. const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth);
  555. const configuredQueries = [
  556. {
  557. ...query,
  558. ...queryOptions,
  559. },
  560. ];
  561. // Clone range for query request
  562. // const queryRange: RawTimeRange = { ...range };
  563. // const { from, to, raw } = this.timeSrv.timeRange();
  564. // Most datasource is using `panelId + query.refId` for cancellation logic.
  565. // Using `format` here because it relates to the view panel that the request is for.
  566. // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
  567. // Therefore panel id has to be unique.
  568. const panelId = `${queryOptions.format}-${query.key}`;
  569. return {
  570. interval,
  571. intervalMs,
  572. panelId,
  573. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  574. range: {
  575. from: dateMath.parse(range.from, false),
  576. to: dateMath.parse(range.to, true),
  577. raw: range,
  578. },
  579. rangeRaw: range,
  580. scopedVars: {
  581. __interval: { text: interval, value: interval },
  582. __interval_ms: { text: intervalMs, value: intervalMs },
  583. },
  584. };
  585. }
  586. startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  587. const queryOptions = this.buildQueryOptions(query, options);
  588. const transaction: QueryTransaction = {
  589. query,
  590. resultType,
  591. rowIndex,
  592. id: generateKey(), // reusing for unique ID
  593. done: false,
  594. latency: 0,
  595. options: queryOptions,
  596. scanning: this.state.scanning,
  597. };
  598. // Using updater style because we might be modifying queryTransactions in quick succession
  599. this.setState(state => {
  600. const { queryTransactions } = state;
  601. // Discarding existing transactions of same type
  602. const remainingTransactions = queryTransactions.filter(
  603. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  604. );
  605. // Append new transaction
  606. const nextQueryTransactions = [...remainingTransactions, transaction];
  607. const results = calculateResultsFromQueryTransactions(
  608. nextQueryTransactions,
  609. state.datasource,
  610. state.graphInterval
  611. );
  612. return {
  613. ...results,
  614. queryTransactions: nextQueryTransactions,
  615. showingStartPage: false,
  616. graphInterval: queryOptions.intervalMs,
  617. };
  618. });
  619. return transaction;
  620. }
  621. completeQueryTransaction(
  622. transactionId: string,
  623. result: any,
  624. latency: number,
  625. queries: DataQuery[],
  626. datasourceId: string
  627. ) {
  628. const { datasource } = this.state;
  629. if (datasource.meta.id !== datasourceId) {
  630. // Navigated away, queries did not matter
  631. return;
  632. }
  633. this.setState(state => {
  634. const { history, queryTransactions } = state;
  635. let { scanning } = state;
  636. // Transaction might have been discarded
  637. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  638. if (!transaction) {
  639. return null;
  640. }
  641. // Get query hints
  642. let hints: QueryHint[];
  643. if (datasource.getQueryHints as QueryHintGetter) {
  644. hints = datasource.getQueryHints(transaction.query, result);
  645. }
  646. // Mark transactions as complete
  647. const nextQueryTransactions = queryTransactions.map(qt => {
  648. if (qt.id === transactionId) {
  649. return {
  650. ...qt,
  651. hints,
  652. latency,
  653. result,
  654. done: true,
  655. };
  656. }
  657. return qt;
  658. });
  659. const results = calculateResultsFromQueryTransactions(
  660. nextQueryTransactions,
  661. state.datasource,
  662. state.graphInterval
  663. );
  664. const nextHistory = updateHistory(history, datasourceId, queries);
  665. // Keep scanning for results if this was the last scanning transaction
  666. if (scanning) {
  667. if (_.size(result) === 0) {
  668. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  669. if (!other) {
  670. this.scanTimer = setTimeout(this.scanPreviousRange, 1000);
  671. }
  672. } else {
  673. // We can stop scanning if we have a result
  674. scanning = false;
  675. }
  676. }
  677. return {
  678. ...results,
  679. scanning,
  680. history: nextHistory,
  681. queryTransactions: nextQueryTransactions,
  682. };
  683. });
  684. }
  685. failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
  686. const { datasource } = this.state;
  687. if (datasource.meta.id !== datasourceId || response.cancelled) {
  688. // Navigated away, queries did not matter
  689. return;
  690. }
  691. console.error(response);
  692. let error: string | JSX.Element;
  693. if (response.data) {
  694. if (typeof response.data === 'string') {
  695. error = response.data;
  696. } else if (response.data.error) {
  697. error = response.data.error;
  698. if (response.data.response) {
  699. error = (
  700. <>
  701. <span>{response.data.error}</span>
  702. <details>{response.data.response}</details>
  703. </>
  704. );
  705. }
  706. } else {
  707. throw new Error('Could not handle error response');
  708. }
  709. } else if (response.message) {
  710. error = response.message;
  711. } else if (typeof response === 'string') {
  712. error = response;
  713. } else {
  714. error = 'Unknown error during query transaction. Please check JS console logs.';
  715. }
  716. this.setState(state => {
  717. // Transaction might have been discarded
  718. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  719. return null;
  720. }
  721. // Mark transactions as complete
  722. const nextQueryTransactions = state.queryTransactions.map(qt => {
  723. if (qt.id === transactionId) {
  724. return {
  725. ...qt,
  726. error,
  727. done: true,
  728. };
  729. }
  730. return qt;
  731. });
  732. return {
  733. queryTransactions: nextQueryTransactions,
  734. };
  735. });
  736. }
  737. async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {
  738. const queries = [...this.modifiedQueries];
  739. if (!hasNonEmptyQuery(queries)) {
  740. this.setState({
  741. queryTransactions: [],
  742. });
  743. return;
  744. }
  745. const { datasource } = this.state;
  746. const datasourceId = datasource.meta.id;
  747. // Run all queries concurrentlyso
  748. queries.forEach(async (query, rowIndex) => {
  749. const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions);
  750. try {
  751. const now = Date.now();
  752. const res = await datasource.query(transaction.options);
  753. this.exploreEvents.emit('data-received', res.data || []);
  754. const latency = Date.now() - now;
  755. const results = resultGetter ? resultGetter(res.data) : res.data;
  756. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  757. } catch (response) {
  758. this.exploreEvents.emit('data-error', response);
  759. this.failQueryTransaction(transaction.id, response, datasourceId);
  760. }
  761. });
  762. }
  763. updateLogsHighlights = _.debounce((value: DataQuery, index: number) => {
  764. this.setState(state => {
  765. const { datasource } = state;
  766. if (datasource.getHighlighterExpression) {
  767. const logsHighlighterExpressions = [state.datasource.getHighlighterExpression(value)];
  768. return { logsHighlighterExpressions };
  769. }
  770. return null;
  771. });
  772. }, 500);
  773. cloneState(): ExploreState {
  774. // Copy state, but copy queries including modifications
  775. return {
  776. ...this.state,
  777. queryTransactions: [],
  778. initialQueries: [...this.modifiedQueries],
  779. };
  780. }
  781. saveState = () => {
  782. const { stateKey, onSaveState } = this.props;
  783. onSaveState(stateKey, this.cloneState());
  784. };
  785. render() {
  786. const { position, split } = this.props;
  787. const {
  788. StartPage,
  789. datasource,
  790. datasourceError,
  791. datasourceLoading,
  792. datasourceMissing,
  793. exploreDatasources,
  794. graphResult,
  795. history,
  796. initialQueries,
  797. logsHighlighterExpressions,
  798. logsResult,
  799. queryTransactions,
  800. range,
  801. scanning,
  802. scanRange,
  803. showingGraph,
  804. showingLogs,
  805. showingStartPage,
  806. showingTable,
  807. supportsGraph,
  808. supportsLogs,
  809. supportsTable,
  810. tableResult,
  811. } = this.state;
  812. const graphHeight = showingGraph && showingTable ? '200px' : '400px';
  813. const exploreClass = split ? 'explore explore-split' : 'explore';
  814. const selectedDatasource = datasource ? exploreDatasources.find(d => d.name === datasource.name) : undefined;
  815. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  816. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  817. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  818. const loading = queryTransactions.some(qt => !qt.done);
  819. return (
  820. <div className={exploreClass} ref={this.getRef}>
  821. <div className="navbar">
  822. {position === 'left' ? (
  823. <div>
  824. <a className="navbar-page-btn">
  825. <i className="fa fa-rocket" />
  826. Explore
  827. </a>
  828. </div>
  829. ) : (
  830. <div className="navbar-buttons explore-first-button">
  831. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  832. Close Split
  833. </button>
  834. </div>
  835. )}
  836. {!datasourceMissing ? (
  837. <div className="navbar-buttons">
  838. <DataSourcePicker
  839. onChange={this.onChangeDatasource}
  840. datasources={exploreDatasources}
  841. current={selectedDatasource}
  842. />
  843. </div>
  844. ) : null}
  845. <div className="navbar__spacer" />
  846. {position === 'left' && !split ? (
  847. <div className="navbar-buttons">
  848. <button className="btn navbar-button" onClick={this.onClickSplit}>
  849. Split
  850. </button>
  851. </div>
  852. ) : null}
  853. <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} />
  854. <div className="navbar-buttons">
  855. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  856. Clear All
  857. </button>
  858. </div>
  859. <div className="navbar-buttons relative">
  860. <button className="btn navbar-button navbar-button--primary" onClick={this.onSubmit}>
  861. Run Query{' '}
  862. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  863. </button>
  864. </div>
  865. </div>
  866. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  867. {datasourceMissing ? (
  868. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  869. ) : null}
  870. {datasourceError && (
  871. <div className="explore-container">
  872. <Alert message={`Error connecting to datasource: ${datasourceError}`} />
  873. </div>
  874. )}
  875. {datasource && !datasourceError ? (
  876. <div className="explore-container">
  877. <QueryRows
  878. datasource={datasource}
  879. history={history}
  880. initialQueries={initialQueries}
  881. onAddQueryRow={this.onAddQueryRow}
  882. onChangeQuery={this.onChangeQuery}
  883. onClickHintFix={this.onModifyQueries}
  884. onExecuteQuery={this.onSubmit}
  885. onRemoveQueryRow={this.onRemoveQueryRow}
  886. transactions={queryTransactions}
  887. exploreEvents={this.exploreEvents}
  888. range={range}
  889. />
  890. <main className="m-t-2">
  891. <ErrorBoundary>
  892. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  893. {!showingStartPage && (
  894. <>
  895. {supportsGraph && (
  896. <Panel
  897. label="Graph"
  898. isOpen={showingGraph}
  899. loading={graphLoading}
  900. onToggle={this.onClickGraphButton}
  901. >
  902. <Graph
  903. data={graphResult}
  904. height={graphHeight}
  905. id={`explore-graph-${position}`}
  906. onChangeTime={this.onChangeTime}
  907. range={range}
  908. split={split}
  909. />
  910. </Panel>
  911. )}
  912. {supportsTable && (
  913. <Panel
  914. label="Table"
  915. loading={tableLoading}
  916. isOpen={showingTable}
  917. onToggle={this.onClickTableButton}
  918. >
  919. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} />
  920. </Panel>
  921. )}
  922. {supportsLogs && (
  923. <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
  924. <Logs
  925. data={logsResult}
  926. key={logsResult.id}
  927. highlighterExpressions={logsHighlighterExpressions}
  928. loading={logsLoading}
  929. position={position}
  930. onChangeTime={this.onChangeTime}
  931. onClickLabel={this.onClickLabel}
  932. onStartScanning={this.onStartScanning}
  933. onStopScanning={this.onStopScanning}
  934. range={range}
  935. scanning={scanning}
  936. scanRange={scanRange}
  937. />
  938. </Panel>
  939. )}
  940. </>
  941. )}
  942. </ErrorBoundary>
  943. </main>
  944. </div>
  945. ) : null}
  946. </div>
  947. );
  948. }
  949. }
  950. export default hot(module)(Explore);