Explore.tsx 31 KB

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