Explore.tsx 33 KB

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