Explore.tsx 13 KB

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