Explore.tsx 31 KB

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