Explore.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. import React from 'react';
  2. import { hot } from 'react-hot-loader';
  3. import Select from 'react-select';
  4. import { ExploreState, ExploreUrlState, Query } from 'app/types/explore';
  5. import kbn from 'app/core/utils/kbn';
  6. import colors from 'app/core/utils/colors';
  7. import store from 'app/core/store';
  8. import TimeSeries from 'app/core/time_series2';
  9. import { parse as parseDate } from 'app/core/utils/datemath';
  10. import { DEFAULT_RANGE } from 'app/core/utils/explore';
  11. import ResetStyles from 'app/core/components/Picker/ResetStyles';
  12. import PickerOption from 'app/core/components/Picker/PickerOption';
  13. import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer';
  14. import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage';
  15. import ElapsedTime from './ElapsedTime';
  16. import QueryRows from './QueryRows';
  17. import Graph from './Graph';
  18. import Logs from './Logs';
  19. import Table from './Table';
  20. import TimePicker from './TimePicker';
  21. import { ensureQueries, generateQueryKey, hasQuery } from './utils/query';
  22. const MAX_HISTORY_ITEMS = 100;
  23. function makeHints(hints) {
  24. const hintsByIndex = [];
  25. hints.forEach(hint => {
  26. if (hint) {
  27. hintsByIndex[hint.index] = hint;
  28. }
  29. });
  30. return hintsByIndex;
  31. }
  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. interface ExploreProps {
  48. datasourceSrv: any;
  49. onChangeSplit: (split: boolean, state?: ExploreState) => void;
  50. onSaveState: (key: string, state: ExploreState) => void;
  51. position: string;
  52. split: boolean;
  53. splitState?: ExploreState;
  54. stateKey: string;
  55. urlState: ExploreUrlState;
  56. }
  57. export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
  58. el: any;
  59. /**
  60. * Current query expressions of the rows including their modifications, used for running queries.
  61. * Not kept in component state to prevent edit-render roundtrips.
  62. */
  63. queryExpressions: string[];
  64. constructor(props) {
  65. super(props);
  66. const splitState: ExploreState = props.splitState;
  67. let initialQueries: Query[];
  68. if (splitState) {
  69. // Split state overrides everything
  70. this.state = splitState;
  71. initialQueries = splitState.queries;
  72. } else {
  73. const { datasource, queries, range } = props.urlState as ExploreUrlState;
  74. initialQueries = ensureQueries(queries);
  75. this.state = {
  76. datasource: null,
  77. datasourceError: null,
  78. datasourceLoading: null,
  79. datasourceMissing: false,
  80. datasourceName: datasource,
  81. exploreDatasources: [],
  82. graphResult: null,
  83. history: [],
  84. latency: 0,
  85. loading: false,
  86. logsResult: null,
  87. queries: initialQueries,
  88. queryErrors: [],
  89. queryHints: [],
  90. range: range || { ...DEFAULT_RANGE },
  91. requestOptions: null,
  92. showingGraph: true,
  93. showingLogs: true,
  94. showingTable: true,
  95. supportsGraph: null,
  96. supportsLogs: null,
  97. supportsTable: null,
  98. tableResult: null,
  99. };
  100. }
  101. this.queryExpressions = initialQueries.map(q => q.query);
  102. }
  103. async componentDidMount() {
  104. const { datasourceSrv } = this.props;
  105. const { datasourceName } = this.state;
  106. if (!datasourceSrv) {
  107. throw new Error('No datasource service passed as props.');
  108. }
  109. const datasources = datasourceSrv.getExploreSources();
  110. const exploreDatasources = datasources.map(ds => ({
  111. value: ds.name,
  112. label: ds.name,
  113. }));
  114. if (datasources.length > 0) {
  115. this.setState({ datasourceLoading: true, exploreDatasources });
  116. // Priority: datasource in url, default datasource, first explore datasource
  117. let datasource;
  118. if (datasourceName) {
  119. datasource = await datasourceSrv.get(datasourceName);
  120. } else {
  121. datasource = await datasourceSrv.get();
  122. }
  123. if (!datasource.meta.explore) {
  124. datasource = await datasourceSrv.get(datasources[0].name);
  125. }
  126. await this.setDatasource(datasource);
  127. } else {
  128. this.setState({ datasourceMissing: true });
  129. }
  130. }
  131. componentDidCatch(error) {
  132. this.setState({ datasourceError: error });
  133. console.error(error);
  134. }
  135. async setDatasource(datasource) {
  136. const supportsGraph = datasource.meta.metrics;
  137. const supportsLogs = datasource.meta.logs;
  138. const supportsTable = datasource.meta.metrics;
  139. const datasourceId = datasource.meta.id;
  140. let datasourceError = null;
  141. try {
  142. const testResult = await datasource.testDatasource();
  143. datasourceError = testResult.status === 'success' ? null : testResult.message;
  144. } catch (error) {
  145. datasourceError = (error && error.statusText) || error;
  146. }
  147. const historyKey = `grafana.explore.history.${datasourceId}`;
  148. const history = store.getObject(historyKey, []);
  149. if (datasource.init) {
  150. datasource.init();
  151. }
  152. // Keep queries but reset edit state
  153. const nextQueries = this.state.queries.map((q, i) => ({
  154. ...q,
  155. key: generateQueryKey(i),
  156. query: this.queryExpressions[i],
  157. }));
  158. this.setState(
  159. {
  160. datasource,
  161. datasourceError,
  162. history,
  163. supportsGraph,
  164. supportsLogs,
  165. supportsTable,
  166. datasourceLoading: false,
  167. datasourceName: datasource.name,
  168. queries: nextQueries,
  169. },
  170. () => {
  171. if (datasourceError === null) {
  172. this.onSubmit();
  173. }
  174. }
  175. );
  176. }
  177. getRef = el => {
  178. this.el = el;
  179. };
  180. onAddQueryRow = index => {
  181. const { queries } = this.state;
  182. this.queryExpressions[index + 1] = '';
  183. const nextQueries = [
  184. ...queries.slice(0, index + 1),
  185. { query: '', key: generateQueryKey() },
  186. ...queries.slice(index + 1),
  187. ];
  188. this.setState({ queries: nextQueries });
  189. };
  190. onChangeDatasource = async option => {
  191. this.setState({
  192. datasource: null,
  193. datasourceError: null,
  194. datasourceLoading: true,
  195. graphResult: null,
  196. latency: 0,
  197. logsResult: null,
  198. queryErrors: [],
  199. queryHints: [],
  200. tableResult: null,
  201. });
  202. const datasourceName = option.value;
  203. const datasource = await this.props.datasourceSrv.get(datasourceName);
  204. this.setDatasource(datasource);
  205. };
  206. onChangeQuery = (value: string, index: number, override?: boolean) => {
  207. // Keep current value in local cache
  208. this.queryExpressions[index] = value;
  209. // Replace query row on override
  210. if (override) {
  211. const { queries } = this.state;
  212. const nextQuery: Query = {
  213. key: generateQueryKey(index),
  214. query: value,
  215. };
  216. const nextQueries = [...queries];
  217. nextQueries[index] = nextQuery;
  218. this.setState(
  219. {
  220. queryErrors: [],
  221. queryHints: [],
  222. queries: nextQueries,
  223. },
  224. this.onSubmit
  225. );
  226. }
  227. };
  228. onChangeTime = nextRange => {
  229. const range = {
  230. from: nextRange.from,
  231. to: nextRange.to,
  232. };
  233. this.setState({ range }, () => this.onSubmit());
  234. };
  235. onClickClear = () => {
  236. this.queryExpressions = [''];
  237. this.setState(
  238. {
  239. graphResult: null,
  240. logsResult: null,
  241. latency: 0,
  242. queries: ensureQueries(),
  243. queryErrors: [],
  244. queryHints: [],
  245. tableResult: null,
  246. },
  247. this.saveState
  248. );
  249. };
  250. onClickCloseSplit = () => {
  251. const { onChangeSplit } = this.props;
  252. if (onChangeSplit) {
  253. onChangeSplit(false);
  254. }
  255. };
  256. onClickGraphButton = () => {
  257. this.setState(state => ({ showingGraph: !state.showingGraph }));
  258. };
  259. onClickLogsButton = () => {
  260. this.setState(state => ({ showingLogs: !state.showingLogs }));
  261. };
  262. onClickSplit = () => {
  263. const { onChangeSplit } = this.props;
  264. if (onChangeSplit) {
  265. const state = this.cloneState();
  266. onChangeSplit(true, state);
  267. }
  268. };
  269. onClickTableButton = () => {
  270. this.setState(state => ({ showingTable: !state.showingTable }));
  271. };
  272. onClickTableCell = (columnKey: string, rowValue: string) => {
  273. this.onModifyQueries({ type: 'ADD_FILTER', key: columnKey, value: rowValue });
  274. };
  275. onModifyQueries = (action: object, index?: number) => {
  276. const { datasource, queries } = this.state;
  277. if (datasource && datasource.modifyQuery) {
  278. let nextQueries;
  279. if (index === undefined) {
  280. // Modify all queries
  281. nextQueries = queries.map((q, i) => ({
  282. key: generateQueryKey(i),
  283. query: datasource.modifyQuery(this.queryExpressions[i], action),
  284. }));
  285. } else {
  286. // Modify query only at index
  287. nextQueries = [
  288. ...queries.slice(0, index),
  289. {
  290. key: generateQueryKey(index),
  291. query: datasource.modifyQuery(this.queryExpressions[index], action),
  292. },
  293. ...queries.slice(index + 1),
  294. ];
  295. }
  296. this.queryExpressions = nextQueries.map(q => q.query);
  297. this.setState({ queries: nextQueries }, () => this.onSubmit());
  298. }
  299. };
  300. onRemoveQueryRow = index => {
  301. const { queries } = this.state;
  302. if (queries.length <= 1) {
  303. return;
  304. }
  305. const nextQueries = [...queries.slice(0, index), ...queries.slice(index + 1)];
  306. this.queryExpressions = nextQueries.map(q => q.query);
  307. this.setState({ queries: nextQueries }, () => this.onSubmit());
  308. };
  309. onSubmit = () => {
  310. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  311. if (showingTable && supportsTable) {
  312. this.runTableQuery();
  313. }
  314. if (showingGraph && supportsGraph) {
  315. this.runGraphQuery();
  316. }
  317. if (showingLogs && supportsLogs) {
  318. this.runLogsQuery();
  319. }
  320. this.saveState();
  321. };
  322. onQuerySuccess(datasourceId: string, queries: string[]): void {
  323. // save queries to history
  324. let { history } = this.state;
  325. const { datasource } = this.state;
  326. if (datasource.meta.id !== datasourceId) {
  327. // Navigated away, queries did not matter
  328. return;
  329. }
  330. const ts = Date.now();
  331. queries.forEach(query => {
  332. history = [{ query, ts }, ...history];
  333. });
  334. if (history.length > MAX_HISTORY_ITEMS) {
  335. history = history.slice(0, MAX_HISTORY_ITEMS);
  336. }
  337. // Combine all queries of a datasource type into one history
  338. const historyKey = `grafana.explore.history.${datasourceId}`;
  339. store.setObject(historyKey, history);
  340. this.setState({ history });
  341. }
  342. buildQueryOptions(targetOptions: { format: string; hinting?: boolean; instant?: boolean }) {
  343. const { datasource, range } = this.state;
  344. const resolution = this.el.offsetWidth;
  345. const absoluteRange = {
  346. from: parseDate(range.from, false),
  347. to: parseDate(range.to, true),
  348. };
  349. const { interval } = kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  350. const targets = this.queryExpressions.map(q => ({
  351. ...targetOptions,
  352. expr: q,
  353. }));
  354. return {
  355. interval,
  356. range,
  357. targets,
  358. };
  359. }
  360. async runGraphQuery() {
  361. const { datasource } = this.state;
  362. const queries = [...this.queryExpressions];
  363. if (!hasQuery(queries)) {
  364. return;
  365. }
  366. this.setState({ latency: 0, loading: true, graphResult: null, queryErrors: [], queryHints: [] });
  367. const now = Date.now();
  368. const options = this.buildQueryOptions({ format: 'time_series', instant: false, hinting: true });
  369. try {
  370. const res = await datasource.query(options);
  371. const result = makeTimeSeriesList(res.data, options);
  372. const queryHints = res.hints ? makeHints(res.hints) : [];
  373. const latency = Date.now() - now;
  374. this.setState({ latency, loading: false, graphResult: result, queryHints, requestOptions: options });
  375. this.onQuerySuccess(datasource.meta.id, queries);
  376. } catch (response) {
  377. console.error(response);
  378. const queryError = response.data ? response.data.error : response;
  379. this.setState({ loading: false, queryErrors: [queryError] });
  380. }
  381. }
  382. async runTableQuery() {
  383. const queries = [...this.queryExpressions];
  384. const { datasource } = this.state;
  385. if (!hasQuery(queries)) {
  386. return;
  387. }
  388. this.setState({ latency: 0, loading: true, queryErrors: [], queryHints: [], tableResult: null });
  389. const now = Date.now();
  390. const options = this.buildQueryOptions({
  391. format: 'table',
  392. instant: true,
  393. });
  394. try {
  395. const res = await datasource.query(options);
  396. const tableModel = res.data[0];
  397. const latency = Date.now() - now;
  398. this.setState({ latency, loading: false, tableResult: tableModel, requestOptions: options });
  399. this.onQuerySuccess(datasource.meta.id, queries);
  400. } catch (response) {
  401. console.error(response);
  402. const queryError = response.data ? response.data.error : response;
  403. this.setState({ loading: false, queryErrors: [queryError] });
  404. }
  405. }
  406. async runLogsQuery() {
  407. const queries = [...this.queryExpressions];
  408. const { datasource } = this.state;
  409. if (!hasQuery(queries)) {
  410. return;
  411. }
  412. this.setState({ latency: 0, loading: true, queryErrors: [], queryHints: [], logsResult: null });
  413. const now = Date.now();
  414. const options = this.buildQueryOptions({
  415. format: 'logs',
  416. });
  417. try {
  418. const res = await datasource.query(options);
  419. const logsData = res.data;
  420. const latency = Date.now() - now;
  421. this.setState({ latency, loading: false, logsResult: logsData, requestOptions: options });
  422. this.onQuerySuccess(datasource.meta.id, queries);
  423. } catch (response) {
  424. console.error(response);
  425. const queryError = response.data ? response.data.error : response;
  426. this.setState({ loading: false, queryErrors: [queryError] });
  427. }
  428. }
  429. request = url => {
  430. const { datasource } = this.state;
  431. return datasource.metadataRequest(url);
  432. };
  433. cloneState(): ExploreState {
  434. // Copy state, but copy queries including modifications
  435. return {
  436. ...this.state,
  437. queries: ensureQueries(this.queryExpressions.map(query => ({ query }))),
  438. };
  439. }
  440. saveState = () => {
  441. const { stateKey, onSaveState } = this.props;
  442. onSaveState(stateKey, this.cloneState());
  443. };
  444. render() {
  445. const { position, split } = this.props;
  446. const {
  447. datasource,
  448. datasourceError,
  449. datasourceLoading,
  450. datasourceMissing,
  451. exploreDatasources,
  452. graphResult,
  453. history,
  454. latency,
  455. loading,
  456. logsResult,
  457. queries,
  458. queryErrors,
  459. queryHints,
  460. range,
  461. requestOptions,
  462. showingGraph,
  463. showingLogs,
  464. showingTable,
  465. supportsGraph,
  466. supportsLogs,
  467. supportsTable,
  468. tableResult,
  469. } = this.state;
  470. const showingBoth = showingGraph && showingTable;
  471. const graphHeight = showingBoth ? '200px' : '400px';
  472. const graphButtonActive = showingBoth || showingGraph ? 'active' : '';
  473. const logsButtonActive = showingLogs ? 'active' : '';
  474. const tableButtonActive = showingBoth || showingTable ? 'active' : '';
  475. const exploreClass = split ? 'explore explore-split' : 'explore';
  476. return (
  477. <div className={exploreClass} ref={this.getRef}>
  478. <div className="navbar">
  479. {position === 'left' ? (
  480. <div>
  481. <a className="navbar-page-btn">
  482. <i className="fa fa-rocket" />
  483. Explore
  484. </a>
  485. </div>
  486. ) : (
  487. <div className="navbar-buttons explore-first-button">
  488. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  489. Close Split
  490. </button>
  491. </div>
  492. )}
  493. {!datasourceMissing ? (
  494. <div className="navbar-buttons">
  495. <Select
  496. classNamePrefix={`gf-form-select-box`}
  497. isMulti={false}
  498. isLoading={datasourceLoading}
  499. isClearable={false}
  500. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  501. onChange={this.onChangeDatasource}
  502. options={exploreDatasources}
  503. styles={ResetStyles}
  504. placeholder="Select datasource"
  505. loadingMessage={() => 'Loading datasources...'}
  506. noOptionsMessage={() => 'No datasources found'}
  507. getOptionValue={i => i.value}
  508. getOptionLabel={i => i.label}
  509. components={{
  510. Option: PickerOption,
  511. IndicatorsContainer,
  512. NoOptionsMessage,
  513. }}
  514. />
  515. </div>
  516. ) : null}
  517. <div className="navbar__spacer" />
  518. {position === 'left' && !split ? (
  519. <div className="navbar-buttons">
  520. <button className="btn navbar-button" onClick={this.onClickSplit}>
  521. Split
  522. </button>
  523. </div>
  524. ) : null}
  525. <TimePicker range={range} onChangeTime={this.onChangeTime} />
  526. <div className="navbar-buttons">
  527. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  528. Clear All
  529. </button>
  530. </div>
  531. <div className="navbar-buttons relative">
  532. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  533. Run Query <i className="fa fa-level-down run-icon" />
  534. </button>
  535. {loading || latency ? <ElapsedTime time={latency} className="text-info" /> : null}
  536. </div>
  537. </div>
  538. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  539. {datasourceMissing ? (
  540. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  541. ) : null}
  542. {datasourceError ? (
  543. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  544. ) : null}
  545. {datasource && !datasourceError ? (
  546. <div className="explore-container">
  547. <QueryRows
  548. history={history}
  549. queries={queries}
  550. queryErrors={queryErrors}
  551. queryHints={queryHints}
  552. request={this.request}
  553. onAddQueryRow={this.onAddQueryRow}
  554. onChangeQuery={this.onChangeQuery}
  555. onClickHintFix={this.onModifyQueries}
  556. onExecuteQuery={this.onSubmit}
  557. onRemoveQueryRow={this.onRemoveQueryRow}
  558. supportsLogs={supportsLogs}
  559. />
  560. <div className="result-options">
  561. {supportsGraph ? (
  562. <button className={`btn toggle-btn ${graphButtonActive}`} onClick={this.onClickGraphButton}>
  563. Graph
  564. </button>
  565. ) : null}
  566. {supportsTable ? (
  567. <button className={`btn toggle-btn ${tableButtonActive}`} onClick={this.onClickTableButton}>
  568. Table
  569. </button>
  570. ) : null}
  571. {supportsLogs ? (
  572. <button className={`btn toggle-btn ${logsButtonActive}`} onClick={this.onClickLogsButton}>
  573. Logs
  574. </button>
  575. ) : null}
  576. </div>
  577. <main className="m-t-2">
  578. {supportsGraph &&
  579. showingGraph &&
  580. graphResult && (
  581. <Graph
  582. data={graphResult}
  583. height={graphHeight}
  584. loading={loading}
  585. id={`explore-graph-${position}`}
  586. options={requestOptions}
  587. split={split}
  588. />
  589. )}
  590. {supportsTable && showingTable ? (
  591. <Table className="m-t-3" data={tableResult} loading={loading} onClickCell={this.onClickTableCell} />
  592. ) : null}
  593. {supportsLogs && showingLogs ? <Logs data={logsResult} loading={loading} /> : null}
  594. </main>
  595. </div>
  596. ) : null}
  597. </div>
  598. );
  599. }
  600. }
  601. export default hot(module)(Explore);