Explore.tsx 18 KB

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