Explore.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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: object, index?: number) => {
  336. const { datasource } = this.state;
  337. if (datasource && datasource.modifyQuery) {
  338. this.setState(
  339. state => {
  340. const { queries, queryTransactions } = state;
  341. let nextQueries;
  342. let nextQueryTransactions;
  343. if (index === undefined) {
  344. // Modify all queries
  345. nextQueries = queries.map((q, i) => ({
  346. key: generateQueryKey(i),
  347. query: datasource.modifyQuery(this.queryExpressions[i], action),
  348. }));
  349. // Discard all ongoing transactions
  350. nextQueryTransactions = [];
  351. } else {
  352. // Modify query only at index
  353. nextQueries = [
  354. ...queries.slice(0, index),
  355. {
  356. key: generateQueryKey(index),
  357. query: datasource.modifyQuery(this.queryExpressions[index], action),
  358. },
  359. ...queries.slice(index + 1),
  360. ];
  361. // Discard transactions related to row query
  362. nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  363. }
  364. this.queryExpressions = nextQueries.map(q => q.query);
  365. return {
  366. queries: nextQueries,
  367. queryTransactions: nextQueryTransactions,
  368. };
  369. },
  370. () => this.onSubmit()
  371. );
  372. }
  373. };
  374. onRemoveQueryRow = index => {
  375. // Remove from local cache
  376. this.queryExpressions = [...this.queryExpressions.slice(0, index), ...this.queryExpressions.slice(index + 1)];
  377. this.setState(
  378. state => {
  379. const { queries, queryTransactions } = state;
  380. if (queries.length <= 1) {
  381. return null;
  382. }
  383. // Remove row from react state
  384. const nextQueries = [...queries.slice(0, index), ...queries.slice(index + 1)];
  385. // Discard transactions related to row query
  386. const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
  387. return {
  388. queries: nextQueries,
  389. queryTransactions: nextQueryTransactions,
  390. };
  391. },
  392. () => this.onSubmit()
  393. );
  394. };
  395. onSubmit = () => {
  396. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  397. if (showingTable && supportsTable) {
  398. this.runTableQuery();
  399. }
  400. if (showingGraph && supportsGraph) {
  401. this.runGraphQueries();
  402. }
  403. if (showingLogs && supportsLogs) {
  404. this.runLogsQuery();
  405. }
  406. this.saveState();
  407. };
  408. buildQueryOptions(
  409. query: string,
  410. rowIndex: number,
  411. targetOptions: { format: string; hinting?: boolean; instant?: boolean }
  412. ) {
  413. const { datasource, range } = this.state;
  414. const resolution = this.el.offsetWidth;
  415. const absoluteRange = {
  416. from: parseDate(range.from, false),
  417. to: parseDate(range.to, true),
  418. };
  419. const { interval } = kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  420. const targets = [
  421. {
  422. ...targetOptions,
  423. // Target identifier is needed for table transformations
  424. refId: rowIndex + 1,
  425. expr: query,
  426. },
  427. ];
  428. // Clone range for query request
  429. const queryRange: Range = { ...range };
  430. return {
  431. interval,
  432. targets,
  433. range: queryRange,
  434. };
  435. }
  436. startQueryTransaction(query: string, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
  437. const queryOptions = this.buildQueryOptions(query, rowIndex, options);
  438. const transaction: QueryTransaction = {
  439. query,
  440. resultType,
  441. rowIndex,
  442. id: generateQueryKey(),
  443. done: false,
  444. latency: 0,
  445. options: queryOptions,
  446. };
  447. // Using updater style because we might be modifying queryTransactions in quick succession
  448. this.setState(state => {
  449. const { queryTransactions } = state;
  450. // Discarding existing transactions of same type
  451. const remainingTransactions = queryTransactions.filter(
  452. qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
  453. );
  454. // Append new transaction
  455. const nextQueryTransactions = [...remainingTransactions, transaction];
  456. return {
  457. queryTransactions: nextQueryTransactions,
  458. };
  459. });
  460. return transaction;
  461. }
  462. completeQueryTransaction(
  463. transactionId: string,
  464. result: any,
  465. latency: number,
  466. queries: string[],
  467. datasourceId: string
  468. ) {
  469. const { datasource } = this.state;
  470. if (datasource.meta.id !== datasourceId) {
  471. // Navigated away, queries did not matter
  472. return;
  473. }
  474. this.setState(state => {
  475. const { history, queryTransactions } = state;
  476. // Transaction might have been discarded
  477. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  478. if (!transaction) {
  479. return null;
  480. }
  481. // Get query hints
  482. let hints;
  483. if (datasource.getQueryHints) {
  484. hints = datasource.getQueryHints(transaction.query, result);
  485. }
  486. // Mark transactions as complete
  487. const nextQueryTransactions = queryTransactions.map(qt => {
  488. if (qt.id === transactionId) {
  489. return {
  490. ...qt,
  491. hints,
  492. latency,
  493. result,
  494. done: true,
  495. };
  496. }
  497. return qt;
  498. });
  499. const nextHistory = updateHistory(history, datasourceId, queries);
  500. return {
  501. history: nextHistory,
  502. queryTransactions: nextQueryTransactions,
  503. };
  504. });
  505. }
  506. discardTransactions(rowIndex: number) {
  507. this.setState(state => {
  508. const remainingTransactions = state.queryTransactions.filter(qt => qt.rowIndex !== rowIndex);
  509. return { queryTransactions: remainingTransactions };
  510. });
  511. }
  512. failQueryTransaction(transactionId: string, error: string, datasourceId: string) {
  513. const { datasource } = this.state;
  514. if (datasource.meta.id !== datasourceId) {
  515. // Navigated away, queries did not matter
  516. return;
  517. }
  518. this.setState(state => {
  519. // Transaction might have been discarded
  520. if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
  521. return null;
  522. }
  523. // Mark transactions as complete
  524. const nextQueryTransactions = state.queryTransactions.map(qt => {
  525. if (qt.id === transactionId) {
  526. return {
  527. ...qt,
  528. error,
  529. done: true,
  530. };
  531. }
  532. return qt;
  533. });
  534. return {
  535. queryTransactions: nextQueryTransactions,
  536. };
  537. });
  538. }
  539. async runGraphQueries() {
  540. const queries = [...this.queryExpressions];
  541. if (!hasQuery(queries)) {
  542. return;
  543. }
  544. const { datasource } = this.state;
  545. const datasourceId = datasource.meta.id;
  546. // Run all queries concurrently
  547. queries.forEach(async (query, rowIndex) => {
  548. if (query) {
  549. const transaction = this.startQueryTransaction(query, rowIndex, 'Graph', {
  550. format: 'time_series',
  551. instant: false,
  552. });
  553. try {
  554. const now = Date.now();
  555. const res = await datasource.query(transaction.options);
  556. const latency = Date.now() - now;
  557. const results = makeTimeSeriesList(res.data, transaction.options);
  558. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  559. this.setState({ graphRange: transaction.options.range });
  560. } catch (response) {
  561. console.error(response);
  562. const queryError = response.data ? response.data.error : response;
  563. this.failQueryTransaction(transaction.id, queryError, datasourceId);
  564. }
  565. } else {
  566. this.discardTransactions(rowIndex);
  567. }
  568. });
  569. }
  570. async runTableQuery() {
  571. const queries = [...this.queryExpressions];
  572. if (!hasQuery(queries)) {
  573. return;
  574. }
  575. const { datasource } = this.state;
  576. const datasourceId = datasource.meta.id;
  577. // Run all queries concurrently
  578. queries.forEach(async (query, rowIndex) => {
  579. if (query) {
  580. const transaction = this.startQueryTransaction(query, rowIndex, 'Table', {
  581. format: 'table',
  582. instant: true,
  583. valueWithRefId: true,
  584. });
  585. try {
  586. const now = Date.now();
  587. const res = await datasource.query(transaction.options);
  588. const latency = Date.now() - now;
  589. const results = res.data[0];
  590. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  591. } catch (response) {
  592. console.error(response);
  593. const queryError = response.data ? response.data.error : response;
  594. this.failQueryTransaction(transaction.id, queryError, datasourceId);
  595. }
  596. } else {
  597. this.discardTransactions(rowIndex);
  598. }
  599. });
  600. }
  601. async runLogsQuery() {
  602. const queries = [...this.queryExpressions];
  603. if (!hasQuery(queries)) {
  604. return;
  605. }
  606. const { datasource } = this.state;
  607. const datasourceId = datasource.meta.id;
  608. // Run all queries concurrently
  609. queries.forEach(async (query, rowIndex) => {
  610. if (query) {
  611. const transaction = this.startQueryTransaction(query, rowIndex, 'Logs', { format: 'logs' });
  612. try {
  613. const now = Date.now();
  614. const res = await datasource.query(transaction.options);
  615. const latency = Date.now() - now;
  616. const results = res.data;
  617. this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
  618. } catch (response) {
  619. console.error(response);
  620. const queryError = response.data ? response.data.error : response;
  621. this.failQueryTransaction(transaction.id, queryError, datasourceId);
  622. }
  623. } else {
  624. this.discardTransactions(rowIndex);
  625. }
  626. });
  627. }
  628. request = url => {
  629. const { datasource } = this.state;
  630. return datasource.metadataRequest(url);
  631. };
  632. cloneState(): ExploreState {
  633. // Copy state, but copy queries including modifications
  634. return {
  635. ...this.state,
  636. queryTransactions: [],
  637. queries: ensureQueries(this.queryExpressions.map(query => ({ query }))),
  638. };
  639. }
  640. saveState = () => {
  641. const { stateKey, onSaveState } = this.props;
  642. onSaveState(stateKey, this.cloneState());
  643. };
  644. render() {
  645. const { position, split } = this.props;
  646. const {
  647. datasource,
  648. datasourceError,
  649. datasourceLoading,
  650. datasourceMissing,
  651. exploreDatasources,
  652. graphRange,
  653. history,
  654. queries,
  655. queryTransactions,
  656. range,
  657. showingGraph,
  658. showingLogs,
  659. showingTable,
  660. supportsGraph,
  661. supportsLogs,
  662. supportsTable,
  663. } = this.state;
  664. const showingBoth = showingGraph && showingTable;
  665. const graphHeight = showingBoth ? '200px' : '400px';
  666. const graphButtonActive = showingBoth || showingGraph ? 'active' : '';
  667. const logsButtonActive = showingLogs ? 'active' : '';
  668. const tableButtonActive = showingBoth || showingTable ? 'active' : '';
  669. const exploreClass = split ? 'explore explore-split' : 'explore';
  670. const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
  671. const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
  672. const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
  673. const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
  674. const graphResult = _.flatten(
  675. queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result)
  676. );
  677. const tableResult = mergeTablesIntoModel(
  678. new TableModel(),
  679. ...queryTransactions.filter(qt => qt.resultType === 'Table' && qt.done).map(qt => qt.result)
  680. );
  681. const logsResult = _.flatten(
  682. queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done).map(qt => qt.result)
  683. );
  684. const loading = queryTransactions.some(qt => !qt.done);
  685. return (
  686. <div className={exploreClass} ref={this.getRef}>
  687. <div className="navbar">
  688. {position === 'left' ? (
  689. <div>
  690. <a className="navbar-page-btn">
  691. <i className="fa fa-rocket" />
  692. Explore
  693. </a>
  694. </div>
  695. ) : (
  696. <div className="navbar-buttons explore-first-button">
  697. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  698. Close Split
  699. </button>
  700. </div>
  701. )}
  702. {!datasourceMissing ? (
  703. <div className="navbar-buttons">
  704. <Select
  705. classNamePrefix={`gf-form-select-box`}
  706. isMulti={false}
  707. isLoading={datasourceLoading}
  708. isClearable={false}
  709. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  710. onChange={this.onChangeDatasource}
  711. options={exploreDatasources}
  712. styles={ResetStyles}
  713. placeholder="Select datasource"
  714. loadingMessage={() => 'Loading datasources...'}
  715. noOptionsMessage={() => 'No datasources found'}
  716. value={selectedDatasource}
  717. components={{
  718. Option: PickerOption,
  719. IndicatorsContainer,
  720. NoOptionsMessage,
  721. }}
  722. />
  723. </div>
  724. ) : null}
  725. <div className="navbar__spacer" />
  726. {position === 'left' && !split ? (
  727. <div className="navbar-buttons">
  728. <button className="btn navbar-button" onClick={this.onClickSplit}>
  729. Split
  730. </button>
  731. </div>
  732. ) : null}
  733. <TimePicker range={range} onChangeTime={this.onChangeTime} />
  734. <div className="navbar-buttons">
  735. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  736. Clear All
  737. </button>
  738. </div>
  739. <div className="navbar-buttons relative">
  740. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  741. Run Query{' '}
  742. {loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
  743. </button>
  744. </div>
  745. </div>
  746. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  747. {datasourceMissing ? (
  748. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  749. ) : null}
  750. {datasourceError ? (
  751. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  752. ) : null}
  753. {datasource && !datasourceError ? (
  754. <div className="explore-container">
  755. <QueryRows
  756. history={history}
  757. queries={queries}
  758. request={this.request}
  759. onAddQueryRow={this.onAddQueryRow}
  760. onChangeQuery={this.onChangeQuery}
  761. onClickHintFix={this.onModifyQueries}
  762. onExecuteQuery={this.onSubmit}
  763. onRemoveQueryRow={this.onRemoveQueryRow}
  764. supportsLogs={supportsLogs}
  765. transactions={queryTransactions}
  766. />
  767. <div className="result-options">
  768. {supportsGraph ? (
  769. <button className={`btn toggle-btn ${graphButtonActive}`} onClick={this.onClickGraphButton}>
  770. Graph
  771. </button>
  772. ) : null}
  773. {supportsTable ? (
  774. <button className={`btn toggle-btn ${tableButtonActive}`} onClick={this.onClickTableButton}>
  775. Table
  776. </button>
  777. ) : null}
  778. {supportsLogs ? (
  779. <button className={`btn toggle-btn ${logsButtonActive}`} onClick={this.onClickLogsButton}>
  780. Logs
  781. </button>
  782. ) : null}
  783. </div>
  784. <main className="m-t-2">
  785. {supportsGraph &&
  786. showingGraph && (
  787. <Graph
  788. data={graphResult}
  789. height={graphHeight}
  790. loading={graphLoading}
  791. id={`explore-graph-${position}`}
  792. range={graphRange}
  793. split={split}
  794. />
  795. )}
  796. {supportsTable && showingTable ? (
  797. <div className="panel-container m-t-2">
  798. <Table data={tableResult} loading={tableLoading} onClickCell={this.onClickTableCell} />
  799. </div>
  800. ) : null}
  801. {supportsLogs && showingLogs ? <Logs data={logsResult} loading={logsLoading} /> : null}
  802. </main>
  803. </div>
  804. ) : null}
  805. </div>
  806. );
  807. }
  808. }
  809. export default hot(module)(Explore);