Explore.tsx 18 KB

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