Explore.tsx 33 KB

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