Explore.tsx 11 KB

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