Explore.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 { AutoSizer } from 'react-virtualized';
  7. import memoizeOne from 'memoize-one';
  8. // Services & Utils
  9. import store from 'app/core/store';
  10. // Components
  11. import { Alert, DataQuery, ExploreStartPageProps, DataSourceApi, PanelData } from '@grafana/ui';
  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. toggleGraph,
  27. } from './state/actions';
  28. // Types
  29. import { RawTimeRange, GraphSeriesXY, TimeZone, AbsoluteTimeRange } from '@grafana/data';
  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. isLive: boolean;
  82. updateTimeRange: typeof updateTimeRange;
  83. graphResult?: GraphSeriesXY[];
  84. loading?: boolean;
  85. absoluteRange: AbsoluteTimeRange;
  86. showingGraph?: boolean;
  87. showingTable?: boolean;
  88. timeZone?: TimeZone;
  89. onHiddenSeriesChanged?: (hiddenSeries: string[]) => void;
  90. toggleGraph: typeof toggleGraph;
  91. queryResponse: PanelData;
  92. }
  93. /**
  94. * Explore provides an area for quick query iteration for a given datasource.
  95. * Once a datasource is selected it populates the query section at the top.
  96. * When queries are run, their results are being displayed in the main section.
  97. * The datasource determines what kind of query editor it brings, and what kind
  98. * of results viewers it supports. The state is managed entirely in Redux.
  99. *
  100. * SPLIT VIEW
  101. *
  102. * Explore can have two Explore areas side-by-side. This is handled in `Wrapper.tsx`.
  103. * Since there can be multiple Explores (e.g., left and right) each action needs
  104. * the `exploreId` as first parameter so that the reducer knows which Explore state
  105. * is affected.
  106. *
  107. * DATASOURCE REQUESTS
  108. *
  109. * A click on Run Query creates transactions for all DataQueries for all expanded
  110. * result viewers. New runs are discarding previous runs. Upon completion a transaction
  111. * saves the result. The result viewers construct their data from the currently existing
  112. * transactions.
  113. *
  114. * The result viewers determine some of the query options sent to the datasource, e.g.,
  115. * `format`, to indicate eventual transformations by the datasources' result transformers.
  116. */
  117. export class Explore extends React.PureComponent<ExploreProps> {
  118. el: any;
  119. exploreEvents: Emitter;
  120. constructor(props: ExploreProps) {
  121. super(props);
  122. this.exploreEvents = new Emitter();
  123. }
  124. componentDidMount() {
  125. const { initialized, exploreId, initialDatasource, initialQueries, initialRange, mode, initialUI } = this.props;
  126. const width = this.el ? this.el.offsetWidth : 0;
  127. // initialize the whole explore first time we mount and if browser history contains a change in datasource
  128. if (!initialized) {
  129. this.props.initializeExplore(
  130. exploreId,
  131. initialDatasource,
  132. initialQueries,
  133. initialRange,
  134. mode,
  135. width,
  136. this.exploreEvents,
  137. initialUI
  138. );
  139. }
  140. }
  141. componentWillUnmount() {
  142. this.exploreEvents.removeAllListeners();
  143. }
  144. componentDidUpdate(prevProps: ExploreProps) {
  145. this.refreshExplore();
  146. }
  147. getRef = (el: any) => {
  148. this.el = el;
  149. };
  150. onChangeTime = (rawRange: RawTimeRange) => {
  151. const { updateTimeRange, exploreId } = this.props;
  152. updateTimeRange({ exploreId, rawRange });
  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. this.props.scanStart(this.props.exploreId);
  174. };
  175. onStopScanning = () => {
  176. this.props.scanStopAction({ exploreId: this.props.exploreId });
  177. };
  178. onToggleGraph = (showingGraph: boolean) => {
  179. const { toggleGraph, exploreId } = this.props;
  180. toggleGraph(exploreId, showingGraph);
  181. };
  182. onUpdateTimeRange = (absoluteRange: AbsoluteTimeRange) => {
  183. const { updateTimeRange, exploreId } = this.props;
  184. updateTimeRange({ exploreId, absoluteRange });
  185. };
  186. refreshExplore = () => {
  187. const { exploreId, update } = this.props;
  188. if (update.queries || update.ui || update.range || update.datasource || update.mode) {
  189. this.props.refreshExplore(exploreId);
  190. }
  191. };
  192. renderEmptyState = () => {
  193. return (
  194. <div className="explore-container">
  195. <NoDataSourceCallToAction />
  196. </div>
  197. );
  198. };
  199. onReconnect = (event: React.MouseEvent<HTMLButtonElement>) => {
  200. const { exploreId, reconnectDatasource } = this.props;
  201. event.preventDefault();
  202. reconnectDatasource(exploreId);
  203. };
  204. render() {
  205. const {
  206. StartPage,
  207. datasourceInstance,
  208. datasourceError,
  209. datasourceLoading,
  210. datasourceMissing,
  211. exploreId,
  212. showingStartPage,
  213. split,
  214. queryKeys,
  215. mode,
  216. graphResult,
  217. loading,
  218. absoluteRange,
  219. showingGraph,
  220. showingTable,
  221. timeZone,
  222. queryResponse,
  223. } = this.props;
  224. const exploreClass = split ? 'explore explore-split' : 'explore';
  225. return (
  226. <div className={exploreClass} ref={this.getRef}>
  227. <ExploreToolbar exploreId={exploreId} onChangeTime={this.onChangeTime} />
  228. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  229. {datasourceMissing ? this.renderEmptyState() : null}
  230. <FadeIn duration={datasourceError ? 150 : 5} in={datasourceError ? true : false}>
  231. <div className="explore-container">
  232. <Alert
  233. title={`Error connecting to datasource: ${datasourceError}`}
  234. button={{ text: 'Reconnect', onClick: this.onReconnect }}
  235. />
  236. </div>
  237. </FadeIn>
  238. {datasourceInstance && (
  239. <div className="explore-container">
  240. <QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
  241. <ErrorContainer queryErrors={[queryResponse.error]} />
  242. <AutoSizer onResize={this.onResize} disableHeight>
  243. {({ width }) => {
  244. if (width === 0) {
  245. return null;
  246. }
  247. return (
  248. <main className="m-t-2" style={{ width }}>
  249. <ErrorBoundary>
  250. {showingStartPage && <StartPage onClickExample={this.onClickExample} />}
  251. {!showingStartPage && (
  252. <>
  253. {mode === ExploreMode.Metrics && (
  254. <ExploreGraphPanel
  255. series={graphResult}
  256. width={width}
  257. loading={loading}
  258. absoluteRange={absoluteRange}
  259. isStacked={false}
  260. showPanel={true}
  261. showingGraph={showingGraph}
  262. showingTable={showingTable}
  263. timeZone={timeZone}
  264. onToggleGraph={this.onToggleGraph}
  265. onUpdateTimeRange={this.onUpdateTimeRange}
  266. showBars={false}
  267. showLines={true}
  268. />
  269. )}
  270. {mode === ExploreMode.Metrics && (
  271. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  272. )}
  273. {mode === ExploreMode.Logs && (
  274. <LogsContainer
  275. width={width}
  276. exploreId={exploreId}
  277. onClickLabel={this.onClickLabel}
  278. onStartScanning={this.onStartScanning}
  279. onStopScanning={this.onStopScanning}
  280. />
  281. )}
  282. </>
  283. )}
  284. </ErrorBoundary>
  285. </main>
  286. );
  287. }}
  288. </AutoSizer>
  289. </div>
  290. )}
  291. </div>
  292. );
  293. }
  294. }
  295. const ensureQueriesMemoized = memoizeOne(ensureQueries);
  296. const getTimeRangeFromUrlMemoized = memoizeOne(getTimeRangeFromUrl);
  297. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  298. const explore = state.explore;
  299. const { split } = explore;
  300. const item: ExploreItemState = explore[exploreId];
  301. const timeZone = getTimeZone(state.user);
  302. const {
  303. StartPage,
  304. datasourceError,
  305. datasourceInstance,
  306. datasourceLoading,
  307. datasourceMissing,
  308. initialized,
  309. showingStartPage,
  310. queryKeys,
  311. urlState,
  312. update,
  313. isLive,
  314. supportedModes,
  315. mode,
  316. graphResult,
  317. loading,
  318. showingGraph,
  319. showingTable,
  320. absoluteRange,
  321. queryResponse,
  322. } = item;
  323. const { datasource, queries, range: urlRange, mode: urlMode, ui } = (urlState || {}) as ExploreUrlState;
  324. const initialDatasource = datasource || store.get(lastUsedDatasourceKeyForOrgId(state.user.orgId));
  325. const initialQueries: DataQuery[] = ensureQueriesMemoized(queries);
  326. const initialRange = urlRange ? getTimeRangeFromUrlMemoized(urlRange, timeZone).raw : DEFAULT_RANGE;
  327. let newMode: ExploreMode;
  328. if (supportedModes.length) {
  329. const urlModeIsValid = supportedModes.includes(urlMode);
  330. const modeStateIsValid = supportedModes.includes(mode);
  331. if (modeStateIsValid) {
  332. newMode = mode;
  333. } else if (urlModeIsValid) {
  334. newMode = urlMode;
  335. } else {
  336. newMode = supportedModes[0];
  337. }
  338. } else {
  339. newMode = [ExploreMode.Metrics, ExploreMode.Logs].includes(mode) ? mode : ExploreMode.Metrics;
  340. }
  341. const initialUI = ui || DEFAULT_UI_STATE;
  342. return {
  343. StartPage,
  344. datasourceError,
  345. datasourceInstance,
  346. datasourceLoading,
  347. datasourceMissing,
  348. initialized,
  349. showingStartPage,
  350. split,
  351. queryKeys,
  352. update,
  353. initialDatasource,
  354. initialQueries,
  355. initialRange,
  356. mode: newMode,
  357. initialUI,
  358. isLive,
  359. graphResult,
  360. loading,
  361. showingGraph,
  362. showingTable,
  363. absoluteRange,
  364. queryResponse,
  365. };
  366. }
  367. const mapDispatchToProps = {
  368. changeSize,
  369. initializeExplore,
  370. modifyQueries,
  371. reconnectDatasource,
  372. refreshExplore,
  373. scanStart,
  374. scanStopAction,
  375. setQueries,
  376. updateTimeRange,
  377. toggleGraph,
  378. };
  379. export default hot(module)(
  380. connect(
  381. mapStateToProps,
  382. mapDispatchToProps
  383. )(Explore)
  384. ) as React.ComponentType<{ exploreId: ExploreId }>;