Explore.tsx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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.getAll();
  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. };
  573. }
  574. startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  575. const queryOptions = this.buildQueryOptions(query, options);
  576. const transaction: QueryTransaction = {
  577. query,
  578. resultType,
  579. rowIndex,
  580. id: generateKey(), // reusing for unique ID
  581. done: false,
  582. latency: 0,
  583. options: queryOptions,
  584. scanning: this.state.scanning,
  585. };
  586. // Using updater style because we might be modifying queryTransactions in quick succession
  587. this.setState(state => {
  588. const { queryTransactions } = state;
  589. // Discarding existing transactions of same type
  590. const remainingTransactions = queryTransactions.filter(
  591. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  592. );
  593. // Append new transaction
  594. const nextQueryTransactions = [...remainingTransactions, transaction];
  595. const results = calculateResultsFromQueryTransactions(
  596. nextQueryTransactions,
  597. state.datasource,
  598. state.graphInterval
  599. );
  600. return {
  601. ...results,
  602. queryTransactions: nextQueryTransactions,
  603. showingStartPage: false,
  604. };
  605. });
  606. return transaction;
  607. }
  608. completeQueryTransaction(
  609. transactionId: string,
  610. result: any,
  611. latency: number,
  612. queries: DataQuery[],
  613. datasourceId: string
  614. ) {
  615. const { datasource } = this.state;
  616. if (datasource.meta.id !== datasourceId) {
  617. // Navigated away, queries did not matter
  618. return;
  619. }
  620. this.setState(state => {
  621. const { history, queryTransactions, scanning } = state;
  622. // Transaction might have been discarded
  623. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  624. if (!transaction) {
  625. return null;
  626. }
  627. // Get query hints
  628. let hints: QueryHint[];
  629. if (datasource.getQueryHints as QueryHintGetter) {
  630. hints = datasource.getQueryHints(transaction.query, result);
  631. }
  632. // Mark transactions as complete
  633. const nextQueryTransactions = queryTransactions.map(qt => {
  634. if (qt.id === transactionId) {
  635. return {
  636. ...qt,
  637. hints,
  638. latency,
  639. result,
  640. done: true,
  641. };
  642. }
  643. return qt;
  644. });
  645. const results = calculateResultsFromQueryTransactions(
  646. nextQueryTransactions,
  647. state.datasource,
  648. state.graphInterval
  649. );
  650. const nextHistory = updateHistory(history, datasourceId, queries);
  651. // Keep scanning for results if this was the last scanning transaction
  652. if (_.size(result) === 0 && scanning) {
  653. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  654. if (!other) {
  655. this.scanTimer = setTimeout(this.scanPreviousRange, 1000);
  656. }
  657. }
  658. return {
  659. ...results,
  660. history: nextHistory,
  661. queryTransactions: nextQueryTransactions,
  662. };
  663. });
  664. }
  665. failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
  666. const { datasource } = this.state;
  667. if (datasource.meta.id !== datasourceId || response.cancelled) {
  668. // Navigated away, queries did not matter
  669. return;
  670. }
  671. console.error(response);
  672. let error: string | JSX.Element = response;
  673. if (response.data) {
  674. if (typeof response.data === 'string') {
  675. error = response.data;
  676. } else if (response.data.error) {
  677. error = response.data.error;
  678. if (response.data.response) {
  679. error = (
  680. <>
  681. <span>{response.data.error}</span>
  682. <details>{response.data.response}</details>
  683. </>
  684. );
  685. }
  686. } else {
  687. throw new Error('Could not handle error response');
  688. }
  689. }
  690. this.setState(state => {
  691. // Transaction might have been discarded
  692. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  693. return null;
  694. }
  695. // Mark transactions as complete
  696. const nextQueryTransactions = state.queryTransactions.map(qt => {
  697. if (qt.id === transactionId) {
  698. return {
  699. ...qt,
  700. error,
  701. done: true,
  702. };
  703. }
  704. return qt;
  705. });
  706. return {
  707. queryTransactions: nextQueryTransactions,
  708. };
  709. });
  710. }
  711. async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {
  712. const queries = [...this.modifiedQueries];
  713. if (!hasNonEmptyQuery(queries)) {
  714. this.setState({
  715. queryTransactions: [],
  716. });
  717. return;
  718. }
  719. const { datasource } = this.state;
  720. const datasourceId = datasource.meta.id;
  721. // Run all queries concurrentlyso
  722. queries.forEach(async (query, rowIndex) => {
  723. const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions);
  724. try {
  725. const now = Date.now();
  726. const res = await datasource.query(transaction.options);
  727. this.exploreEvents.emit('data-received', res.data || []);
  728. const latency = Date.now() - now;
  729. const results = resultGetter ? resultGetter(res.data) : res.data;
  730. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  731. } catch (response) {
  732. this.exploreEvents.emit('data-error', response);
  733. this.failQueryTransaction(transaction.id, response, datasourceId);
  734. }
  735. });
  736. }
  737. updateLogsHighlights = _.debounce((value: DataQuery, index: number) => {
  738. this.setState(state => {
  739. const { datasource } = state;
  740. if (datasource.getHighlighterExpression) {
  741. const logsHighlighterExpressions = [state.datasource.getHighlighterExpression(value)];
  742. return { logsHighlighterExpressions };
  743. }
  744. return null;
  745. });
  746. }, 500);
  747. cloneState(): ExploreState {
  748. // Copy state, but copy queries including modifications
  749. return {
  750. ...this.state,
  751. queryTransactions: [],
  752. initialQueries: [...this.modifiedQueries],
  753. };
  754. }
  755. saveState = () => {
  756. const { stateKey, onSaveState } = this.props;
  757. onSaveState(stateKey, this.cloneState());
  758. };
  759. render() {
  760. const { position, split } = this.props;
  761. const {
  762. StartPage,
  763. datasource,
  764. datasourceError,
  765. datasourceLoading,
  766. datasourceMissing,
  767. exploreDatasources,
  768. graphResult,
  769. history,
  770. initialQueries,
  771. logsHighlighterExpressions,
  772. logsResult,
  773. queryTransactions,
  774. range,
  775. scanning,
  776. scanRange,
  777. showingGraph,
  778. showingLogs,
  779. showingStartPage,
  780. showingTable,
  781. supportsGraph,
  782. supportsLogs,
  783. supportsTable,
  784. tableResult,
  785. } = this.state;
  786. const graphHeight = showingGraph && showingTable ? '200px' : '400px';
  787. const exploreClass = split ? 'explore explore-split' : 'explore';
  788. const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
  789. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  790. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  791. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  792. const loading = queryTransactions.some(qt => !qt.done);
  793. return (
  794. <div className={exploreClass} ref={this.getRef}>
  795. <div className="navbar">
  796. {position === 'left' ? (
  797. <div>
  798. <a className="navbar-page-btn">
  799. <i className="fa fa-rocket" />
  800. Explore
  801. </a>
  802. </div>
  803. ) : (
  804. <div className="navbar-buttons explore-first-button">
  805. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  806. Close Split
  807. </button>
  808. </div>
  809. )}
  810. {!datasourceMissing ? (
  811. <div className="navbar-buttons">
  812. <Select
  813. classNamePrefix={`gf-form-select-box`}
  814. isMulti={false}
  815. menuShouldScrollIntoView={false}
  816. isLoading={datasourceLoading}
  817. isClearable={false}
  818. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  819. onChange={this.onChangeDatasource}
  820. options={exploreDatasources}
  821. styles={ResetStyles}
  822. placeholder="Select datasource"
  823. loadingMessage={() => 'Loading datasources...'}
  824. noOptionsMessage={() => 'No datasources found'}
  825. value={selectedDatasource}
  826. components={{
  827. Option: PickerOption,
  828. IndicatorsContainer,
  829. NoOptionsMessage,
  830. }}
  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--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);