Explore.tsx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. // Most 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. // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
  558. // Therefore panel id has to be unique.
  559. const panelId = `${queryOptions.format}-${query.key}`;
  560. return {
  561. interval,
  562. intervalMs,
  563. panelId,
  564. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  565. range: {
  566. from: dateMath.parse(range.from, false),
  567. to: dateMath.parse(range.to, true),
  568. raw: range,
  569. },
  570. rangeRaw: range,
  571. scopedVars: {
  572. __interval: { text: interval, value: interval },
  573. __interval_ms: { text: intervalMs, value: intervalMs },
  574. },
  575. };
  576. }
  577. startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  578. const queryOptions = this.buildQueryOptions(query, options);
  579. const transaction: QueryTransaction = {
  580. query,
  581. resultType,
  582. rowIndex,
  583. id: generateKey(), // reusing for unique ID
  584. done: false,
  585. latency: 0,
  586. options: queryOptions,
  587. scanning: this.state.scanning,
  588. };
  589. // Using updater style because we might be modifying queryTransactions in quick succession
  590. this.setState(state => {
  591. const { queryTransactions } = state;
  592. // Discarding existing transactions of same type
  593. const remainingTransactions = queryTransactions.filter(
  594. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  595. );
  596. // Append new transaction
  597. const nextQueryTransactions = [...remainingTransactions, transaction];
  598. const results = calculateResultsFromQueryTransactions(
  599. nextQueryTransactions,
  600. state.datasource,
  601. state.graphInterval
  602. );
  603. return {
  604. ...results,
  605. queryTransactions: nextQueryTransactions,
  606. showingStartPage: false,
  607. graphInterval: queryOptions.intervalMs,
  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 } = state;
  626. let { scanning } = state;
  627. // Transaction might have been discarded
  628. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  629. if (!transaction) {
  630. return null;
  631. }
  632. // Get query hints
  633. let hints: QueryHint[];
  634. if (datasource.getQueryHints as QueryHintGetter) {
  635. hints = datasource.getQueryHints(transaction.query, result);
  636. }
  637. // Mark transactions as complete
  638. const nextQueryTransactions = queryTransactions.map(qt => {
  639. if (qt.id === transactionId) {
  640. return {
  641. ...qt,
  642. hints,
  643. latency,
  644. result,
  645. done: true,
  646. };
  647. }
  648. return qt;
  649. });
  650. const results = calculateResultsFromQueryTransactions(
  651. nextQueryTransactions,
  652. state.datasource,
  653. state.graphInterval
  654. );
  655. const nextHistory = updateHistory(history, datasourceId, queries);
  656. // Keep scanning for results if this was the last scanning transaction
  657. if (scanning) {
  658. if (_.size(result) === 0) {
  659. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  660. if (!other) {
  661. this.scanTimer = setTimeout(this.scanPreviousRange, 1000);
  662. }
  663. } else {
  664. // We can stop scanning if we have a result
  665. scanning = false;
  666. }
  667. }
  668. return {
  669. ...results,
  670. scanning,
  671. history: nextHistory,
  672. queryTransactions: nextQueryTransactions,
  673. };
  674. });
  675. }
  676. failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
  677. const { datasource } = this.state;
  678. if (datasource.meta.id !== datasourceId || response.cancelled) {
  679. // Navigated away, queries did not matter
  680. return;
  681. }
  682. console.error(response);
  683. let error: string | JSX.Element;
  684. if (response.data) {
  685. if (typeof response.data === 'string') {
  686. error = response.data;
  687. } else if (response.data.error) {
  688. error = response.data.error;
  689. if (response.data.response) {
  690. error = (
  691. <>
  692. <span>{response.data.error}</span>
  693. <details>{response.data.response}</details>
  694. </>
  695. );
  696. }
  697. } else {
  698. throw new Error('Could not handle error response');
  699. }
  700. } else if (response.message) {
  701. error = response.message;
  702. } else if (typeof response === 'string') {
  703. error = response;
  704. } else {
  705. error = 'Unknown error during query transaction. Please check JS console logs.';
  706. }
  707. this.setState(state => {
  708. // Transaction might have been discarded
  709. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  710. return null;
  711. }
  712. // Mark transactions as complete
  713. const nextQueryTransactions = state.queryTransactions.map(qt => {
  714. if (qt.id === transactionId) {
  715. return {
  716. ...qt,
  717. error,
  718. done: true,
  719. };
  720. }
  721. return qt;
  722. });
  723. return {
  724. queryTransactions: nextQueryTransactions,
  725. };
  726. });
  727. }
  728. async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {
  729. const queries = [...this.modifiedQueries];
  730. if (!hasNonEmptyQuery(queries)) {
  731. this.setState({
  732. queryTransactions: [],
  733. });
  734. return;
  735. }
  736. const { datasource } = this.state;
  737. const datasourceId = datasource.meta.id;
  738. // Run all queries concurrentlyso
  739. queries.forEach(async (query, rowIndex) => {
  740. const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions);
  741. try {
  742. const now = Date.now();
  743. const res = await datasource.query(transaction.options);
  744. this.exploreEvents.emit('data-received', res.data || []);
  745. const latency = Date.now() - now;
  746. const results = resultGetter ? resultGetter(res.data) : res.data;
  747. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  748. } catch (response) {
  749. this.exploreEvents.emit('data-error', response);
  750. this.failQueryTransaction(transaction.id, response, datasourceId);
  751. }
  752. });
  753. }
  754. updateLogsHighlights = _.debounce((value: DataQuery, index: number) => {
  755. this.setState(state => {
  756. const { datasource } = state;
  757. if (datasource.getHighlighterExpression) {
  758. const logsHighlighterExpressions = [state.datasource.getHighlighterExpression(value)];
  759. return { logsHighlighterExpressions };
  760. }
  761. return null;
  762. });
  763. }, 500);
  764. cloneState(): ExploreState {
  765. // Copy state, but copy queries including modifications
  766. return {
  767. ...this.state,
  768. queryTransactions: [],
  769. initialQueries: [...this.modifiedQueries],
  770. };
  771. }
  772. saveState = () => {
  773. const { stateKey, onSaveState } = this.props;
  774. onSaveState(stateKey, this.cloneState());
  775. };
  776. render() {
  777. const { position, split } = this.props;
  778. const {
  779. StartPage,
  780. datasource,
  781. datasourceError,
  782. datasourceLoading,
  783. datasourceMissing,
  784. exploreDatasources,
  785. graphResult,
  786. history,
  787. initialQueries,
  788. logsHighlighterExpressions,
  789. logsResult,
  790. queryTransactions,
  791. range,
  792. scanning,
  793. scanRange,
  794. showingGraph,
  795. showingLogs,
  796. showingStartPage,
  797. showingTable,
  798. supportsGraph,
  799. supportsLogs,
  800. supportsTable,
  801. tableResult,
  802. } = this.state;
  803. const graphHeight = showingGraph && showingTable ? '200px' : '400px';
  804. const exploreClass = split ? 'explore explore-split' : 'explore';
  805. const selectedDatasource = datasource ? exploreDatasources.find(d => d.name === datasource.name) : undefined;
  806. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  807. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  808. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  809. const loading = queryTransactions.some(qt => !qt.done);
  810. return (
  811. <div className={exploreClass} ref={this.getRef}>
  812. <div className="navbar">
  813. {position === 'left' ? (
  814. <div>
  815. <a className="navbar-page-btn">
  816. <i className="fa fa-rocket" />
  817. Explore
  818. </a>
  819. </div>
  820. ) : (
  821. <div className="navbar-buttons explore-first-button">
  822. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  823. Close Split
  824. </button>
  825. </div>
  826. )}
  827. {!datasourceMissing ? (
  828. <div className="navbar-buttons">
  829. <DataSourcePicker
  830. onChange={this.onChangeDatasource}
  831. datasources={exploreDatasources}
  832. current={selectedDatasource}
  833. />
  834. </div>
  835. ) : null}
  836. <div className="navbar__spacer" />
  837. {position === 'left' && !split ? (
  838. <div className="navbar-buttons">
  839. <button className="btn navbar-button" onClick={this.onClickSplit}>
  840. Split
  841. </button>
  842. </div>
  843. ) : null}
  844. <TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} />
  845. <div className="navbar-buttons">
  846. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  847. Clear All
  848. </button>
  849. </div>
  850. <div className="navbar-buttons relative">
  851. <button className="btn navbar-button navbar-button--primary" onClick={this.onSubmit}>
  852. Run Query{' '}
  853. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  854. </button>
  855. </div>
  856. </div>
  857. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  858. {datasourceMissing ? (
  859. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  860. ) : null}
  861. {datasourceError && (
  862. <div className="explore-container">
  863. <Alert message={`Error connecting to datasource: ${datasourceError}`} />
  864. </div>
  865. )}
  866. {datasource && !datasourceError ? (
  867. <div className="explore-container">
  868. <QueryRows
  869. datasource={datasource}
  870. history={history}
  871. initialQueries={initialQueries}
  872. onAddQueryRow={this.onAddQueryRow}
  873. onChangeQuery={this.onChangeQuery}
  874. onClickHintFix={this.onModifyQueries}
  875. onExecuteQuery={this.onSubmit}
  876. onRemoveQueryRow={this.onRemoveQueryRow}
  877. transactions={queryTransactions}
  878. exploreEvents={this.exploreEvents}
  879. range={range}
  880. />
  881. <main className="m-t-2">
  882. <ErrorBoundary>
  883. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  884. {!showingStartPage && (
  885. <>
  886. {supportsGraph && (
  887. <Panel
  888. label="Graph"
  889. isOpen={showingGraph}
  890. loading={graphLoading}
  891. onToggle={this.onClickGraphButton}
  892. >
  893. <Graph
  894. data={graphResult}
  895. height={graphHeight}
  896. id={`explore-graph-${position}`}
  897. onChangeTime={this.onChangeTime}
  898. range={range}
  899. split={split}
  900. />
  901. </Panel>
  902. )}
  903. {supportsTable && (
  904. <Panel
  905. label="Table"
  906. loading={tableLoading}
  907. isOpen={showingTable}
  908. onToggle={this.onClickTableButton}
  909. >
  910. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} />
  911. </Panel>
  912. )}
  913. {supportsLogs && (
  914. <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
  915. <Logs
  916. data={logsResult}
  917. key={logsResult.id}
  918. highlighterExpressions={logsHighlighterExpressions}
  919. loading={logsLoading}
  920. position={position}
  921. onChangeTime={this.onChangeTime}
  922. onClickLabel={this.onClickLabel}
  923. onStartScanning={this.onStartScanning}
  924. onStopScanning={this.onStopScanning}
  925. range={range}
  926. scanning={scanning}
  927. scanRange={scanRange}
  928. />
  929. </Panel>
  930. )}
  931. </>
  932. )}
  933. </ErrorBoundary>
  934. </main>
  935. </div>
  936. ) : null}
  937. </div>
  938. );
  939. }
  940. }
  941. export default hot(module)(Explore);