Explore.tsx 30 KB

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