Explore.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. isLive: boolean;
  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 = (range: RawTimeRange, changedByScanner?: boolean) => {
  149. if (this.props.scanning && !changedByScanner) {
  150. this.onStopScanning();
  151. }
  152. this.props.changeTime(this.props.exploreId, range);
  153. };
  154. // Use this in help pages to set page to a single query
  155. onClickExample = (query: DataQuery) => {
  156. this.props.setQueries(this.props.exploreId, [query]);
  157. };
  158. onClickLabel = (key: string, value: string) => {
  159. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  160. };
  161. onModifyQueries = (action: any, index?: number) => {
  162. const { datasourceInstance } = this.props;
  163. if (datasourceInstance && datasourceInstance.modifyQuery) {
  164. const modifier = (queries: DataQuery, modification: any) => datasourceInstance.modifyQuery(queries, modification);
  165. this.props.modifyQueries(this.props.exploreId, action, index, modifier);
  166. }
  167. };
  168. onResize = (size: { height: number; width: number }) => {
  169. this.props.changeSize(this.props.exploreId, size);
  170. };
  171. onStartScanning = () => {
  172. // Scanner will trigger a query
  173. const scanner = this.scanPreviousRange;
  174. this.props.scanStart(this.props.exploreId, scanner);
  175. };
  176. scanPreviousRange = (): RawTimeRange => {
  177. // Calling move() on the timepicker will trigger this.onChangeTime()
  178. return this.timepickerRef.current.move(-1, true);
  179. };
  180. onStopScanning = () => {
  181. this.props.scanStopAction({ exploreId: this.props.exploreId });
  182. };
  183. refreshExplore = () => {
  184. const { exploreId, update } = this.props;
  185. if (update.queries || update.ui || update.range || update.datasource) {
  186. this.props.refreshExplore(exploreId);
  187. }
  188. };
  189. renderEmptyState = () => {
  190. return (
  191. <div className="explore-container">
  192. <NoDataSourceCallToAction />
  193. </div>
  194. );
  195. };
  196. onReconnect = (event: React.MouseEvent<HTMLButtonElement>) => {
  197. const { exploreId, reconnectDatasource } = this.props;
  198. event.preventDefault();
  199. reconnectDatasource(exploreId);
  200. };
  201. render() {
  202. const {
  203. StartPage,
  204. datasourceInstance,
  205. datasourceError,
  206. datasourceLoading,
  207. datasourceMissing,
  208. exploreId,
  209. showingStartPage,
  210. split,
  211. queryKeys,
  212. queryErrors,
  213. mode,
  214. } = this.props;
  215. const exploreClass = split ? 'explore explore-split' : 'explore';
  216. return (
  217. <div className={exploreClass} ref={this.getRef}>
  218. <ExploreToolbar exploreId={exploreId} timepickerRef={this.timepickerRef} onChangeTime={this.onChangeTime} />
  219. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  220. {datasourceMissing ? this.renderEmptyState() : null}
  221. <FadeIn duration={datasourceError ? 150 : 5} in={datasourceError ? true : false}>
  222. <div className="explore-container">
  223. <Alert
  224. message={`Error connecting to datasource: ${datasourceError}`}
  225. button={{ text: 'Reconnect', onClick: this.onReconnect }}
  226. />
  227. </div>
  228. </FadeIn>
  229. {datasourceInstance && (
  230. <div className="explore-container">
  231. <QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
  232. <ErrorContainer queryErrors={queryErrors} />
  233. <AutoSizer onResize={this.onResize} disableHeight>
  234. {({ width }) => {
  235. if (width === 0) {
  236. return null;
  237. }
  238. return (
  239. <main className="m-t-2" style={{ width }}>
  240. <ErrorBoundary>
  241. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  242. {!showingStartPage && (
  243. <>
  244. {mode === ExploreMode.Metrics && <GraphContainer width={width} exploreId={exploreId} />}
  245. {mode === ExploreMode.Metrics && (
  246. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  247. )}
  248. {mode === ExploreMode.Logs && (
  249. <LogsContainer
  250. width={width}
  251. exploreId={exploreId}
  252. onClickLabel={this.onClickLabel}
  253. onStartScanning={this.onStartScanning}
  254. onStopScanning={this.onStopScanning}
  255. />
  256. )}
  257. </>
  258. )}
  259. </ErrorBoundary>
  260. </main>
  261. );
  262. }}
  263. </AutoSizer>
  264. </div>
  265. )}
  266. </div>
  267. );
  268. }
  269. }
  270. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  271. const explore = state.explore;
  272. const { split } = explore;
  273. const item: ExploreItemState = explore[exploreId];
  274. const timeZone = getTimeZone(state.user);
  275. const {
  276. StartPage,
  277. datasourceError,
  278. datasourceInstance,
  279. datasourceLoading,
  280. datasourceMissing,
  281. initialized,
  282. showingStartPage,
  283. queryKeys,
  284. urlState,
  285. update,
  286. queryErrors,
  287. mode,
  288. isLive,
  289. } = item;
  290. const { datasource, queries, range: urlRange, ui } = (urlState || {}) as ExploreUrlState;
  291. const initialDatasource = datasource || store.get(LAST_USED_DATASOURCE_KEY);
  292. const initialQueries: DataQuery[] = ensureQueries(queries);
  293. const initialRange = urlRange ? getTimeRangeFromUrl(urlRange, timeZone).raw : DEFAULT_RANGE;
  294. const initialUI = ui || DEFAULT_UI_STATE;
  295. return {
  296. StartPage,
  297. datasourceError,
  298. datasourceInstance,
  299. datasourceLoading,
  300. datasourceMissing,
  301. initialized,
  302. showingStartPage,
  303. split,
  304. queryKeys,
  305. update,
  306. initialDatasource,
  307. initialQueries,
  308. initialRange,
  309. initialUI,
  310. queryErrors,
  311. mode,
  312. isLive,
  313. };
  314. }
  315. const mapDispatchToProps = {
  316. changeSize,
  317. changeTime,
  318. initializeExplore,
  319. modifyQueries,
  320. reconnectDatasource,
  321. refreshExplore,
  322. scanStart,
  323. scanStopAction,
  324. setQueries,
  325. };
  326. export default hot(module)(
  327. connect(
  328. mapStateToProps,
  329. mapDispatchToProps
  330. )(Explore)
  331. ) as React.ComponentType<{ exploreId: ExploreId }>;