Explore.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. }
  251. };
  252. onClickGraphButton = () => {
  253. this.setState(state => ({ showingGraph: !state.showingGraph }));
  254. };
  255. onClickLogsButton = () => {
  256. this.setState(state => ({ showingLogs: !state.showingLogs }));
  257. };
  258. onClickSplit = () => {
  259. const { onChangeSplit } = this.props;
  260. if (onChangeSplit) {
  261. const state = this.cloneState();
  262. onChangeSplit(true, state);
  263. }
  264. };
  265. onClickTableButton = () => {
  266. this.setState(state => ({ showingTable: !state.showingTable }));
  267. };
  268. onClickTableCell = (columnKey: string, rowValue: string) => {
  269. this.onModifyQueries({ type: 'ADD_FILTER', key: columnKey, value: rowValue });
  270. };
  271. onModifyQueries = (action: object, index?: number) => {
  272. const { datasource, queries } = this.state;
  273. if (datasource && datasource.modifyQuery) {
  274. let nextQueries;
  275. if (index === undefined) {
  276. // Modify all queries
  277. nextQueries = queries.map((q, i) => ({
  278. key: generateQueryKey(i),
  279. query: datasource.modifyQuery(this.queryExpressions[i], action),
  280. }));
  281. } else {
  282. // Modify query only at index
  283. nextQueries = [
  284. ...queries.slice(0, index),
  285. {
  286. key: generateQueryKey(index),
  287. query: datasource.modifyQuery(this.queryExpressions[index], action),
  288. },
  289. ...queries.slice(index + 1),
  290. ];
  291. }
  292. this.queryExpressions = nextQueries.map(q => q.query);
  293. this.setState({ queries: nextQueries }, () => this.onSubmit());
  294. }
  295. };
  296. onRemoveQueryRow = index => {
  297. const { queries } = this.state;
  298. if (queries.length <= 1) {
  299. return;
  300. }
  301. const nextQueries = [...queries.slice(0, index), ...queries.slice(index + 1)];
  302. this.queryExpressions = nextQueries.map(q => q.query);
  303. this.setState({ queries: nextQueries }, () => this.onSubmit());
  304. };
  305. onSubmit = () => {
  306. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  307. if (showingTable && supportsTable) {
  308. this.runTableQuery();
  309. }
  310. if (showingGraph && supportsGraph) {
  311. this.runGraphQuery();
  312. }
  313. if (showingLogs && supportsLogs) {
  314. this.runLogsQuery();
  315. }
  316. this.saveState();
  317. };
  318. onQuerySuccess(datasourceId: string, queries: string[]): void {
  319. // save queries to history
  320. let { history } = this.state;
  321. const { datasource } = this.state;
  322. if (datasource.meta.id !== datasourceId) {
  323. // Navigated away, queries did not matter
  324. return;
  325. }
  326. const ts = Date.now();
  327. queries.forEach(query => {
  328. history = [{ query, ts }, ...history];
  329. });
  330. if (history.length > MAX_HISTORY_ITEMS) {
  331. history = history.slice(0, MAX_HISTORY_ITEMS);
  332. }
  333. // Combine all queries of a datasource type into one history
  334. const historyKey = `grafana.explore.history.${datasourceId}`;
  335. store.setObject(historyKey, history);
  336. this.setState({ history });
  337. }
  338. buildQueryOptions(targetOptions: { format: string; hinting?: boolean; instant?: boolean }) {
  339. const { datasource, range } = this.state;
  340. const resolution = this.el.offsetWidth;
  341. const absoluteRange = {
  342. from: parseDate(range.from, false),
  343. to: parseDate(range.to, true),
  344. };
  345. const { interval } = kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  346. const targets = this.queryExpressions.map(q => ({
  347. ...targetOptions,
  348. expr: q,
  349. }));
  350. return {
  351. interval,
  352. range,
  353. targets,
  354. };
  355. }
  356. async runGraphQuery() {
  357. const { datasource } = this.state;
  358. const queries = [...this.queryExpressions];
  359. if (!hasQuery(queries)) {
  360. return;
  361. }
  362. this.setState({ latency: 0, loading: true, graphResult: null, queryErrors: [], queryHints: [] });
  363. const now = Date.now();
  364. const options = this.buildQueryOptions({ format: 'time_series', instant: false, hinting: true });
  365. try {
  366. const res = await datasource.query(options);
  367. const result = makeTimeSeriesList(res.data, options);
  368. const queryHints = res.hints ? makeHints(res.hints) : [];
  369. const latency = Date.now() - now;
  370. this.setState({ latency, loading: false, graphResult: result, queryHints, requestOptions: options });
  371. this.onQuerySuccess(datasource.meta.id, queries);
  372. } catch (response) {
  373. console.error(response);
  374. const queryError = response.data ? response.data.error : response;
  375. this.setState({ loading: false, queryErrors: [queryError] });
  376. }
  377. }
  378. async runTableQuery() {
  379. const queries = [...this.queryExpressions];
  380. const { datasource } = this.state;
  381. if (!hasQuery(queries)) {
  382. return;
  383. }
  384. this.setState({ latency: 0, loading: true, queryErrors: [], queryHints: [], tableResult: null });
  385. const now = Date.now();
  386. const options = this.buildQueryOptions({
  387. format: 'table',
  388. instant: true,
  389. });
  390. try {
  391. const res = await datasource.query(options);
  392. const tableModel = res.data[0];
  393. const latency = Date.now() - now;
  394. this.setState({ latency, loading: false, tableResult: tableModel, requestOptions: options });
  395. this.onQuerySuccess(datasource.meta.id, queries);
  396. } catch (response) {
  397. console.error(response);
  398. const queryError = response.data ? response.data.error : response;
  399. this.setState({ loading: false, queryErrors: [queryError] });
  400. }
  401. }
  402. async runLogsQuery() {
  403. const queries = [...this.queryExpressions];
  404. const { datasource } = this.state;
  405. if (!hasQuery(queries)) {
  406. return;
  407. }
  408. this.setState({ latency: 0, loading: true, queryErrors: [], queryHints: [], logsResult: null });
  409. const now = Date.now();
  410. const options = this.buildQueryOptions({
  411. format: 'logs',
  412. });
  413. try {
  414. const res = await datasource.query(options);
  415. const logsData = res.data;
  416. const latency = Date.now() - now;
  417. this.setState({ latency, loading: false, logsResult: logsData, requestOptions: options });
  418. this.onQuerySuccess(datasource.meta.id, queries);
  419. } catch (response) {
  420. console.error(response);
  421. const queryError = response.data ? response.data.error : response;
  422. this.setState({ loading: false, queryErrors: [queryError] });
  423. }
  424. }
  425. request = url => {
  426. const { datasource } = this.state;
  427. return datasource.metadataRequest(url);
  428. };
  429. cloneState(): ExploreState {
  430. // Copy state, but copy queries including modifications
  431. return {
  432. ...this.state,
  433. queries: ensureQueries(this.queryExpressions.map(query => ({ query }))),
  434. };
  435. }
  436. saveState = () => {
  437. const { stateKey, onSaveState } = this.props;
  438. onSaveState(stateKey, this.cloneState());
  439. };
  440. render() {
  441. const { position, split } = this.props;
  442. const {
  443. datasource,
  444. datasourceError,
  445. datasourceLoading,
  446. datasourceMissing,
  447. exploreDatasources,
  448. graphResult,
  449. history,
  450. latency,
  451. loading,
  452. logsResult,
  453. queries,
  454. queryErrors,
  455. queryHints,
  456. range,
  457. requestOptions,
  458. showingGraph,
  459. showingLogs,
  460. showingTable,
  461. supportsGraph,
  462. supportsLogs,
  463. supportsTable,
  464. tableResult,
  465. } = this.state;
  466. const showingBoth = showingGraph && showingTable;
  467. const graphHeight = showingBoth ? '200px' : '400px';
  468. const graphButtonActive = showingBoth || showingGraph ? 'active' : '';
  469. const logsButtonActive = showingLogs ? 'active' : '';
  470. const tableButtonActive = showingBoth || showingTable ? 'active' : '';
  471. const exploreClass = split ? 'explore explore-split' : 'explore';
  472. const selectedDatasource = datasource ? datasource.name : undefined;
  473. return (
  474. <div className={exploreClass} ref={this.getRef}>
  475. <div className="navbar">
  476. {position === 'left' ? (
  477. <div>
  478. <a className="navbar-page-btn">
  479. <i className="fa fa-rocket" />
  480. Explore
  481. </a>
  482. </div>
  483. ) : (
  484. <div className="navbar-buttons explore-first-button">
  485. <button className="btn navbar-button" onClick={this.onClickCloseSplit}>
  486. Close Split
  487. </button>
  488. </div>
  489. )}
  490. {!datasourceMissing ? (
  491. <div className="navbar-buttons">
  492. <Select
  493. clearable={false}
  494. className="gf-form-input gf-form-input--form-dropdown datasource-picker"
  495. onChange={this.onChangeDatasource}
  496. options={exploreDatasources}
  497. isOpen={true}
  498. placeholder="Loading datasources..."
  499. value={selectedDatasource}
  500. />
  501. </div>
  502. ) : null}
  503. <div className="navbar__spacer" />
  504. {position === 'left' && !split ? (
  505. <div className="navbar-buttons">
  506. <button className="btn navbar-button" onClick={this.onClickSplit}>
  507. Split
  508. </button>
  509. </div>
  510. ) : null}
  511. <TimePicker range={range} onChangeTime={this.onChangeTime} />
  512. <div className="navbar-buttons">
  513. <button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
  514. Clear All
  515. </button>
  516. </div>
  517. <div className="navbar-buttons relative">
  518. <button className="btn navbar-button--primary" onClick={this.onSubmit}>
  519. Run Query <i className="fa fa-level-down run-icon" />
  520. </button>
  521. {loading || latency ? <ElapsedTime time={latency} className="text-info" /> : null}
  522. </div>
  523. </div>
  524. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  525. {datasourceMissing ? (
  526. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  527. ) : null}
  528. {datasourceError ? (
  529. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  530. ) : null}
  531. {datasource && !datasourceError ? (
  532. <div className="explore-container">
  533. <QueryRows
  534. history={history}
  535. queries={queries}
  536. queryErrors={queryErrors}
  537. queryHints={queryHints}
  538. request={this.request}
  539. onAddQueryRow={this.onAddQueryRow}
  540. onChangeQuery={this.onChangeQuery}
  541. onClickHintFix={this.onModifyQueries}
  542. onExecuteQuery={this.onSubmit}
  543. onRemoveQueryRow={this.onRemoveQueryRow}
  544. supportsLogs={supportsLogs}
  545. />
  546. <div className="result-options">
  547. {supportsGraph ? (
  548. <button className={`btn toggle-btn ${graphButtonActive}`} onClick={this.onClickGraphButton}>
  549. Graph
  550. </button>
  551. ) : null}
  552. {supportsTable ? (
  553. <button className={`btn toggle-btn ${tableButtonActive}`} onClick={this.onClickTableButton}>
  554. Table
  555. </button>
  556. ) : null}
  557. {supportsLogs ? (
  558. <button className={`btn toggle-btn ${logsButtonActive}`} onClick={this.onClickLogsButton}>
  559. Logs
  560. </button>
  561. ) : null}
  562. </div>
  563. <main className="m-t-2">
  564. {supportsGraph &&
  565. showingGraph &&
  566. graphResult && (
  567. <Graph
  568. data={graphResult}
  569. height={graphHeight}
  570. loading={loading}
  571. id={`explore-graph-${position}`}
  572. options={requestOptions}
  573. split={split}
  574. />
  575. )}
  576. {supportsTable && showingTable ? (
  577. <Table className="m-t-3" data={tableResult} loading={loading} onClickCell={this.onClickTableCell} />
  578. ) : null}
  579. {supportsLogs && showingLogs ? <Logs data={logsResult} loading={loading} /> : null}
  580. </main>
  581. </div>
  582. ) : null}
  583. </div>
  584. );
  585. }
  586. }
  587. export default hot(module)(Explore);