Explore.tsx 28 KB

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