Explore.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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 { Alert } from './Error';
  42. import TimePicker, { parseTime } from './TimePicker';
  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 = { from: parseTime(range.from), to: parseTime(range.to) } || { ...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 } = 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.label === 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. <Select
  831. classNamePrefix={`gf-form-select-box`}
  832. isMulti={false}
  833. menuShouldScrollIntoView={false}
  834. isLoading={datasourceLoading}
  835. isClearable={false}
  836. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  837. onChange={this.onChangeDatasource}
  838. options={exploreDatasources}
  839. styles={ResetStyles}
  840. maxMenuHeight={500}
  841. placeholder="Select datasource"
  842. loadingMessage={() => 'Loading datasources...'}
  843. noOptionsMessage={() => 'No datasources found'}
  844. value={selectedDatasource}
  845. components={{
  846. Option: PickerOption,
  847. IndicatorsContainer,
  848. NoOptionsMessage,
  849. }}
  850. />
  851. </div>
  852. ) : null}
  853. <div className="navbar__spacer" />
  854. {position === 'left' && !split ? (
  855. <div className="navbar-buttons">
  856. <button className="btn navbar-button" onClick={this.onClickSplit}>
  857. Split
  858. </button>
  859. </div>
  860. ) : null}
  861. <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} />
  862. <div className="navbar-buttons">
  863. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  864. Clear All
  865. </button>
  866. </div>
  867. <div className="navbar-buttons relative">
  868. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  869. Run Query{' '}
  870. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  871. </button>
  872. </div>
  873. </div>
  874. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  875. {datasourceMissing ? (
  876. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  877. ) : null}
  878. {datasourceError && (
  879. <div className="explore-container">
  880. <Alert message={`Error connecting to datasource: ${datasourceError}`} />
  881. </div>
  882. )}
  883. {datasource && !datasourceError ? (
  884. <div className="explore-container">
  885. <QueryRows
  886. datasource={datasource}
  887. history={history}
  888. initialQueries={initialQueries}
  889. onAddQueryRow={this.onAddQueryRow}
  890. onChangeQuery={this.onChangeQuery}
  891. onClickHintFix={this.onModifyQueries}
  892. onExecuteQuery={this.onSubmit}
  893. onRemoveQueryRow={this.onRemoveQueryRow}
  894. transactions={queryTransactions}
  895. exploreEvents={this.exploreEvents}
  896. range={range}
  897. />
  898. <main className="m-t-2">
  899. <ErrorBoundary>
  900. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  901. {!showingStartPage && (
  902. <>
  903. {supportsGraph && (
  904. <Panel
  905. label="Graph"
  906. isOpen={showingGraph}
  907. loading={graphLoading}
  908. onToggle={this.onClickGraphButton}
  909. >
  910. <Graph
  911. data={graphResult}
  912. height={graphHeight}
  913. id={`explore-graph-${position}`}
  914. onChangeTime={this.onChangeTime}
  915. range={range}
  916. split={split}
  917. />
  918. </Panel>
  919. )}
  920. {supportsTable && (
  921. <Panel
  922. label="Table"
  923. loading={tableLoading}
  924. isOpen={showingTable}
  925. onToggle={this.onClickTableButton}
  926. >
  927. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} />
  928. </Panel>
  929. )}
  930. {supportsLogs && (
  931. <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
  932. <Logs
  933. data={logsResult}
  934. key={logsResult.id}
  935. highlighterExpressions={logsHighlighterExpressions}
  936. loading={logsLoading}
  937. position={position}
  938. onChangeTime={this.onChangeTime}
  939. onClickLabel={this.onClickLabel}
  940. onStartScanning={this.onStartScanning}
  941. onStopScanning={this.onStopScanning}
  942. range={range}
  943. scanning={scanning}
  944. scanRange={scanRange}
  945. />
  946. </Panel>
  947. )}
  948. </>
  949. )}
  950. </ErrorBoundary>
  951. </main>
  952. </div>
  953. ) : null}
  954. </div>
  955. );
  956. }
  957. }
  958. export default hot(module)(Explore);