Explore.tsx 32 KB

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