Explore.tsx 30 KB

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