Explore.tsx 33 KB

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