Explore.tsx 29 KB

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