Explore.tsx 11 KB

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