Explore.tsx 11 KB

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