Explore.tsx 30 KB

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