Explore.tsx 18 KB

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