Explore.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. showingStartPage: Boolean(StartPage),
  237. },
  238. () => {
  239. if (datasourceError === null) {
  240. this.onSubmit();
  241. }
  242. }
  243. );
  244. }
  245. getRef = el => {
  246. this.el = el;
  247. };
  248. onAddQueryRow = index => {
  249. // Local cache
  250. this.modifiedQueries[index + 1] = { ...generateQueryKeys(index + 1) };
  251. this.setState(state => {
  252. const { initialQueries, queryTransactions } = state;
  253. const nextQueries = [
  254. ...initialQueries.slice(0, index + 1),
  255. { ...this.modifiedQueries[index + 1] },
  256. ...initialQueries.slice(index + 1),
  257. ];
  258. // Ongoing transactions need to update their row indices
  259. const nextQueryTransactions = queryTransactions.map(qt => {
  260. if (qt.rowIndex > index) {
  261. return {
  262. ...qt,
  263. rowIndex: qt.rowIndex + 1,
  264. };
  265. }
  266. return qt;
  267. });
  268. return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions };
  269. });
  270. };
  271. onChangeDatasource = async option => {
  272. const origin = this.state.datasource;
  273. this.setState({
  274. datasource: null,
  275. datasourceError: null,
  276. datasourceLoading: true,
  277. queryTransactions: [],
  278. });
  279. const datasourceName = option.value;
  280. const datasource = await this.props.datasourceSrv.get(datasourceName);
  281. this.setDatasource(datasource as any, origin);
  282. };
  283. onChangeQuery = (value: DataQuery, index: number, override?: boolean) => {
  284. // Null value means reset
  285. if (value === null) {
  286. value = { ...generateQueryKeys(index) };
  287. }
  288. // Keep current value in local cache
  289. this.modifiedQueries[index] = value;
  290. if (override) {
  291. this.setState(state => {
  292. // Replace query row by injecting new key
  293. const { initialQueries, queryTransactions } = state;
  294. const query: DataQuery = {
  295. ...value,
  296. ...generateQueryKeys(index),
  297. };
  298. const nextQueries = [...initialQueries];
  299. nextQueries[index] = query;
  300. this.modifiedQueries = [...nextQueries];
  301. // Discard ongoing transaction related to row query
  302. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  303. return {
  304. initialQueries: nextQueries,
  305. queryTransactions: nextQueryTransactions,
  306. };
  307. }, this.onSubmit);
  308. }
  309. };
  310. onChangeTime = (nextRange: RawTimeRange, scanning?: boolean) => {
  311. const range: RawTimeRange = {
  312. ...nextRange,
  313. };
  314. if (this.state.scanning && !scanning) {
  315. this.onStopScanning();
  316. }
  317. this.setState({ range, scanning }, () => this.onSubmit());
  318. };
  319. onClickClear = () => {
  320. this.onStopScanning();
  321. this.modifiedQueries = ensureQueries();
  322. this.setState(
  323. prevState => ({
  324. initialQueries: [...this.modifiedQueries],
  325. queryTransactions: [],
  326. showingStartPage: Boolean(prevState.StartPage),
  327. }),
  328. this.saveState
  329. );
  330. };
  331. onClickCloseSplit = () => {
  332. const { onChangeSplit } = this.props;
  333. if (onChangeSplit) {
  334. onChangeSplit(false);
  335. }
  336. };
  337. onClickGraphButton = () => {
  338. this.setState(
  339. state => {
  340. const showingGraph = !state.showingGraph;
  341. let nextQueryTransactions = state.queryTransactions;
  342. if (!showingGraph) {
  343. // Discard transactions related to Graph query
  344. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph');
  345. }
  346. return { queryTransactions: nextQueryTransactions, showingGraph };
  347. },
  348. () => {
  349. if (this.state.showingGraph) {
  350. this.onSubmit();
  351. }
  352. }
  353. );
  354. };
  355. onClickLogsButton = () => {
  356. this.setState(
  357. state => {
  358. const showingLogs = !state.showingLogs;
  359. let nextQueryTransactions = state.queryTransactions;
  360. if (!showingLogs) {
  361. // Discard transactions related to Logs query
  362. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs');
  363. }
  364. return { queryTransactions: nextQueryTransactions, showingLogs };
  365. },
  366. () => {
  367. if (this.state.showingLogs) {
  368. this.onSubmit();
  369. }
  370. }
  371. );
  372. };
  373. // Use this in help pages to set page to a single query
  374. onClickExample = (query: DataQuery) => {
  375. const nextQueries = [{ ...query, ...generateQueryKeys() }];
  376. this.modifiedQueries = [...nextQueries];
  377. this.setState({ initialQueries: nextQueries }, this.onSubmit);
  378. };
  379. onClickSplit = () => {
  380. const { onChangeSplit } = this.props;
  381. if (onChangeSplit) {
  382. const state = this.cloneState();
  383. onChangeSplit(true, state);
  384. }
  385. };
  386. onClickTableButton = () => {
  387. this.setState(
  388. state => {
  389. const showingTable = !state.showingTable;
  390. if (showingTable) {
  391. return { showingTable, queryTransactions: state.queryTransactions };
  392. }
  393. // Toggle off needs discarding of table queries
  394. const nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table');
  395. const results = calculateResultsFromQueryTransactions(
  396. nextQueryTransactions,
  397. state.datasource,
  398. state.graphInterval
  399. );
  400. return { ...results, queryTransactions: nextQueryTransactions, showingTable };
  401. },
  402. () => {
  403. if (this.state.showingTable) {
  404. this.onSubmit();
  405. }
  406. }
  407. );
  408. };
  409. onClickLabel = (key: string, value: string) => {
  410. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  411. };
  412. onModifyQueries = (action, index?: number) => {
  413. const { datasource } = this.state;
  414. if (datasource && datasource.modifyQuery) {
  415. const preventSubmit = action.preventSubmit;
  416. this.setState(
  417. state => {
  418. const { initialQueries, queryTransactions } = state;
  419. let nextQueries: DataQuery[];
  420. let nextQueryTransactions;
  421. if (index === undefined) {
  422. // Modify all queries
  423. nextQueries = initialQueries.map((query, i) => ({
  424. ...datasource.modifyQuery(this.modifiedQueries[i], action),
  425. ...generateQueryKeys(i),
  426. }));
  427. // Discard all ongoing transactions
  428. nextQueryTransactions = [];
  429. } else {
  430. // Modify query only at index
  431. nextQueries = initialQueries.map((query, i) => {
  432. // Synchronise all queries with local query cache to ensure consistency
  433. // TODO still needed?
  434. return i === index
  435. ? {
  436. ...datasource.modifyQuery(this.modifiedQueries[i], action),
  437. ...generateQueryKeys(i),
  438. }
  439. : query;
  440. });
  441. nextQueryTransactions = queryTransactions
  442. // Consume the hint corresponding to the action
  443. .map(qt => {
  444. if (qt.hints != null && qt.rowIndex === index) {
  445. qt.hints = qt.hints.filter(hint => hint.fix.action !== action);
  446. }
  447. return qt;
  448. })
  449. // Preserve previous row query transaction to keep results visible if next query is incomplete
  450. .filter(qt => preventSubmit || qt.rowIndex !== index);
  451. }
  452. this.modifiedQueries = [...nextQueries];
  453. return {
  454. initialQueries: nextQueries,
  455. queryTransactions: nextQueryTransactions,
  456. };
  457. },
  458. // Accepting certain fixes do not result in a well-formed query which should not be submitted
  459. !preventSubmit ? () => this.onSubmit() : null
  460. );
  461. }
  462. };
  463. onRemoveQueryRow = index => {
  464. // Remove from local cache
  465. this.modifiedQueries = [...this.modifiedQueries.slice(0, index), ...this.modifiedQueries.slice(index + 1)];
  466. this.setState(
  467. state => {
  468. const { initialQueries, queryTransactions } = state;
  469. if (initialQueries.length <= 1) {
  470. return null;
  471. }
  472. // Remove row from react state
  473. const nextQueries = [...initialQueries.slice(0, index), ...initialQueries.slice(index + 1)];
  474. // Discard transactions related to row query
  475. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  476. const results = calculateResultsFromQueryTransactions(
  477. nextQueryTransactions,
  478. state.datasource,
  479. state.graphInterval
  480. );
  481. return {
  482. ...results,
  483. initialQueries: nextQueries,
  484. queryTransactions: nextQueryTransactions,
  485. };
  486. },
  487. () => this.onSubmit()
  488. );
  489. };
  490. onStartScanning = () => {
  491. this.setState({ scanning: true }, this.scanPreviousRange);
  492. };
  493. scanPreviousRange = () => {
  494. const scanRange = this.timepickerRef.current.move(-1, true);
  495. this.setState({ scanRange });
  496. };
  497. onStopScanning = () => {
  498. clearTimeout(this.scanTimer);
  499. this.setState(state => {
  500. const { queryTransactions } = state;
  501. const nextQueryTransactions = queryTransactions.filter(qt => qt.scanning && !qt.done);
  502. return { queryTransactions: nextQueryTransactions, scanning: false, scanRange: undefined };
  503. });
  504. };
  505. onSubmit = () => {
  506. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  507. // Keep table queries first since they need to return quickly
  508. if (showingTable && supportsTable) {
  509. this.runQueries(
  510. 'Table',
  511. {
  512. format: 'table',
  513. instant: true,
  514. valueWithRefId: true,
  515. },
  516. data => data[0]
  517. );
  518. }
  519. if (showingGraph && supportsGraph) {
  520. this.runQueries(
  521. 'Graph',
  522. {
  523. format: 'time_series',
  524. instant: false,
  525. },
  526. makeTimeSeriesList
  527. );
  528. }
  529. if (showingLogs && supportsLogs) {
  530. this.runQueries('Logs', { format: 'logs' });
  531. }
  532. this.saveState();
  533. };
  534. buildQueryOptions(query: DataQuery, queryOptions: { format: string; hinting?: boolean; instant?: boolean }) {
  535. const { datasource, range } = this.state;
  536. const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth);
  537. const configuredQueries = [
  538. {
  539. ...query,
  540. ...queryOptions,
  541. },
  542. ];
  543. // Clone range for query request
  544. const queryRange: RawTimeRange = { ...range };
  545. // Datasource is using `panelId + query.refId` for cancellation logic.
  546. // Using `format` here because it relates to the view panel that the request is for.
  547. const panelId = queryOptions.format;
  548. return {
  549. interval,
  550. intervalMs,
  551. panelId,
  552. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  553. range: queryRange,
  554. };
  555. }
  556. startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  557. const queryOptions = this.buildQueryOptions(query, options);
  558. const transaction: QueryTransaction = {
  559. query,
  560. resultType,
  561. rowIndex,
  562. id: generateKey(), // reusing for unique ID
  563. done: false,
  564. latency: 0,
  565. options: queryOptions,
  566. scanning: this.state.scanning,
  567. };
  568. // Using updater style because we might be modifying queryTransactions in quick succession
  569. this.setState(state => {
  570. const { queryTransactions } = state;
  571. // Discarding existing transactions of same type
  572. const remainingTransactions = queryTransactions.filter(
  573. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  574. );
  575. // Append new transaction
  576. const nextQueryTransactions = [...remainingTransactions, transaction];
  577. const results = calculateResultsFromQueryTransactions(
  578. nextQueryTransactions,
  579. state.datasource,
  580. state.graphInterval
  581. );
  582. return {
  583. ...results,
  584. queryTransactions: nextQueryTransactions,
  585. showingStartPage: false,
  586. };
  587. });
  588. return transaction;
  589. }
  590. completeQueryTransaction(
  591. transactionId: string,
  592. result: any,
  593. latency: number,
  594. queries: DataQuery[],
  595. datasourceId: string
  596. ) {
  597. const { datasource } = this.state;
  598. if (datasource.meta.id !== datasourceId) {
  599. // Navigated away, queries did not matter
  600. return;
  601. }
  602. this.setState(state => {
  603. const { history, queryTransactions, scanning } = state;
  604. // Transaction might have been discarded
  605. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  606. if (!transaction) {
  607. return null;
  608. }
  609. // Get query hints
  610. let hints: QueryHint[];
  611. if (datasource.getQueryHints as QueryHintGetter) {
  612. hints = datasource.getQueryHints(transaction.query, result);
  613. }
  614. // Mark transactions as complete
  615. const nextQueryTransactions = queryTransactions.map(qt => {
  616. if (qt.id === transactionId) {
  617. return {
  618. ...qt,
  619. hints,
  620. latency,
  621. result,
  622. done: true,
  623. };
  624. }
  625. return qt;
  626. });
  627. const results = calculateResultsFromQueryTransactions(
  628. nextQueryTransactions,
  629. state.datasource,
  630. state.graphInterval
  631. );
  632. const nextHistory = updateHistory(history, datasourceId, queries);
  633. // Keep scanning for results if this was the last scanning transaction
  634. if (_.size(result) === 0 && scanning) {
  635. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  636. if (!other) {
  637. this.scanTimer = setTimeout(this.scanPreviousRange, 1000);
  638. }
  639. }
  640. return {
  641. ...results,
  642. history: nextHistory,
  643. queryTransactions: nextQueryTransactions,
  644. };
  645. });
  646. }
  647. failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
  648. const { datasource } = this.state;
  649. if (datasource.meta.id !== datasourceId || response.cancelled) {
  650. // Navigated away, queries did not matter
  651. return;
  652. }
  653. console.error(response);
  654. let error: string | JSX.Element = response;
  655. if (response.data) {
  656. if (typeof response.data === 'string') {
  657. error = response.data;
  658. } else if (response.data.error) {
  659. error = response.data.error;
  660. if (response.data.response) {
  661. error = (
  662. <>
  663. <span>{response.data.error}</span>
  664. <details>{response.data.response}</details>
  665. </>
  666. );
  667. }
  668. } else {
  669. throw new Error('Could not handle error response');
  670. }
  671. }
  672. this.setState(state => {
  673. // Transaction might have been discarded
  674. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  675. return null;
  676. }
  677. // Mark transactions as complete
  678. const nextQueryTransactions = state.queryTransactions.map(qt => {
  679. if (qt.id === transactionId) {
  680. return {
  681. ...qt,
  682. error,
  683. done: true,
  684. };
  685. }
  686. return qt;
  687. });
  688. return {
  689. queryTransactions: nextQueryTransactions,
  690. };
  691. });
  692. }
  693. async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {
  694. const queries = [...this.modifiedQueries];
  695. if (!hasNonEmptyQuery(queries)) {
  696. return;
  697. }
  698. const { datasource } = this.state;
  699. const datasourceId = datasource.meta.id;
  700. // Run all queries concurrently
  701. queries.forEach(async (query, rowIndex) => {
  702. const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions);
  703. try {
  704. const now = Date.now();
  705. const res = await datasource.query(transaction.options);
  706. const latency = Date.now() - now;
  707. const results = resultGetter ? resultGetter(res.data) : res.data;
  708. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  709. } catch (response) {
  710. this.failQueryTransaction(transaction.id, response, datasourceId);
  711. }
  712. });
  713. }
  714. cloneState(): ExploreState {
  715. // Copy state, but copy queries including modifications
  716. return {
  717. ...this.state,
  718. queryTransactions: [],
  719. initialQueries: [...this.modifiedQueries],
  720. };
  721. }
  722. saveState = () => {
  723. const { stateKey, onSaveState } = this.props;
  724. onSaveState(stateKey, this.cloneState());
  725. };
  726. render() {
  727. const { position, split } = this.props;
  728. const {
  729. StartPage,
  730. datasource,
  731. datasourceError,
  732. datasourceLoading,
  733. datasourceMissing,
  734. exploreDatasources,
  735. graphResult,
  736. history,
  737. initialQueries,
  738. logsResult,
  739. queryTransactions,
  740. range,
  741. scanning,
  742. scanRange,
  743. showingGraph,
  744. showingLogs,
  745. showingStartPage,
  746. showingTable,
  747. supportsGraph,
  748. supportsLogs,
  749. supportsTable,
  750. tableResult,
  751. } = this.state;
  752. const graphHeight = showingGraph && showingTable ? '200px' : '400px';
  753. const exploreClass = split ? 'explore explore-split' : 'explore';
  754. const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
  755. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  756. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  757. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  758. const loading = queryTransactions.some(qt => !qt.done);
  759. return (
  760. <div className={exploreClass} ref={this.getRef}>
  761. <div className="navbar">
  762. {position === 'left' ? (
  763. <div>
  764. <a className="navbar-page-btn">
  765. <i className="fa fa-rocket" />
  766. Explore
  767. </a>
  768. </div>
  769. ) : (
  770. <div className="navbar-buttons explore-first-button">
  771. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  772. Close Split
  773. </button>
  774. </div>
  775. )}
  776. {!datasourceMissing ? (
  777. <div className="navbar-buttons">
  778. <Select
  779. classNamePrefix={`gf-form-select-box`}
  780. isMulti={false}
  781. isLoading={datasourceLoading}
  782. isClearable={false}
  783. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  784. onChange={this.onChangeDatasource}
  785. options={exploreDatasources}
  786. styles={ResetStyles}
  787. placeholder="Select datasource"
  788. loadingMessage={() => 'Loading datasources...'}
  789. noOptionsMessage={() => 'No datasources found'}
  790. value={selectedDatasource}
  791. components={{
  792. Option: PickerOption,
  793. IndicatorsContainer,
  794. NoOptionsMessage,
  795. }}
  796. />
  797. </div>
  798. ) : null}
  799. <div className="navbar__spacer" />
  800. {position === 'left' && !split ? (
  801. <div className="navbar-buttons">
  802. <button className="btn navbar-button" onClick={this.onClickSplit}>
  803. Split
  804. </button>
  805. </div>
  806. ) : null}
  807. <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} />
  808. <div className="navbar-buttons">
  809. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  810. Clear All
  811. </button>
  812. </div>
  813. <div className="navbar-buttons relative">
  814. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  815. Run Query{' '}
  816. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  817. </button>
  818. </div>
  819. </div>
  820. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  821. {datasourceMissing ? (
  822. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  823. ) : null}
  824. {datasourceError ? (
  825. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  826. ) : null}
  827. {datasource && !datasourceError ? (
  828. <div className="explore-container">
  829. <QueryRows
  830. datasource={datasource}
  831. history={history}
  832. initialQueries={initialQueries}
  833. onAddQueryRow={this.onAddQueryRow}
  834. onChangeQuery={this.onChangeQuery}
  835. onClickHintFix={this.onModifyQueries}
  836. onExecuteQuery={this.onSubmit}
  837. onRemoveQueryRow={this.onRemoveQueryRow}
  838. transactions={queryTransactions}
  839. />
  840. <main className="m-t-2">
  841. <ErrorBoundary>
  842. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  843. {!showingStartPage && (
  844. <>
  845. {supportsGraph && (
  846. <Panel
  847. label="Graph"
  848. isOpen={showingGraph}
  849. loading={graphLoading}
  850. onToggle={this.onClickGraphButton}
  851. >
  852. <Graph
  853. data={graphResult}
  854. height={graphHeight}
  855. id={`explore-graph-${position}`}
  856. onChangeTime={this.onChangeTime}
  857. range={range}
  858. split={split}
  859. />
  860. </Panel>
  861. )}
  862. {supportsTable && (
  863. <Panel
  864. label="Table"
  865. loading={tableLoading}
  866. isOpen={showingTable}
  867. onToggle={this.onClickTableButton}
  868. >
  869. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} />
  870. </Panel>
  871. )}
  872. {supportsLogs && (
  873. <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
  874. <Logs
  875. data={logsResult}
  876. key={logsResult.id}
  877. loading={logsLoading}
  878. position={position}
  879. onChangeTime={this.onChangeTime}
  880. onClickLabel={this.onClickLabel}
  881. onStartScanning={this.onStartScanning}
  882. onStopScanning={this.onStopScanning}
  883. range={range}
  884. scanning={scanning}
  885. scanRange={scanRange}
  886. />
  887. </Panel>
  888. )}
  889. </>
  890. )}
  891. </ErrorBoundary>
  892. </main>
  893. </div>
  894. ) : null}
  895. </div>
  896. );
  897. }
  898. }
  899. export default hot(module)(Explore);