Explore.tsx 18 KB

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