Explore.tsx 33 KB

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