Explore.tsx 31 KB

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