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 {
  6. ExploreState,
  7. ExploreUrlState,
  8. HistoryItem,
  9. Query,
  10. QueryTransaction,
  11. Range,
  12. ResultType,
  13. } from 'app/types/explore';
  14. import kbn from 'app/core/utils/kbn';
  15. import colors from 'app/core/utils/colors';
  16. import store from 'app/core/store';
  17. import TimeSeries from 'app/core/time_series2';
  18. import { parse as parseDate } from 'app/core/utils/datemath';
  19. import { DEFAULT_RANGE } from 'app/core/utils/explore';
  20. import ResetStyles from 'app/core/components/Picker/ResetStyles';
  21. import PickerOption from 'app/core/components/Picker/PickerOption';
  22. import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer';
  23. import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage';
  24. import TableModel, { mergeTablesIntoModel } from 'app/core/table_model';
  25. import QueryRows from './QueryRows';
  26. import Graph from './Graph';
  27. import Logs from './Logs';
  28. import Table from './Table';
  29. import TimePicker from './TimePicker';
  30. import { ensureQueries, generateQueryKey, hasQuery } from './utils/query';
  31. const MAX_HISTORY_ITEMS = 100;
  32. function makeTimeSeriesList(dataList, options) {
  33. return dataList.map((seriesData, index) => {
  34. const datapoints = seriesData.datapoints || [];
  35. const alias = seriesData.target;
  36. const colorIndex = index % colors.length;
  37. const color = colors[colorIndex];
  38. const series = new TimeSeries({
  39. datapoints,
  40. alias,
  41. color,
  42. unit: seriesData.unit,
  43. });
  44. return series;
  45. });
  46. }
  47. /**
  48. * Update the query history. Side-effect: store history in local storage
  49. */
  50. function updateHistory(history: HistoryItem[], datasourceId: string, queries: string[]): HistoryItem[] {
  51. const ts = Date.now();
  52. queries.forEach(query => {
  53. history = [{ query, ts }, ...history];
  54. });
  55. if (history.length > MAX_HISTORY_ITEMS) {
  56. history = history.slice(0, MAX_HISTORY_ITEMS);
  57. }
  58. // Combine all queries of a datasource type into one history
  59. const historyKey = `grafana.explore.history.${datasourceId}`;
  60. store.setObject(historyKey, history);
  61. return history;
  62. }
  63. interface ExploreProps {
  64. datasourceSrv: any;
  65. onChangeSplit: (split: boolean, state?: ExploreState) => void;
  66. onSaveState: (key: string, state: ExploreState) => void;
  67. position: string;
  68. split: boolean;
  69. splitState?: ExploreState;
  70. stateKey: string;
  71. urlState: ExploreUrlState;
  72. }
  73. export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
  74. el: any;
  75. /**
  76. * Current query expressions of the rows including their modifications, used for running queries.
  77. * Not kept in component state to prevent edit-render roundtrips.
  78. */
  79. queryExpressions: string[];
  80. constructor(props) {
  81. super(props);
  82. const splitState: ExploreState = props.splitState;
  83. let initialQueries: Query[];
  84. if (splitState) {
  85. // Split state overrides everything
  86. this.state = splitState;
  87. initialQueries = splitState.queries;
  88. } else {
  89. const { datasource, queries, range } = props.urlState as ExploreUrlState;
  90. initialQueries = ensureQueries(queries);
  91. const initialRange = range || { ...DEFAULT_RANGE };
  92. this.state = {
  93. datasource: null,
  94. datasourceError: null,
  95. datasourceLoading: null,
  96. datasourceMissing: false,
  97. datasourceName: datasource,
  98. exploreDatasources: [],
  99. graphRange: initialRange,
  100. history: [],
  101. queries: initialQueries,
  102. queryTransactions: [],
  103. range: initialRange,
  104. showingGraph: true,
  105. showingLogs: true,
  106. showingTable: true,
  107. supportsGraph: null,
  108. supportsLogs: null,
  109. supportsTable: null,
  110. };
  111. }
  112. this.queryExpressions = initialQueries.map(q => q.query);
  113. }
  114. async componentDidMount() {
  115. const { datasourceSrv } = this.props;
  116. const { datasourceName } = this.state;
  117. if (!datasourceSrv) {
  118. throw new Error('No datasource service passed as props.');
  119. }
  120. const datasources = datasourceSrv.getExploreSources();
  121. const exploreDatasources = datasources.map(ds => ({
  122. value: ds.name,
  123. label: ds.name,
  124. }));
  125. if (datasources.length > 0) {
  126. this.setState({ datasourceLoading: true, exploreDatasources });
  127. // Priority: datasource in url, default datasource, first explore datasource
  128. let datasource;
  129. if (datasourceName) {
  130. datasource = await datasourceSrv.get(datasourceName);
  131. } else {
  132. datasource = await datasourceSrv.get();
  133. }
  134. if (!datasource.meta.explore) {
  135. datasource = await datasourceSrv.get(datasources[0].name);
  136. }
  137. await this.setDatasource(datasource);
  138. } else {
  139. this.setState({ datasourceMissing: true });
  140. }
  141. }
  142. componentDidCatch(error) {
  143. this.setState({ datasourceError: error });
  144. console.error(error);
  145. }
  146. async setDatasource(datasource) {
  147. const supportsGraph = datasource.meta.metrics;
  148. const supportsLogs = datasource.meta.logs;
  149. const supportsTable = datasource.meta.metrics;
  150. const datasourceId = datasource.meta.id;
  151. let datasourceError = null;
  152. try {
  153. const testResult = await datasource.testDatasource();
  154. datasourceError = testResult.status === 'success' ? null : testResult.message;
  155. } catch (error) {
  156. datasourceError = (error && error.statusText) || error;
  157. }
  158. const historyKey = `grafana.explore.history.${datasourceId}`;
  159. const history = store.getObject(historyKey, []);
  160. if (datasource.init) {
  161. datasource.init();
  162. }
  163. // Keep queries but reset edit state
  164. const nextQueries = this.state.queries.map((q, i) => ({
  165. ...q,
  166. key: generateQueryKey(i),
  167. query: this.queryExpressions[i],
  168. }));
  169. this.setState(
  170. {
  171. datasource,
  172. datasourceError,
  173. history,
  174. supportsGraph,
  175. supportsLogs,
  176. supportsTable,
  177. datasourceLoading: false,
  178. datasourceName: datasource.name,
  179. queries: nextQueries,
  180. },
  181. () => {
  182. if (datasourceError === null) {
  183. this.onSubmit();
  184. }
  185. }
  186. );
  187. }
  188. getRef = el => {
  189. this.el = el;
  190. };
  191. onAddQueryRow = index => {
  192. // Local cache
  193. this.queryExpressions[index + 1] = '';
  194. this.setState(state => {
  195. const { queries, queryTransactions } = state;
  196. // Add row by generating new react key
  197. const nextQueries = [
  198. ...queries.slice(0, index + 1),
  199. { query: '', key: generateQueryKey() },
  200. ...queries.slice(index + 1),
  201. ];
  202. // Ongoing transactions need to update their row indices
  203. const nextQueryTransactions = queryTransactions.map(qt => {
  204. if (qt.rowIndex > index) {
  205. return {
  206. ...qt,
  207. rowIndex: qt.rowIndex + 1,
  208. };
  209. }
  210. return qt;
  211. });
  212. return { queries: nextQueries, queryTransactions: nextQueryTransactions };
  213. });
  214. };
  215. onChangeDatasource = async option => {
  216. this.setState({
  217. datasource: null,
  218. datasourceError: null,
  219. datasourceLoading: true,
  220. queryTransactions: [],
  221. });
  222. const datasourceName = option.value;
  223. const datasource = await this.props.datasourceSrv.get(datasourceName);
  224. this.setDatasource(datasource);
  225. };
  226. onChangeQuery = (value: string, index: number, override?: boolean) => {
  227. // Keep current value in local cache
  228. this.queryExpressions[index] = value;
  229. if (override) {
  230. this.setState(state => {
  231. // Replace query row
  232. const { queries, queryTransactions } = state;
  233. const nextQuery: Query = {
  234. key: generateQueryKey(index),
  235. query: value,
  236. };
  237. const nextQueries = [...queries];
  238. nextQueries[index] = nextQuery;
  239. // Discard ongoing transaction related to row query
  240. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  241. return {
  242. queries: nextQueries,
  243. queryTransactions: nextQueryTransactions,
  244. };
  245. }, this.onSubmit);
  246. }
  247. };
  248. onChangeTime = nextRange => {
  249. const range = {
  250. from: nextRange.from,
  251. to: nextRange.to,
  252. };
  253. this.setState({ range }, () => this.onSubmit());
  254. };
  255. onClickClear = () => {
  256. this.queryExpressions = [''];
  257. this.setState(
  258. {
  259. queries: ensureQueries(),
  260. queryTransactions: [],
  261. },
  262. this.saveState
  263. );
  264. };
  265. onClickCloseSplit = () => {
  266. const { onChangeSplit } = this.props;
  267. if (onChangeSplit) {
  268. onChangeSplit(false);
  269. }
  270. };
  271. onClickGraphButton = () => {
  272. this.setState(
  273. state => {
  274. const showingGraph = !state.showingGraph;
  275. let nextQueryTransactions = state.queryTransactions;
  276. if (!showingGraph) {
  277. // Discard transactions related to Graph query
  278. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph');
  279. }
  280. return { queryTransactions: nextQueryTransactions, showingGraph };
  281. },
  282. () => {
  283. if (this.state.showingGraph) {
  284. this.onSubmit();
  285. }
  286. }
  287. );
  288. };
  289. onClickLogsButton = () => {
  290. this.setState(
  291. state => {
  292. const showingLogs = !state.showingLogs;
  293. let nextQueryTransactions = state.queryTransactions;
  294. if (!showingLogs) {
  295. // Discard transactions related to Logs query
  296. nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs');
  297. }
  298. return { queryTransactions: nextQueryTransactions, showingLogs };
  299. },
  300. () => {
  301. if (this.state.showingLogs) {
  302. this.onSubmit();
  303. }
  304. }
  305. );
  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 = {
  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: Range = { ...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, error: string, datasourceId: string) {
  525. const { datasource } = this.state;
  526. if (datasource.meta.id !== datasourceId) {
  527. // Navigated away, queries did not matter
  528. return;
  529. }
  530. this.setState(state => {
  531. // Transaction might have been discarded
  532. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  533. return null;
  534. }
  535. // Mark transactions as complete
  536. const nextQueryTransactions = state.queryTransactions.map(qt => {
  537. if (qt.id === transactionId) {
  538. return {
  539. ...qt,
  540. error,
  541. done: true,
  542. };
  543. }
  544. return qt;
  545. });
  546. return {
  547. queryTransactions: nextQueryTransactions,
  548. };
  549. });
  550. }
  551. async runGraphQueries() {
  552. const queries = [...this.queryExpressions];
  553. if (!hasQuery(queries)) {
  554. return;
  555. }
  556. const { datasource } = this.state;
  557. const datasourceId = datasource.meta.id;
  558. // Run all queries concurrently
  559. queries.forEach(async (query, rowIndex) => {
  560. if (query) {
  561. const transaction = this.startQueryTransaction(query, rowIndex, 'Graph', {
  562. format: 'time_series',
  563. instant: false,
  564. });
  565. try {
  566. const now = Date.now();
  567. const res = await datasource.query(transaction.options);
  568. const latency = Date.now() - now;
  569. const results = makeTimeSeriesList(res.data, transaction.options);
  570. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  571. this.setState({ graphRange: transaction.options.range });
  572. } catch (response) {
  573. console.error(response);
  574. const queryError = response.data ? response.data.error : response;
  575. this.failQueryTransaction(transaction.id, queryError, 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. console.error(response);
  605. const queryError = response.data ? response.data.error : response;
  606. this.failQueryTransaction(transaction.id, queryError, datasourceId);
  607. }
  608. } else {
  609. this.discardTransactions(rowIndex);
  610. }
  611. });
  612. }
  613. async runLogsQuery() {
  614. const queries = [...this.queryExpressions];
  615. if (!hasQuery(queries)) {
  616. return;
  617. }
  618. const { datasource } = this.state;
  619. const datasourceId = datasource.meta.id;
  620. // Run all queries concurrently
  621. queries.forEach(async (query, rowIndex) => {
  622. if (query) {
  623. const transaction = this.startQueryTransaction(query, rowIndex, 'Logs', { format: 'logs' });
  624. try {
  625. const now = Date.now();
  626. const res = await datasource.query(transaction.options);
  627. const latency = Date.now() - now;
  628. const results = res.data;
  629. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  630. } catch (response) {
  631. console.error(response);
  632. const queryError = response.data ? response.data.error : response;
  633. this.failQueryTransaction(transaction.id, queryError, datasourceId);
  634. }
  635. } else {
  636. this.discardTransactions(rowIndex);
  637. }
  638. });
  639. }
  640. cloneState(): ExploreState {
  641. // Copy state, but copy queries including modifications
  642. return {
  643. ...this.state,
  644. queryTransactions: [],
  645. queries: ensureQueries(this.queryExpressions.map(query => ({ query }))),
  646. };
  647. }
  648. saveState = () => {
  649. const { stateKey, onSaveState } = this.props;
  650. onSaveState(stateKey, this.cloneState());
  651. };
  652. render() {
  653. const { position, split } = this.props;
  654. const {
  655. datasource,
  656. datasourceError,
  657. datasourceLoading,
  658. datasourceMissing,
  659. exploreDatasources,
  660. graphRange,
  661. history,
  662. queries,
  663. queryTransactions,
  664. range,
  665. showingGraph,
  666. showingLogs,
  667. showingTable,
  668. supportsGraph,
  669. supportsLogs,
  670. supportsTable,
  671. } = this.state;
  672. const showingBoth = showingGraph && showingTable;
  673. const graphHeight = showingBoth ? '200px' : '400px';
  674. const graphButtonActive = showingBoth || showingGraph ? 'active' : '';
  675. const logsButtonActive = showingLogs ? 'active' : '';
  676. const tableButtonActive = showingBoth || showingTable ? 'active' : '';
  677. const exploreClass = split ? 'explore explore-split' : 'explore';
  678. const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
  679. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  680. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  681. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  682. const graphResult = _.flatten(
  683. queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result)
  684. );
  685. const tableResult = mergeTablesIntoModel(
  686. new TableModel(),
  687. ...queryTransactions.filter(qt => qt.resultType === 'Table' && qt.done).map(qt => qt.result)
  688. );
  689. const logsResult = _.flatten(
  690. queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done).map(qt => qt.result)
  691. );
  692. const loading = queryTransactions.some(qt => !qt.done);
  693. return (
  694. <div className={exploreClass} ref={this.getRef}>
  695. <div className="navbar">
  696. {position === 'left' ? (
  697. <div>
  698. <a className="navbar-page-btn">
  699. <i className="fa fa-rocket" />
  700. Explore
  701. </a>
  702. </div>
  703. ) : (
  704. <div className="navbar-buttons explore-first-button">
  705. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  706. Close Split
  707. </button>
  708. </div>
  709. )}
  710. {!datasourceMissing ? (
  711. <div className="navbar-buttons">
  712. <Select
  713. classNamePrefix={`gf-form-select-box`}
  714. isMulti={false}
  715. isLoading={datasourceLoading}
  716. isClearable={false}
  717. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  718. onChange={this.onChangeDatasource}
  719. options={exploreDatasources}
  720. styles={ResetStyles}
  721. placeholder="Select datasource"
  722. loadingMessage={() => 'Loading datasources...'}
  723. noOptionsMessage={() => 'No datasources found'}
  724. value={selectedDatasource}
  725. components={{
  726. Option: PickerOption,
  727. IndicatorsContainer,
  728. NoOptionsMessage,
  729. }}
  730. />
  731. </div>
  732. ) : null}
  733. <div className="navbar__spacer" />
  734. {position === 'left' && !split ? (
  735. <div className="navbar-buttons">
  736. <button className="btn navbar-button" onClick={this.onClickSplit}>
  737. Split
  738. </button>
  739. </div>
  740. ) : null}
  741. <TimePicker range={range} onChangeTime={this.onChangeTime} />
  742. <div className="navbar-buttons">
  743. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  744. Clear All
  745. </button>
  746. </div>
  747. <div className="navbar-buttons relative">
  748. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  749. Run Query{' '}
  750. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  751. </button>
  752. </div>
  753. </div>
  754. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  755. {datasourceMissing ? (
  756. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  757. ) : null}
  758. {datasourceError ? (
  759. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  760. ) : null}
  761. {datasource && !datasourceError ? (
  762. <div className="explore-container">
  763. <QueryRows
  764. datasource={datasource}
  765. history={history}
  766. queries={queries}
  767. onAddQueryRow={this.onAddQueryRow}
  768. onChangeQuery={this.onChangeQuery}
  769. onClickHintFix={this.onModifyQueries}
  770. onExecuteQuery={this.onSubmit}
  771. onRemoveQueryRow={this.onRemoveQueryRow}
  772. supportsLogs={supportsLogs}
  773. transactions={queryTransactions}
  774. />
  775. <div className="result-options">
  776. {supportsGraph ? (
  777. <button className={`btn toggle-btn ${graphButtonActive}`} onClick={this.onClickGraphButton}>
  778. Graph
  779. </button>
  780. ) : null}
  781. {supportsTable ? (
  782. <button className={`btn toggle-btn ${tableButtonActive}`} onClick={this.onClickTableButton}>
  783. Table
  784. </button>
  785. ) : null}
  786. {supportsLogs ? (
  787. <button className={`btn toggle-btn ${logsButtonActive}`} onClick={this.onClickLogsButton}>
  788. Logs
  789. </button>
  790. ) : null}
  791. </div>
  792. <main className="m-t-2">
  793. {supportsGraph &&
  794. showingGraph && (
  795. <Graph
  796. data={graphResult}
  797. height={graphHeight}
  798. loading={graphLoading}
  799. id={`explore-graph-${position}`}
  800. range={graphRange}
  801. split={split}
  802. />
  803. )}
  804. {supportsTable && showingTable ? (
  805. <div className="panel-container m-t-2">
  806. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickTableCell} />
  807. </div>
  808. ) : null}
  809. {supportsLogs && showingLogs ? <Logs data={logsResult} loading={logsLoading} /> : null}
  810. </main>
  811. </div>
  812. ) : null}
  813. </div>
  814. );
  815. }
  816. }
  817. export default hot(module)(Explore);