Explore.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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 { ExploreState, ExploreUrlState, HistoryItem, Query, QueryTransaction, ResultType } from 'app/types/explore';
  7. import { RawTimeRange, DataQuery } from 'app/types/series';
  8. import kbn from 'app/core/utils/kbn';
  9. import colors from 'app/core/utils/colors';
  10. import store from 'app/core/store';
  11. import TimeSeries from 'app/core/time_series2';
  12. import { parse as parseDate } from 'app/core/utils/datemath';
  13. import { DEFAULT_RANGE } from 'app/core/utils/explore';
  14. import ResetStyles from 'app/core/components/Picker/ResetStyles';
  15. import PickerOption from 'app/core/components/Picker/PickerOption';
  16. import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer';
  17. import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage';
  18. import TableModel, { mergeTablesIntoModel } from 'app/core/table_model';
  19. import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
  20. import Panel from './Panel';
  21. import QueryRows from './QueryRows';
  22. import Graph from './Graph';
  23. import Logs from './Logs';
  24. import Table from './Table';
  25. import ErrorBoundary from './ErrorBoundary';
  26. import TimePicker from './TimePicker';
  27. import { ensureQueries, generateQueryKey, hasQuery } from './utils/query';
  28. const MAX_HISTORY_ITEMS = 100;
  29. function getIntervals(range: RawTimeRange, datasource, resolution: number): { interval: string; intervalMs: number } {
  30. if (!datasource || !resolution) {
  31. return { interval: '1s', intervalMs: 1000 };
  32. }
  33. const absoluteRange: RawTimeRange = {
  34. from: parseDate(range.from, false),
  35. to: parseDate(range.to, true),
  36. };
  37. return kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  38. }
  39. function makeTimeSeriesList(dataList, options) {
  40. return dataList.map((seriesData, index) => {
  41. const datapoints = seriesData.datapoints || [];
  42. const alias = seriesData.target;
  43. const colorIndex = index % colors.length;
  44. const color = colors[colorIndex];
  45. const series = new TimeSeries({
  46. datapoints,
  47. alias,
  48. color,
  49. unit: seriesData.unit,
  50. });
  51. return series;
  52. });
  53. }
  54. /**
  55. * Update the query history. Side-effect: store history in local storage
  56. */
  57. function updateHistory(history: HistoryItem[], datasourceId: string, queries: string[]): HistoryItem[] {
  58. const ts = Date.now();
  59. queries.forEach(query => {
  60. history = [{ query, ts }, ...history];
  61. });
  62. if (history.length > MAX_HISTORY_ITEMS) {
  63. history = history.slice(0, MAX_HISTORY_ITEMS);
  64. }
  65. // Combine all queries of a datasource type into one history
  66. const historyKey = `grafana.explore.history.${datasourceId}`;
  67. store.setObject(historyKey, history);
  68. return history;
  69. }
  70. interface ExploreProps {
  71. datasourceSrv: DatasourceSrv;
  72. onChangeSplit: (split: boolean, state?: ExploreState) => void;
  73. onSaveState: (key: string, state: ExploreState) => void;
  74. position: string;
  75. split: boolean;
  76. splitState?: ExploreState;
  77. stateKey: string;
  78. urlState: ExploreUrlState;
  79. }
  80. export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
  81. el: any;
  82. /**
  83. * Current query expressions of the rows including their modifications, used for running queries.
  84. * Not kept in component state to prevent edit-render roundtrips.
  85. * TODO: make this generic (other datasources might not have string representations of current query state)
  86. */
  87. queryExpressions: string[];
  88. /**
  89. * Local ID cache to compare requested vs selected datasource
  90. */
  91. requestedDatasourceId: string;
  92. constructor(props) {
  93. super(props);
  94. const splitState: ExploreState = props.splitState;
  95. let initialQueries: Query[];
  96. if (splitState) {
  97. // Split state overrides everything
  98. this.state = splitState;
  99. initialQueries = splitState.queries;
  100. } else {
  101. const { datasource, queries, range } = props.urlState as ExploreUrlState;
  102. initialQueries = ensureQueries(queries);
  103. const initialRange = range || { ...DEFAULT_RANGE };
  104. this.state = {
  105. datasource: null,
  106. datasourceError: null,
  107. datasourceLoading: null,
  108. datasourceMissing: false,
  109. datasourceName: datasource,
  110. exploreDatasources: [],
  111. graphRange: initialRange,
  112. history: [],
  113. queries: initialQueries,
  114. queryTransactions: [],
  115. range: initialRange,
  116. showingGraph: true,
  117. showingLogs: true,
  118. showingStartPage: false,
  119. showingTable: true,
  120. supportsGraph: null,
  121. supportsLogs: null,
  122. supportsTable: null,
  123. };
  124. }
  125. this.queryExpressions = initialQueries.map(q => q.query);
  126. }
  127. async componentDidMount() {
  128. const { datasourceSrv } = this.props;
  129. const { datasourceName } = this.state;
  130. if (!datasourceSrv) {
  131. throw new Error('No datasource service passed as props.');
  132. }
  133. const datasources = datasourceSrv.getExploreSources();
  134. const exploreDatasources = datasources.map(ds => ({
  135. value: ds.name,
  136. label: ds.name,
  137. }));
  138. if (datasources.length > 0) {
  139. this.setState({ datasourceLoading: true, exploreDatasources });
  140. // Priority: datasource in url, default datasource, first explore datasource
  141. let datasource;
  142. if (datasourceName) {
  143. datasource = await datasourceSrv.get(datasourceName);
  144. } else {
  145. datasource = await datasourceSrv.get();
  146. }
  147. if (!datasource.meta.explore) {
  148. datasource = await datasourceSrv.get(datasources[0].name);
  149. }
  150. await this.setDatasource(datasource);
  151. } else {
  152. this.setState({ datasourceMissing: true });
  153. }
  154. }
  155. async setDatasource(datasource: any, origin?: DataSource) {
  156. const supportsGraph = datasource.meta.metrics;
  157. const supportsLogs = datasource.meta.logs;
  158. const supportsTable = datasource.meta.metrics;
  159. const datasourceId = datasource.meta.id;
  160. let datasourceError = null;
  161. // Keep ID to track selection
  162. this.requestedDatasourceId = datasourceId;
  163. try {
  164. const testResult = await datasource.testDatasource();
  165. datasourceError = testResult.status === 'success' ? null : testResult.message;
  166. } catch (error) {
  167. datasourceError = (error && error.statusText) || 'Network error';
  168. }
  169. if (datasourceId !== this.requestedDatasourceId) {
  170. // User already changed datasource again, discard results
  171. return;
  172. }
  173. const historyKey = `grafana.explore.history.${datasourceId}`;
  174. const history = store.getObject(historyKey, []);
  175. if (datasource.init) {
  176. datasource.init();
  177. }
  178. // Check if queries can be imported from previously selected datasource
  179. let queryExpressions = this.queryExpressions;
  180. if (origin) {
  181. if (origin.meta.id === datasource.meta.id) {
  182. // Keep same queries if same type of datasource
  183. queryExpressions = [...this.queryExpressions];
  184. } else if (datasource.importQueries) {
  185. // Datasource-specific importers, wrapping to satisfy interface
  186. const wrappedQueries: DataQuery[] = this.queryExpressions.map((query, index) => ({
  187. refId: String(index),
  188. expr: query,
  189. }));
  190. const modifiedQueries: DataQuery[] = await datasource.importQueries(wrappedQueries, origin.meta);
  191. queryExpressions = modifiedQueries.map(({ expr }) => expr);
  192. } else {
  193. // Default is blank queries
  194. queryExpressions = this.queryExpressions.map(() => '');
  195. }
  196. }
  197. // Reset edit state with new queries
  198. const nextQueries = this.state.queries.map((q, i) => ({
  199. ...q,
  200. key: generateQueryKey(i),
  201. query: queryExpressions[i],
  202. }));
  203. this.queryExpressions = queryExpressions;
  204. // Custom components
  205. const StartPage = datasource.pluginExports.ExploreStartPage;
  206. this.setState(
  207. {
  208. StartPage,
  209. datasource,
  210. datasourceError,
  211. history,
  212. supportsGraph,
  213. supportsLogs,
  214. supportsTable,
  215. datasourceLoading: false,
  216. datasourceName: datasource.name,
  217. queries: nextQueries,
  218. showingStartPage: Boolean(StartPage),
  219. },
  220. () => {
  221. if (datasourceError === null) {
  222. this.onSubmit();
  223. }
  224. }
  225. );
  226. }
  227. getRef = el => {
  228. this.el = el;
  229. };
  230. onAddQueryRow = index => {
  231. // Local cache
  232. this.queryExpressions[index + 1] = '';
  233. this.setState(state => {
  234. const { queries, queryTransactions } = state;
  235. // Add row by generating new react key
  236. const nextQueries = [
  237. ...queries.slice(0, index + 1),
  238. { query: '', key: generateQueryKey() },
  239. ...queries.slice(index + 1),
  240. ];
  241. // Ongoing transactions need to update their row indices
  242. const nextQueryTransactions = queryTransactions.map(qt => {
  243. if (qt.rowIndex > index) {
  244. return {
  245. ...qt,
  246. rowIndex: qt.rowIndex + 1,
  247. };
  248. }
  249. return qt;
  250. });
  251. return { queries: nextQueries, queryTransactions: nextQueryTransactions };
  252. });
  253. };
  254. onChangeDatasource = async option => {
  255. const origin = this.state.datasource;
  256. this.setState({
  257. datasource: null,
  258. datasourceError: null,
  259. datasourceLoading: true,
  260. queryTransactions: [],
  261. });
  262. const datasourceName = option.value;
  263. const datasource = await this.props.datasourceSrv.get(datasourceName);
  264. this.setDatasource(datasource as any, origin);
  265. };
  266. onChangeQuery = (value: string, index: number, override?: boolean) => {
  267. // Keep current value in local cache
  268. this.queryExpressions[index] = value;
  269. if (override) {
  270. this.setState(state => {
  271. // Replace query row
  272. const { queries, queryTransactions } = state;
  273. const nextQuery: Query = {
  274. key: generateQueryKey(index),
  275. query: value,
  276. };
  277. const nextQueries = [...queries];
  278. nextQueries[index] = nextQuery;
  279. // Discard ongoing transaction related to row query
  280. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  281. return {
  282. queries: nextQueries,
  283. queryTransactions: nextQueryTransactions,
  284. };
  285. }, this.onSubmit);
  286. }
  287. };
  288. onChangeTime = (nextRange: RawTimeRange) => {
  289. const range: RawTimeRange = {
  290. ...nextRange,
  291. };
  292. this.setState({ range }, () => this.onSubmit());
  293. };
  294. onClickClear = () => {
  295. this.queryExpressions = [''];
  296. this.setState(
  297. prevState => ({
  298. queries: ensureQueries(),
  299. queryTransactions: [],
  300. showingStartPage: Boolean(prevState.StartPage),
  301. }),
  302. this.saveState
  303. );
  304. };
  305. onClickCloseSplit = () => {
  306. const { onChangeSplit } = this.props;
  307. if (onChangeSplit) {
  308. onChangeSplit(false);
  309. }
  310. };
  311. onClickGraphButton = () => {
  312. this.setState(
  313. state => {
  314. const showingGraph = !state.showingGraph;
  315. let nextQueryTransactions = state.queryTransactions;
  316. if (!showingGraph) {
  317. // Discard transactions related to Graph query
  318. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph');
  319. }
  320. return { queryTransactions: nextQueryTransactions, showingGraph };
  321. },
  322. () => {
  323. if (this.state.showingGraph) {
  324. this.onSubmit();
  325. }
  326. }
  327. );
  328. };
  329. onClickLogsButton = () => {
  330. this.setState(
  331. state => {
  332. const showingLogs = !state.showingLogs;
  333. let nextQueryTransactions = state.queryTransactions;
  334. if (!showingLogs) {
  335. // Discard transactions related to Logs query
  336. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs');
  337. }
  338. return { queryTransactions: nextQueryTransactions, showingLogs };
  339. },
  340. () => {
  341. if (this.state.showingLogs) {
  342. this.onSubmit();
  343. }
  344. }
  345. );
  346. };
  347. // Use this in help pages to set page to a single query
  348. onClickQuery = query => {
  349. const nextQueries = [{ query, key: generateQueryKey() }];
  350. this.queryExpressions = nextQueries.map(q => q.query);
  351. this.setState({ queries: nextQueries }, this.onSubmit);
  352. };
  353. onClickSplit = () => {
  354. const { onChangeSplit } = this.props;
  355. if (onChangeSplit) {
  356. const state = this.cloneState();
  357. onChangeSplit(true, state);
  358. }
  359. };
  360. onClickTableButton = () => {
  361. this.setState(
  362. state => {
  363. const showingTable = !state.showingTable;
  364. let nextQueryTransactions = state.queryTransactions;
  365. if (!showingTable) {
  366. // Discard transactions related to Table query
  367. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table');
  368. }
  369. return { queryTransactions: nextQueryTransactions, showingTable };
  370. },
  371. () => {
  372. if (this.state.showingTable) {
  373. this.onSubmit();
  374. }
  375. }
  376. );
  377. };
  378. onClickTableCell = (columnKey: string, rowValue: string) => {
  379. this.onModifyQueries({ type: 'ADD_FILTER', key: columnKey, value: rowValue });
  380. };
  381. onModifyQueries = (action, index?: number) => {
  382. const { datasource } = this.state;
  383. if (datasource && datasource.modifyQuery) {
  384. const preventSubmit = action.preventSubmit;
  385. this.setState(
  386. state => {
  387. const { queries, queryTransactions } = state;
  388. let nextQueries;
  389. let nextQueryTransactions;
  390. if (index === undefined) {
  391. // Modify all queries
  392. nextQueries = queries.map((q, i) => ({
  393. key: generateQueryKey(i),
  394. query: datasource.modifyQuery(this.queryExpressions[i], action),
  395. }));
  396. // Discard all ongoing transactions
  397. nextQueryTransactions = [];
  398. } else {
  399. // Modify query only at index
  400. nextQueries = queries.map((q, i) => {
  401. // Synchronise all queries with local query cache to ensure consistency
  402. q.query = this.queryExpressions[i];
  403. return i === index
  404. ? {
  405. key: generateQueryKey(index),
  406. query: datasource.modifyQuery(q.query, action),
  407. }
  408. : q;
  409. });
  410. nextQueryTransactions = queryTransactions
  411. // Consume the hint corresponding to the action
  412. .map(qt => {
  413. if (qt.hints != null && qt.rowIndex === index) {
  414. qt.hints = qt.hints.filter(hint => hint.fix.action !== action);
  415. }
  416. return qt;
  417. })
  418. // Preserve previous row query transaction to keep results visible if next query is incomplete
  419. .filter(qt => preventSubmit || qt.rowIndex !== index);
  420. }
  421. this.queryExpressions = nextQueries.map(q => q.query);
  422. return {
  423. queries: nextQueries,
  424. queryTransactions: nextQueryTransactions,
  425. };
  426. },
  427. // Accepting certain fixes do not result in a well-formed query which should not be submitted
  428. !preventSubmit ? () => this.onSubmit() : null
  429. );
  430. }
  431. };
  432. onRemoveQueryRow = index => {
  433. // Remove from local cache
  434. this.queryExpressions = [...this.queryExpressions.slice(0, index), ...this.queryExpressions.slice(index + 1)];
  435. this.setState(
  436. state => {
  437. const { queries, queryTransactions } = state;
  438. if (queries.length <= 1) {
  439. return null;
  440. }
  441. // Remove row from react state
  442. const nextQueries = [...queries.slice(0, index), ...queries.slice(index + 1)];
  443. // Discard transactions related to row query
  444. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  445. return {
  446. queries: nextQueries,
  447. queryTransactions: nextQueryTransactions,
  448. };
  449. },
  450. () => this.onSubmit()
  451. );
  452. };
  453. onSubmit = () => {
  454. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  455. if (showingTable && supportsTable) {
  456. this.runTableQuery();
  457. }
  458. if (showingGraph && supportsGraph) {
  459. this.runGraphQueries();
  460. }
  461. if (showingLogs && supportsLogs) {
  462. this.runLogsQuery();
  463. }
  464. this.saveState();
  465. };
  466. buildQueryOptions(
  467. query: string,
  468. rowIndex: number,
  469. targetOptions: { format: string; hinting?: boolean; instant?: boolean }
  470. ) {
  471. const { datasource, range } = this.state;
  472. const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth);
  473. const targets = [
  474. {
  475. ...targetOptions,
  476. // Target identifier is needed for table transformations
  477. refId: rowIndex + 1,
  478. expr: query,
  479. },
  480. ];
  481. // Clone range for query request
  482. const queryRange: RawTimeRange = { ...range };
  483. return {
  484. interval,
  485. intervalMs,
  486. targets,
  487. range: queryRange,
  488. };
  489. }
  490. startQueryTransaction(query: string, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  491. const queryOptions = this.buildQueryOptions(query, rowIndex, options);
  492. const transaction: QueryTransaction = {
  493. query,
  494. resultType,
  495. rowIndex,
  496. id: generateQueryKey(),
  497. done: false,
  498. latency: 0,
  499. options: queryOptions,
  500. };
  501. // Using updater style because we might be modifying queryTransactions in quick succession
  502. this.setState(state => {
  503. const { queryTransactions } = state;
  504. // Discarding existing transactions of same type
  505. const remainingTransactions = queryTransactions.filter(
  506. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  507. );
  508. // Append new transaction
  509. const nextQueryTransactions = [...remainingTransactions, transaction];
  510. return {
  511. queryTransactions: nextQueryTransactions,
  512. showingStartPage: false,
  513. };
  514. });
  515. return transaction;
  516. }
  517. completeQueryTransaction(
  518. transactionId: string,
  519. result: any,
  520. latency: number,
  521. queries: string[],
  522. datasourceId: string
  523. ) {
  524. const { datasource } = this.state;
  525. if (datasource.meta.id !== datasourceId) {
  526. // Navigated away, queries did not matter
  527. return;
  528. }
  529. this.setState(state => {
  530. const { history, queryTransactions } = state;
  531. // Transaction might have been discarded
  532. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  533. if (!transaction) {
  534. return null;
  535. }
  536. // Get query hints
  537. let hints;
  538. if (datasource.getQueryHints) {
  539. hints = datasource.getQueryHints(transaction.query, result);
  540. }
  541. // Mark transactions as complete
  542. const nextQueryTransactions = queryTransactions.map(qt => {
  543. if (qt.id === transactionId) {
  544. return {
  545. ...qt,
  546. hints,
  547. latency,
  548. result,
  549. done: true,
  550. };
  551. }
  552. return qt;
  553. });
  554. const nextHistory = updateHistory(history, datasourceId, queries);
  555. return {
  556. history: nextHistory,
  557. queryTransactions: nextQueryTransactions,
  558. };
  559. });
  560. }
  561. discardTransactions(rowIndex: number) {
  562. this.setState(state => {
  563. const remainingTransactions = state.queryTransactions.filter(qt => qt.rowIndex !== rowIndex);
  564. return { queryTransactions: remainingTransactions };
  565. });
  566. }
  567. failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
  568. const { datasource } = this.state;
  569. if (datasource.meta.id !== datasourceId) {
  570. // Navigated away, queries did not matter
  571. return;
  572. }
  573. console.error(response);
  574. let error: string | JSX.Element = response;
  575. if (response.data) {
  576. error = response.data.error;
  577. if (response.data.response) {
  578. error = (
  579. <>
  580. <span>{response.data.error}</span>
  581. <details>{response.data.response}</details>
  582. </>
  583. );
  584. }
  585. }
  586. this.setState(state => {
  587. // Transaction might have been discarded
  588. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  589. return null;
  590. }
  591. // Mark transactions as complete
  592. const nextQueryTransactions = state.queryTransactions.map(qt => {
  593. if (qt.id === transactionId) {
  594. return {
  595. ...qt,
  596. error,
  597. done: true,
  598. };
  599. }
  600. return qt;
  601. });
  602. return {
  603. queryTransactions: nextQueryTransactions,
  604. };
  605. });
  606. }
  607. async runGraphQueries() {
  608. const queries = [...this.queryExpressions];
  609. if (!hasQuery(queries)) {
  610. return;
  611. }
  612. const { datasource } = this.state;
  613. const datasourceId = datasource.meta.id;
  614. // Run all queries concurrently
  615. queries.forEach(async (query, rowIndex) => {
  616. if (query) {
  617. const transaction = this.startQueryTransaction(query, rowIndex, 'Graph', {
  618. format: 'time_series',
  619. instant: false,
  620. });
  621. try {
  622. const now = Date.now();
  623. const res = await datasource.query(transaction.options);
  624. const latency = Date.now() - now;
  625. const results = makeTimeSeriesList(res.data, transaction.options);
  626. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  627. this.setState({ graphRange: transaction.options.range });
  628. } catch (response) {
  629. this.failQueryTransaction(transaction.id, response, datasourceId);
  630. }
  631. } else {
  632. this.discardTransactions(rowIndex);
  633. }
  634. });
  635. }
  636. async runTableQuery() {
  637. const queries = [...this.queryExpressions];
  638. if (!hasQuery(queries)) {
  639. return;
  640. }
  641. const { datasource } = this.state;
  642. const datasourceId = datasource.meta.id;
  643. // Run all queries concurrently
  644. queries.forEach(async (query, rowIndex) => {
  645. if (query) {
  646. const transaction = this.startQueryTransaction(query, rowIndex, 'Table', {
  647. format: 'table',
  648. instant: true,
  649. valueWithRefId: true,
  650. });
  651. try {
  652. const now = Date.now();
  653. const res = await datasource.query(transaction.options);
  654. const latency = Date.now() - now;
  655. const results = res.data[0];
  656. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  657. } catch (response) {
  658. this.failQueryTransaction(transaction.id, response, datasourceId);
  659. }
  660. } else {
  661. this.discardTransactions(rowIndex);
  662. }
  663. });
  664. }
  665. async runLogsQuery() {
  666. const queries = [...this.queryExpressions];
  667. if (!hasQuery(queries)) {
  668. return;
  669. }
  670. const { datasource } = this.state;
  671. const datasourceId = datasource.meta.id;
  672. // Run all queries concurrently
  673. queries.forEach(async (query, rowIndex) => {
  674. if (query) {
  675. const transaction = this.startQueryTransaction(query, rowIndex, 'Logs', { format: 'logs' });
  676. try {
  677. const now = Date.now();
  678. const res = await datasource.query(transaction.options);
  679. const latency = Date.now() - now;
  680. const results = res.data;
  681. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  682. } catch (response) {
  683. this.failQueryTransaction(transaction.id, response, datasourceId);
  684. }
  685. } else {
  686. this.discardTransactions(rowIndex);
  687. }
  688. });
  689. }
  690. cloneState(): ExploreState {
  691. // Copy state, but copy queries including modifications
  692. return {
  693. ...this.state,
  694. queryTransactions: [],
  695. queries: ensureQueries(this.queryExpressions.map(query => ({ query }))),
  696. };
  697. }
  698. saveState = () => {
  699. const { stateKey, onSaveState } = this.props;
  700. onSaveState(stateKey, this.cloneState());
  701. };
  702. render() {
  703. const { position, split } = this.props;
  704. const {
  705. StartPage,
  706. datasource,
  707. datasourceError,
  708. datasourceLoading,
  709. datasourceMissing,
  710. exploreDatasources,
  711. graphRange,
  712. history,
  713. queries,
  714. queryTransactions,
  715. range,
  716. showingGraph,
  717. showingLogs,
  718. showingStartPage,
  719. showingTable,
  720. supportsGraph,
  721. supportsLogs,
  722. supportsTable,
  723. } = this.state;
  724. const graphHeight = showingGraph && showingTable ? '200px' : '400px';
  725. const exploreClass = split ? 'explore explore-split' : 'explore';
  726. const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
  727. const graphRangeIntervals = getIntervals(graphRange, datasource, this.el ? this.el.offsetWidth : 0);
  728. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  729. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  730. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  731. // TODO don't recreate those on each re-render
  732. const graphResult = _.flatten(
  733. queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result)
  734. );
  735. const tableResult = mergeTablesIntoModel(
  736. new TableModel(),
  737. ...queryTransactions.filter(qt => qt.resultType === 'Table' && qt.done && qt.result).map(qt => qt.result)
  738. );
  739. const logsResult =
  740. datasource && datasource.mergeStreams
  741. ? datasource.mergeStreams(
  742. _.flatten(
  743. queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done && qt.result).map(qt => qt.result)
  744. ),
  745. graphRangeIntervals.intervalMs
  746. )
  747. : undefined;
  748. const loading = queryTransactions.some(qt => !qt.done);
  749. return (
  750. <div className={exploreClass} ref={this.getRef}>
  751. <div className="navbar">
  752. {position === 'left' ? (
  753. <div>
  754. <a className="navbar-page-btn">
  755. <i className="fa fa-rocket" />
  756. Explore
  757. </a>
  758. </div>
  759. ) : (
  760. <div className="navbar-buttons explore-first-button">
  761. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  762. Close Split
  763. </button>
  764. </div>
  765. )}
  766. {!datasourceMissing ? (
  767. <div className="navbar-buttons">
  768. <Select
  769. classNamePrefix={`gf-form-select-box`}
  770. isMulti={false}
  771. isLoading={datasourceLoading}
  772. isClearable={false}
  773. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  774. onChange={this.onChangeDatasource}
  775. options={exploreDatasources}
  776. styles={ResetStyles}
  777. placeholder="Select datasource"
  778. loadingMessage={() => 'Loading datasources...'}
  779. noOptionsMessage={() => 'No datasources found'}
  780. value={selectedDatasource}
  781. components={{
  782. Option: PickerOption,
  783. IndicatorsContainer,
  784. NoOptionsMessage,
  785. }}
  786. />
  787. </div>
  788. ) : null}
  789. <div className="navbar__spacer" />
  790. {position === 'left' && !split ? (
  791. <div className="navbar-buttons">
  792. <button className="btn navbar-button" onClick={this.onClickSplit}>
  793. Split
  794. </button>
  795. </div>
  796. ) : null}
  797. <TimePicker range={range} onChangeTime={this.onChangeTime} />
  798. <div className="navbar-buttons">
  799. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  800. Clear All
  801. </button>
  802. </div>
  803. <div className="navbar-buttons relative">
  804. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  805. Run Query{' '}
  806. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  807. </button>
  808. </div>
  809. </div>
  810. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  811. {datasourceMissing ? (
  812. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  813. ) : null}
  814. {datasourceError ? (
  815. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  816. ) : null}
  817. {datasource && !datasourceError ? (
  818. <div className="explore-container">
  819. <QueryRows
  820. datasource={datasource}
  821. history={history}
  822. queries={queries}
  823. onAddQueryRow={this.onAddQueryRow}
  824. onChangeQuery={this.onChangeQuery}
  825. onClickHintFix={this.onModifyQueries}
  826. onExecuteQuery={this.onSubmit}
  827. onRemoveQueryRow={this.onRemoveQueryRow}
  828. transactions={queryTransactions}
  829. />
  830. <main className="m-t-2">
  831. <ErrorBoundary>
  832. {showingStartPage && <StartPage onClickQuery={this.onClickQuery} />}
  833. {!showingStartPage && (
  834. <>
  835. {supportsGraph && (
  836. <Panel
  837. label="Graph"
  838. isOpen={showingGraph}
  839. loading={graphLoading}
  840. onToggle={this.onClickGraphButton}
  841. >
  842. <Graph
  843. data={graphResult}
  844. height={graphHeight}
  845. id={`explore-graph-${position}`}
  846. onChangeTime={this.onChangeTime}
  847. range={graphRange}
  848. split={split}
  849. />
  850. </Panel>
  851. )}
  852. {supportsTable && (
  853. <Panel
  854. label="Table"
  855. loading={tableLoading}
  856. isOpen={showingTable}
  857. onToggle={this.onClickTableButton}
  858. >
  859. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickTableCell} />
  860. </Panel>
  861. )}
  862. {supportsLogs && (
  863. <Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
  864. <Logs
  865. data={logsResult}
  866. loading={logsLoading}
  867. position={position}
  868. onChangeTime={this.onChangeTime}
  869. range={range}
  870. />
  871. </Panel>
  872. )}
  873. </>
  874. )}
  875. </ErrorBoundary>
  876. </main>
  877. </div>
  878. ) : null}
  879. </div>
  880. );
  881. }
  882. }
  883. export default hot(module)(Explore);