Explore.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 LogsContainer from './LogsContainer';
  14. import QueryRows from './QueryRows';
  15. import TableContainer from './TableContainer';
  16. // Actions
  17. import {
  18. changeSize,
  19. initializeExplore,
  20. modifyQueries,
  21. scanStart,
  22. setQueries,
  23. refreshExplore,
  24. reconnectDatasource,
  25. updateTimeRange,
  26. } from './state/actions';
  27. // Types
  28. import { RawTimeRange, GraphSeriesXY } from '@grafana/data';
  29. import { 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. import ExploreGraphPanel from './ExploreGraphPanel';
  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. graphResult?: GraphSeriesXY[];
  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. constructor(props: ExploreProps) {
  114. super(props);
  115. this.exploreEvents = new Emitter();
  116. }
  117. componentDidMount() {
  118. const { initialized, exploreId, initialDatasource, initialQueries, initialRange, mode, initialUI } = this.props;
  119. const width = this.el ? this.el.offsetWidth : 0;
  120. // initialize the whole explore first time we mount and if browser history contains a change in datasource
  121. if (!initialized) {
  122. this.props.initializeExplore(
  123. exploreId,
  124. initialDatasource,
  125. initialQueries,
  126. initialRange,
  127. mode,
  128. width,
  129. this.exploreEvents,
  130. initialUI
  131. );
  132. }
  133. }
  134. componentWillUnmount() {
  135. this.exploreEvents.removeAllListeners();
  136. }
  137. componentDidUpdate(prevProps: ExploreProps) {
  138. this.refreshExplore();
  139. }
  140. getRef = (el: any) => {
  141. this.el = el;
  142. };
  143. onChangeTime = (rawRange: RawTimeRange) => {
  144. const { updateTimeRange, exploreId } = this.props;
  145. updateTimeRange({ exploreId, rawRange });
  146. };
  147. // Use this in help pages to set page to a single query
  148. onClickExample = (query: DataQuery) => {
  149. this.props.setQueries(this.props.exploreId, [query]);
  150. };
  151. onClickLabel = (key: string, value: string) => {
  152. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  153. };
  154. onModifyQueries = (action: any, index?: number) => {
  155. const { datasourceInstance } = this.props;
  156. if (datasourceInstance && datasourceInstance.modifyQuery) {
  157. const modifier = (queries: DataQuery, modification: any) => datasourceInstance.modifyQuery(queries, modification);
  158. this.props.modifyQueries(this.props.exploreId, action, index, modifier);
  159. }
  160. };
  161. onResize = (size: { height: number; width: number }) => {
  162. this.props.changeSize(this.props.exploreId, size);
  163. };
  164. onStartScanning = () => {
  165. // Scanner will trigger a query
  166. this.props.scanStart(this.props.exploreId);
  167. };
  168. onStopScanning = () => {
  169. this.props.scanStopAction({ exploreId: this.props.exploreId });
  170. };
  171. refreshExplore = () => {
  172. const { exploreId, update } = this.props;
  173. if (update.queries || update.ui || update.range || update.datasource || update.mode) {
  174. this.props.refreshExplore(exploreId);
  175. }
  176. };
  177. renderEmptyState = () => {
  178. return (
  179. <div className="explore-container">
  180. <NoDataSourceCallToAction />
  181. </div>
  182. );
  183. };
  184. onReconnect = (event: React.MouseEvent<HTMLButtonElement>) => {
  185. const { exploreId, reconnectDatasource } = this.props;
  186. event.preventDefault();
  187. reconnectDatasource(exploreId);
  188. };
  189. render() {
  190. const {
  191. StartPage,
  192. datasourceInstance,
  193. datasourceError,
  194. datasourceLoading,
  195. datasourceMissing,
  196. exploreId,
  197. showingStartPage,
  198. split,
  199. queryKeys,
  200. queryErrors,
  201. mode,
  202. graphResult,
  203. } = this.props;
  204. const exploreClass = split ? 'explore explore-split' : 'explore';
  205. return (
  206. <div className={exploreClass} ref={this.getRef}>
  207. <ExploreToolbar exploreId={exploreId} onChangeTime={this.onChangeTime} />
  208. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  209. {datasourceMissing ? this.renderEmptyState() : null}
  210. <FadeIn duration={datasourceError ? 150 : 5} in={datasourceError ? true : false}>
  211. <div className="explore-container">
  212. <Alert
  213. message={`Error connecting to datasource: ${datasourceError}`}
  214. button={{ text: 'Reconnect', onClick: this.onReconnect }}
  215. />
  216. </div>
  217. </FadeIn>
  218. {datasourceInstance && (
  219. <div className="explore-container">
  220. <QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
  221. <ErrorContainer queryErrors={queryErrors} />
  222. <AutoSizer onResize={this.onResize} disableHeight>
  223. {({ width }) => {
  224. if (width === 0) {
  225. return null;
  226. }
  227. return (
  228. <main className="m-t-2" style={{ width }}>
  229. <ErrorBoundary>
  230. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  231. {!showingStartPage && (
  232. <>
  233. {mode === ExploreMode.Metrics && (
  234. <ExploreGraphPanel exploreId={exploreId} series={graphResult} width={width} />
  235. )}
  236. {mode === ExploreMode.Metrics && (
  237. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  238. )}
  239. {mode === ExploreMode.Logs && (
  240. <LogsContainer
  241. width={width}
  242. exploreId={exploreId}
  243. onClickLabel={this.onClickLabel}
  244. onStartScanning={this.onStartScanning}
  245. onStopScanning={this.onStopScanning}
  246. />
  247. )}
  248. </>
  249. )}
  250. </ErrorBoundary>
  251. </main>
  252. );
  253. }}
  254. </AutoSizer>
  255. </div>
  256. )}
  257. </div>
  258. );
  259. }
  260. }
  261. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  262. const explore = state.explore;
  263. const { split } = explore;
  264. const item: ExploreItemState = explore[exploreId];
  265. const timeZone = getTimeZone(state.user);
  266. const {
  267. StartPage,
  268. datasourceError,
  269. datasourceInstance,
  270. datasourceLoading,
  271. datasourceMissing,
  272. initialized,
  273. showingStartPage,
  274. queryKeys,
  275. urlState,
  276. update,
  277. queryErrors,
  278. isLive,
  279. supportedModes,
  280. mode,
  281. graphResult,
  282. } = item;
  283. const { datasource, queries, range: urlRange, mode: urlMode, ui } = (urlState || {}) as ExploreUrlState;
  284. const initialDatasource = datasource || store.get(lastUsedDatasourceKeyForOrgId(state.user.orgId));
  285. const initialQueries: DataQuery[] = ensureQueries(queries);
  286. const initialRange = urlRange ? getTimeRangeFromUrl(urlRange, timeZone).raw : DEFAULT_RANGE;
  287. let newMode: ExploreMode;
  288. if (supportedModes.length) {
  289. const urlModeIsValid = supportedModes.includes(urlMode);
  290. const modeStateIsValid = supportedModes.includes(mode);
  291. if (modeStateIsValid) {
  292. newMode = mode;
  293. } else if (urlModeIsValid) {
  294. newMode = urlMode;
  295. } else {
  296. newMode = supportedModes[0];
  297. }
  298. } else {
  299. newMode = [ExploreMode.Metrics, ExploreMode.Logs].includes(mode) ? mode : ExploreMode.Metrics;
  300. }
  301. const initialUI = ui || DEFAULT_UI_STATE;
  302. return {
  303. StartPage,
  304. datasourceError,
  305. datasourceInstance,
  306. datasourceLoading,
  307. datasourceMissing,
  308. initialized,
  309. showingStartPage,
  310. split,
  311. queryKeys,
  312. update,
  313. initialDatasource,
  314. initialQueries,
  315. initialRange,
  316. mode: newMode,
  317. initialUI,
  318. queryErrors,
  319. isLive,
  320. graphResult,
  321. };
  322. }
  323. const mapDispatchToProps = {
  324. changeSize,
  325. initializeExplore,
  326. modifyQueries,
  327. reconnectDatasource,
  328. refreshExplore,
  329. scanStart,
  330. scanStopAction,
  331. setQueries,
  332. updateTimeRange,
  333. };
  334. export default hot(module)(
  335. connect(
  336. mapStateToProps,
  337. mapDispatchToProps
  338. )(Explore)
  339. ) as React.ComponentType<{ exploreId: ExploreId }>;