Explore.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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 TimeSeries from 'app/core/time_series2';
  7. import { decodePathComponent } from 'app/core/utils/location_util';
  8. import { parse as parseDate } from 'app/core/utils/datemath';
  9. import ElapsedTime from './ElapsedTime';
  10. import QueryRows from './QueryRows';
  11. import Graph from './Graph';
  12. import Logs from './Logs';
  13. import Table from './Table';
  14. import TimePicker, { DEFAULT_RANGE } from './TimePicker';
  15. import { ensureQueries, generateQueryKey, hasQuery } from './utils/query';
  16. function makeTimeSeriesList(dataList, options) {
  17. return dataList.map((seriesData, index) => {
  18. const datapoints = seriesData.datapoints || [];
  19. const alias = seriesData.target;
  20. const colorIndex = index % colors.length;
  21. const color = colors[colorIndex];
  22. const series = new TimeSeries({
  23. datapoints,
  24. alias,
  25. color,
  26. unit: seriesData.unit,
  27. });
  28. return series;
  29. });
  30. }
  31. function parseInitialState(initial: string | undefined) {
  32. if (initial) {
  33. try {
  34. const parsed = JSON.parse(decodePathComponent(initial));
  35. return {
  36. datasource: parsed.datasource,
  37. queries: parsed.queries.map(q => q.query),
  38. range: parsed.range,
  39. };
  40. } catch (e) {
  41. console.error(e);
  42. }
  43. }
  44. return { datasource: null, queries: [], range: DEFAULT_RANGE };
  45. }
  46. interface IExploreState {
  47. datasource: any;
  48. datasourceError: any;
  49. datasourceLoading: boolean | null;
  50. datasourceMissing: boolean;
  51. graphResult: any;
  52. initialDatasource?: string;
  53. latency: number;
  54. loading: any;
  55. logsResult: any;
  56. queries: any;
  57. queryError: any;
  58. range: any;
  59. requestOptions: any;
  60. showingGraph: boolean;
  61. showingLogs: boolean;
  62. showingTable: boolean;
  63. supportsGraph: boolean | null;
  64. supportsLogs: boolean | null;
  65. supportsTable: boolean | null;
  66. tableResult: any;
  67. }
  68. export class Explore extends React.Component<any, IExploreState> {
  69. el: any;
  70. constructor(props) {
  71. super(props);
  72. const { datasource, queries, range } = parseInitialState(props.routeParams.state);
  73. this.state = {
  74. datasource: null,
  75. datasourceError: null,
  76. datasourceLoading: null,
  77. datasourceMissing: false,
  78. graphResult: null,
  79. initialDatasource: datasource,
  80. latency: 0,
  81. loading: false,
  82. logsResult: null,
  83. queries: ensureQueries(queries),
  84. queryError: null,
  85. range: range || { ...DEFAULT_RANGE },
  86. requestOptions: null,
  87. showingGraph: true,
  88. showingLogs: true,
  89. showingTable: true,
  90. supportsGraph: null,
  91. supportsLogs: null,
  92. supportsTable: null,
  93. tableResult: null,
  94. ...props.initialState,
  95. };
  96. }
  97. async componentDidMount() {
  98. const { datasourceSrv } = this.props;
  99. const { initialDatasource } = this.state;
  100. if (!datasourceSrv) {
  101. throw new Error('No datasource service passed as props.');
  102. }
  103. const datasources = datasourceSrv.getExploreSources();
  104. if (datasources.length > 0) {
  105. this.setState({ datasourceLoading: true });
  106. // Priority: datasource in url, default datasource, first explore datasource
  107. let datasource;
  108. if (initialDatasource) {
  109. datasource = await datasourceSrv.get(initialDatasource);
  110. } else {
  111. datasource = await datasourceSrv.get();
  112. }
  113. if (!datasource.meta.explore) {
  114. datasource = await datasourceSrv.get(datasources[0].name);
  115. }
  116. this.setDatasource(datasource);
  117. } else {
  118. this.setState({ datasourceMissing: true });
  119. }
  120. }
  121. componentDidCatch(error) {
  122. this.setState({ datasourceError: error });
  123. console.error(error);
  124. }
  125. async setDatasource(datasource) {
  126. const supportsGraph = datasource.meta.metrics;
  127. const supportsLogs = datasource.meta.logs;
  128. const supportsTable = datasource.meta.metrics;
  129. let datasourceError = null;
  130. try {
  131. const testResult = await datasource.testDatasource();
  132. datasourceError = testResult.status === 'success' ? null : testResult.message;
  133. } catch (error) {
  134. datasourceError = (error && error.statusText) || error;
  135. }
  136. this.setState(
  137. {
  138. datasource,
  139. datasourceError,
  140. supportsGraph,
  141. supportsLogs,
  142. supportsTable,
  143. datasourceLoading: false,
  144. },
  145. () => datasourceError === null && this.handleSubmit()
  146. );
  147. }
  148. getRef = el => {
  149. this.el = el;
  150. };
  151. handleAddQueryRow = index => {
  152. const { queries } = this.state;
  153. const nextQueries = [
  154. ...queries.slice(0, index + 1),
  155. { query: '', key: generateQueryKey() },
  156. ...queries.slice(index + 1),
  157. ];
  158. this.setState({ queries: nextQueries });
  159. };
  160. handleChangeDatasource = async option => {
  161. this.setState({
  162. datasource: null,
  163. datasourceError: null,
  164. datasourceLoading: true,
  165. graphResult: null,
  166. logsResult: null,
  167. tableResult: null,
  168. });
  169. const datasource = await this.props.datasourceSrv.get(option.value);
  170. this.setDatasource(datasource);
  171. };
  172. handleChangeQuery = (query, index) => {
  173. const { queries } = this.state;
  174. const nextQuery = {
  175. ...queries[index],
  176. query,
  177. };
  178. const nextQueries = [...queries];
  179. nextQueries[index] = nextQuery;
  180. this.setState({ queries: nextQueries });
  181. };
  182. handleChangeTime = nextRange => {
  183. const range = {
  184. from: nextRange.from,
  185. to: nextRange.to,
  186. };
  187. this.setState({ range }, () => this.handleSubmit());
  188. };
  189. handleClickCloseSplit = () => {
  190. const { onChangeSplit } = this.props;
  191. if (onChangeSplit) {
  192. onChangeSplit(false);
  193. }
  194. };
  195. handleClickGraphButton = () => {
  196. this.setState(state => ({ showingGraph: !state.showingGraph }));
  197. };
  198. handleClickLogsButton = () => {
  199. this.setState(state => ({ showingLogs: !state.showingLogs }));
  200. };
  201. handleClickSplit = () => {
  202. const { onChangeSplit } = this.props;
  203. if (onChangeSplit) {
  204. onChangeSplit(true, this.state);
  205. }
  206. };
  207. handleClickTableButton = () => {
  208. this.setState(state => ({ showingTable: !state.showingTable }));
  209. };
  210. handleRemoveQueryRow = index => {
  211. const { queries } = this.state;
  212. if (queries.length <= 1) {
  213. return;
  214. }
  215. const nextQueries = [...queries.slice(0, index), ...queries.slice(index + 1)];
  216. this.setState({ queries: nextQueries }, () => this.handleSubmit());
  217. };
  218. handleSubmit = () => {
  219. const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
  220. if (showingTable && supportsTable) {
  221. this.runTableQuery();
  222. }
  223. if (showingGraph && supportsGraph) {
  224. this.runGraphQuery();
  225. }
  226. if (showingLogs && supportsLogs) {
  227. this.runLogsQuery();
  228. }
  229. };
  230. buildQueryOptions(targetOptions: { format: string; instant?: boolean }) {
  231. const { datasource, queries, range } = this.state;
  232. const resolution = this.el.offsetWidth;
  233. const absoluteRange = {
  234. from: parseDate(range.from, false),
  235. to: parseDate(range.to, true),
  236. };
  237. const { interval } = kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  238. const targets = queries.map(q => ({
  239. ...targetOptions,
  240. expr: q.query,
  241. }));
  242. return {
  243. interval,
  244. range,
  245. targets,
  246. };
  247. }
  248. async runGraphQuery() {
  249. const { datasource, queries } = this.state;
  250. if (!hasQuery(queries)) {
  251. return;
  252. }
  253. this.setState({ latency: 0, loading: true, graphResult: null, queryError: null });
  254. const now = Date.now();
  255. const options = this.buildQueryOptions({ format: 'time_series', instant: false });
  256. try {
  257. const res = await datasource.query(options);
  258. const result = makeTimeSeriesList(res.data, options);
  259. const latency = Date.now() - now;
  260. this.setState({ latency, loading: false, graphResult: result, requestOptions: options });
  261. } catch (response) {
  262. console.error(response);
  263. const queryError = response.data ? response.data.error : response;
  264. this.setState({ loading: false, queryError });
  265. }
  266. }
  267. async runTableQuery() {
  268. const { datasource, queries } = this.state;
  269. if (!hasQuery(queries)) {
  270. return;
  271. }
  272. this.setState({ latency: 0, loading: true, queryError: null, tableResult: null });
  273. const now = Date.now();
  274. const options = this.buildQueryOptions({
  275. format: 'table',
  276. instant: true,
  277. });
  278. try {
  279. const res = await datasource.query(options);
  280. const tableModel = res.data[0];
  281. const latency = Date.now() - now;
  282. this.setState({ latency, loading: false, tableResult: tableModel, requestOptions: options });
  283. } catch (response) {
  284. console.error(response);
  285. const queryError = response.data ? response.data.error : response;
  286. this.setState({ loading: false, queryError });
  287. }
  288. }
  289. async runLogsQuery() {
  290. const { datasource, queries } = this.state;
  291. if (!hasQuery(queries)) {
  292. return;
  293. }
  294. this.setState({ latency: 0, loading: true, queryError: null, logsResult: null });
  295. const now = Date.now();
  296. const options = this.buildQueryOptions({
  297. format: 'logs',
  298. });
  299. try {
  300. const res = await datasource.query(options);
  301. const logsData = res.data;
  302. const latency = Date.now() - now;
  303. this.setState({ latency, loading: false, logsResult: logsData, requestOptions: options });
  304. } catch (response) {
  305. console.error(response);
  306. const queryError = response.data ? response.data.error : response;
  307. this.setState({ loading: false, queryError });
  308. }
  309. }
  310. request = url => {
  311. const { datasource } = this.state;
  312. return datasource.metadataRequest(url);
  313. };
  314. render() {
  315. const { datasourceSrv, position, split } = this.props;
  316. const {
  317. datasource,
  318. datasourceError,
  319. datasourceLoading,
  320. datasourceMissing,
  321. graphResult,
  322. latency,
  323. loading,
  324. logsResult,
  325. queries,
  326. queryError,
  327. range,
  328. requestOptions,
  329. showingGraph,
  330. showingLogs,
  331. showingTable,
  332. supportsGraph,
  333. supportsLogs,
  334. supportsTable,
  335. tableResult,
  336. } = this.state;
  337. const showingBoth = showingGraph && showingTable;
  338. const graphHeight = showingBoth ? '200px' : '400px';
  339. const graphButtonActive = showingBoth || showingGraph ? 'active' : '';
  340. const logsButtonActive = showingLogs ? 'active' : '';
  341. const tableButtonActive = showingBoth || showingTable ? 'active' : '';
  342. const exploreClass = split ? 'explore explore-split' : 'explore';
  343. const datasources = datasourceSrv.getExploreSources().map(ds => ({
  344. value: ds.name,
  345. label: ds.name,
  346. }));
  347. const selectedDatasource = datasource ? datasource.name : undefined;
  348. return (
  349. <div className={exploreClass} ref={this.getRef}>
  350. <div className="navbar">
  351. {position === 'left' ? (
  352. <div>
  353. <a className="navbar-page-btn">
  354. <i className="fa fa-rocket" />
  355. Explore
  356. </a>
  357. </div>
  358. ) : (
  359. <div className="navbar-buttons explore-first-button">
  360. <button className="btn navbar-button" onClick={this.handleClickCloseSplit}>
  361. Close Split
  362. </button>
  363. </div>
  364. )}
  365. {!datasourceMissing ? (
  366. <div className="navbar-buttons">
  367. <Select
  368. className="datasource-picker"
  369. clearable={false}
  370. onChange={this.handleChangeDatasource}
  371. options={datasources}
  372. placeholder="Loading datasources..."
  373. value={selectedDatasource}
  374. />
  375. </div>
  376. ) : null}
  377. <div className="navbar__spacer" />
  378. {position === 'left' && !split ? (
  379. <div className="navbar-buttons">
  380. <button className="btn navbar-button" onClick={this.handleClickSplit}>
  381. Split
  382. </button>
  383. </div>
  384. ) : null}
  385. <div className="navbar-buttons">
  386. {supportsGraph ? (
  387. <button className={`btn navbar-button ${graphButtonActive}`} onClick={this.handleClickGraphButton}>
  388. Graph
  389. </button>
  390. ) : null}
  391. {supportsTable ? (
  392. <button className={`btn navbar-button ${tableButtonActive}`} onClick={this.handleClickTableButton}>
  393. Table
  394. </button>
  395. ) : null}
  396. {supportsLogs ? (
  397. <button className={`btn navbar-button ${logsButtonActive}`} onClick={this.handleClickLogsButton}>
  398. Logs
  399. </button>
  400. ) : null}
  401. </div>
  402. <TimePicker range={range} onChangeTime={this.handleChangeTime} />
  403. <div className="navbar-buttons relative">
  404. <button className="btn navbar-button--primary" onClick={this.handleSubmit}>
  405. Run Query <i className="fa fa-level-down run-icon" />
  406. </button>
  407. {loading || latency ? <ElapsedTime time={latency} className="text-info" /> : null}
  408. </div>
  409. </div>
  410. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  411. {datasourceMissing ? (
  412. <div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
  413. ) : null}
  414. {datasourceError ? (
  415. <div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
  416. ) : null}
  417. {datasource && !datasourceError ? (
  418. <div className="explore-container">
  419. <QueryRows
  420. queries={queries}
  421. request={this.request}
  422. onAddQueryRow={this.handleAddQueryRow}
  423. onChangeQuery={this.handleChangeQuery}
  424. onExecuteQuery={this.handleSubmit}
  425. onRemoveQueryRow={this.handleRemoveQueryRow}
  426. />
  427. {queryError ? <div className="text-warning m-a-2">{queryError}</div> : null}
  428. <main className="m-t-2">
  429. {supportsGraph && showingGraph ? (
  430. <Graph
  431. data={graphResult}
  432. id={`explore-graph-${position}`}
  433. options={requestOptions}
  434. height={graphHeight}
  435. split={split}
  436. />
  437. ) : null}
  438. {supportsTable && showingTable ? <Table data={tableResult} className="m-t-3" /> : null}
  439. {supportsLogs && showingLogs ? <Logs data={logsResult} /> : null}
  440. </main>
  441. </div>
  442. ) : null}
  443. </div>
  444. );
  445. }
  446. }
  447. export default hot(module)(Explore);