Explore.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // Libraries
  2. import React, { ComponentClass } from 'react';
  3. import { hot } from 'react-hot-loader';
  4. // @ts-ignore
  5. import { connect } from 'react-redux';
  6. import _ from 'lodash';
  7. import { AutoSizer } from 'react-virtualized';
  8. // Services & Utils
  9. import store from 'app/core/store';
  10. // Components
  11. import { Alert } from './Error';
  12. import ErrorBoundary from './ErrorBoundary';
  13. import GraphContainer from './GraphContainer';
  14. import LogsContainer from './LogsContainer';
  15. import QueryRows from './QueryRows';
  16. import TableContainer from './TableContainer';
  17. import TimePicker from './TimePicker';
  18. // Actions
  19. import {
  20. changeSize,
  21. changeTime,
  22. initializeExplore,
  23. modifyQueries,
  24. scanStart,
  25. setQueries,
  26. refreshExplore,
  27. reconnectDatasource,
  28. } from './state/actions';
  29. // Types
  30. import { RawTimeRange, DataQuery, ExploreStartPageProps, ExploreDataSourceApi, DataQueryError } from '@grafana/ui';
  31. import {
  32. ExploreItemState,
  33. ExploreUrlState,
  34. RangeScanner,
  35. ExploreId,
  36. ExploreUpdateState,
  37. ExploreUIState,
  38. ExploreMode,
  39. } from 'app/types/explore';
  40. import { StoreState } from 'app/types';
  41. import {
  42. LAST_USED_DATASOURCE_KEY,
  43. ensureQueries,
  44. DEFAULT_RANGE,
  45. DEFAULT_UI_STATE,
  46. getTimeRangeFromUrl,
  47. } from 'app/core/utils/explore';
  48. import { Emitter } from 'app/core/utils/emitter';
  49. import { ExploreToolbar } from './ExploreToolbar';
  50. import { scanStopAction } from './state/actionTypes';
  51. import { NoDataSourceCallToAction } from './NoDataSourceCallToAction';
  52. import { FadeIn } from 'app/core/components/Animations/FadeIn';
  53. import { getTimeZone } from '../profile/state/selectors';
  54. import { ErrorContainer } from './ErrorContainer';
  55. interface ExploreProps {
  56. StartPage?: ComponentClass<ExploreStartPageProps>;
  57. changeSize: typeof changeSize;
  58. changeTime: typeof changeTime;
  59. datasourceError: string;
  60. datasourceInstance: ExploreDataSourceApi;
  61. datasourceLoading: boolean | null;
  62. datasourceMissing: boolean;
  63. exploreId: ExploreId;
  64. initializeExplore: typeof initializeExplore;
  65. initialized: boolean;
  66. modifyQueries: typeof modifyQueries;
  67. update: ExploreUpdateState;
  68. reconnectDatasource: typeof reconnectDatasource;
  69. refreshExplore: typeof refreshExplore;
  70. scanner?: RangeScanner;
  71. scanning?: boolean;
  72. scanRange?: RawTimeRange;
  73. scanStart: typeof scanStart;
  74. scanStopAction: typeof scanStopAction;
  75. setQueries: typeof setQueries;
  76. split: boolean;
  77. showingStartPage?: boolean;
  78. queryKeys: string[];
  79. initialDatasource: string;
  80. initialQueries: DataQuery[];
  81. initialRange: RawTimeRange;
  82. initialUI: ExploreUIState;
  83. queryErrors: DataQueryError[];
  84. mode: ExploreMode;
  85. }
  86. /**
  87. * Explore provides an area for quick query iteration for a given datasource.
  88. * Once a datasource is selected it populates the query section at the top.
  89. * When queries are run, their results are being displayed in the main section.
  90. * The datasource determines what kind of query editor it brings, and what kind
  91. * of results viewers it supports. The state is managed entirely in Redux.
  92. *
  93. * SPLIT VIEW
  94. *
  95. * Explore can have two Explore areas side-by-side. This is handled in `Wrapper.tsx`.
  96. * Since there can be multiple Explores (e.g., left and right) each action needs
  97. * the `exploreId` as first parameter so that the reducer knows which Explore state
  98. * is affected.
  99. *
  100. * DATASOURCE REQUESTS
  101. *
  102. * A click on Run Query creates transactions for all DataQueries for all expanded
  103. * result viewers. New runs are discarding previous runs. Upon completion a transaction
  104. * saves the result. The result viewers construct their data from the currently existing
  105. * transactions.
  106. *
  107. * The result viewers determine some of the query options sent to the datasource, e.g.,
  108. * `format`, to indicate eventual transformations by the datasources' result transformers.
  109. */
  110. export class Explore extends React.PureComponent<ExploreProps> {
  111. el: any;
  112. exploreEvents: Emitter;
  113. /**
  114. * Timepicker to control scanning
  115. */
  116. timepickerRef: React.RefObject<TimePicker>;
  117. constructor(props: ExploreProps) {
  118. super(props);
  119. this.exploreEvents = new Emitter();
  120. this.timepickerRef = React.createRef();
  121. }
  122. componentDidMount() {
  123. const { initialized, exploreId, initialDatasource, initialQueries, initialRange, initialUI } = this.props;
  124. const width = this.el ? this.el.offsetWidth : 0;
  125. // initialize the whole explore first time we mount and if browser history contains a change in datasource
  126. if (!initialized) {
  127. this.props.initializeExplore(
  128. exploreId,
  129. initialDatasource,
  130. initialQueries,
  131. initialRange,
  132. width,
  133. this.exploreEvents,
  134. initialUI
  135. );
  136. }
  137. }
  138. componentWillUnmount() {
  139. this.exploreEvents.removeAllListeners();
  140. }
  141. componentDidUpdate(prevProps: ExploreProps) {
  142. this.refreshExplore();
  143. }
  144. getRef = (el: any) => {
  145. this.el = el;
  146. };
  147. onChangeTime = (range: RawTimeRange, changedByScanner?: boolean) => {
  148. if (this.props.scanning && !changedByScanner) {
  149. this.onStopScanning();
  150. }
  151. this.props.changeTime(this.props.exploreId, range);
  152. };
  153. // Use this in help pages to set page to a single query
  154. onClickExample = (query: DataQuery) => {
  155. this.props.setQueries(this.props.exploreId, [query]);
  156. };
  157. onClickLabel = (key: string, value: string) => {
  158. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  159. };
  160. onModifyQueries = (action: any, index?: number) => {
  161. const { datasourceInstance } = this.props;
  162. if (datasourceInstance && datasourceInstance.modifyQuery) {
  163. const modifier = (queries: DataQuery, modification: any) => datasourceInstance.modifyQuery(queries, modification);
  164. this.props.modifyQueries(this.props.exploreId, action, index, modifier);
  165. }
  166. };
  167. onResize = (size: { height: number; width: number }) => {
  168. this.props.changeSize(this.props.exploreId, size);
  169. };
  170. onStartScanning = () => {
  171. // Scanner will trigger a query
  172. const scanner = this.scanPreviousRange;
  173. this.props.scanStart(this.props.exploreId, scanner);
  174. };
  175. scanPreviousRange = (): RawTimeRange => {
  176. // Calling move() on the timepicker will trigger this.onChangeTime()
  177. return this.timepickerRef.current.move(-1, true);
  178. };
  179. onStopScanning = () => {
  180. this.props.scanStopAction({ exploreId: this.props.exploreId });
  181. };
  182. refreshExplore = () => {
  183. const { exploreId, update } = this.props;
  184. if (update.queries || update.ui || update.range || update.datasource) {
  185. this.props.refreshExplore(exploreId);
  186. }
  187. };
  188. renderEmptyState = () => {
  189. return (
  190. <div className="explore-container">
  191. <NoDataSourceCallToAction />
  192. </div>
  193. );
  194. };
  195. onReconnect = (event: React.MouseEvent<HTMLButtonElement>) => {
  196. const { exploreId, reconnectDatasource } = this.props;
  197. event.preventDefault();
  198. reconnectDatasource(exploreId);
  199. };
  200. render() {
  201. const {
  202. StartPage,
  203. datasourceInstance,
  204. datasourceError,
  205. datasourceLoading,
  206. datasourceMissing,
  207. exploreId,
  208. showingStartPage,
  209. split,
  210. queryKeys,
  211. queryErrors,
  212. mode,
  213. } = this.props;
  214. const exploreClass = split ? 'explore explore-split' : 'explore';
  215. return (
  216. <div className={exploreClass} ref={this.getRef}>
  217. <ExploreToolbar exploreId={exploreId} timepickerRef={this.timepickerRef} onChangeTime={this.onChangeTime} />
  218. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  219. {datasourceMissing ? this.renderEmptyState() : null}
  220. <FadeIn duration={datasourceError ? 150 : 5} in={datasourceError ? true : false}>
  221. <div className="explore-container">
  222. <Alert
  223. message={`Error connecting to datasource: ${datasourceError}`}
  224. button={{ text: 'Reconnect', onClick: this.onReconnect }}
  225. />
  226. </div>
  227. </FadeIn>
  228. {datasourceInstance && (
  229. <div className="explore-container">
  230. <QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
  231. <ErrorContainer queryErrors={queryErrors} />
  232. <AutoSizer onResize={this.onResize} disableHeight>
  233. {({ width }) => {
  234. if (width === 0) {
  235. return null;
  236. }
  237. return (
  238. <main className="m-t-2" style={{ width }}>
  239. <ErrorBoundary>
  240. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  241. {!showingStartPage && (
  242. <>
  243. {mode === ExploreMode.Metrics && <GraphContainer width={width} exploreId={exploreId} />}
  244. {mode === ExploreMode.Metrics && (
  245. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  246. )}
  247. {mode === ExploreMode.Logs && (
  248. <LogsContainer
  249. width={width}
  250. exploreId={exploreId}
  251. onClickLabel={this.onClickLabel}
  252. onStartScanning={this.onStartScanning}
  253. onStopScanning={this.onStopScanning}
  254. />
  255. )}
  256. </>
  257. )}
  258. </ErrorBoundary>
  259. </main>
  260. );
  261. }}
  262. </AutoSizer>
  263. </div>
  264. )}
  265. </div>
  266. );
  267. }
  268. }
  269. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  270. const explore = state.explore;
  271. const { split } = explore;
  272. const item: ExploreItemState = explore[exploreId];
  273. const timeZone = getTimeZone(state.user);
  274. const {
  275. StartPage,
  276. datasourceError,
  277. datasourceInstance,
  278. datasourceLoading,
  279. datasourceMissing,
  280. initialized,
  281. showingStartPage,
  282. queryKeys,
  283. urlState,
  284. update,
  285. queryErrors,
  286. mode,
  287. } = item;
  288. const { datasource, queries, range: urlRange, ui } = (urlState || {}) as ExploreUrlState;
  289. const initialDatasource = datasource || store.get(LAST_USED_DATASOURCE_KEY);
  290. const initialQueries: DataQuery[] = ensureQueries(queries);
  291. const initialRange = urlRange ? getTimeRangeFromUrl(urlRange, timeZone).raw : DEFAULT_RANGE;
  292. const initialUI = ui || DEFAULT_UI_STATE;
  293. return {
  294. StartPage,
  295. datasourceError,
  296. datasourceInstance,
  297. datasourceLoading,
  298. datasourceMissing,
  299. initialized,
  300. showingStartPage,
  301. split,
  302. queryKeys,
  303. update,
  304. initialDatasource,
  305. initialQueries,
  306. initialRange,
  307. initialUI,
  308. queryErrors,
  309. mode,
  310. };
  311. }
  312. const mapDispatchToProps = {
  313. changeSize,
  314. changeTime,
  315. initializeExplore,
  316. modifyQueries,
  317. reconnectDatasource,
  318. refreshExplore,
  319. scanStart,
  320. scanStopAction,
  321. setQueries,
  322. };
  323. export default hot(module)(
  324. connect(
  325. mapStateToProps,
  326. mapDispatchToProps
  327. )(Explore)
  328. ) as React.ComponentType<{ exploreId: ExploreId }>;