Explore.tsx 19 KB

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