Explore.tsx 30 KB

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