Explore.tsx 30 KB

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