Explore.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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, ErrorBoundaryAlert, DataQuery, ExploreStartPageProps, DataSourceApi, PanelData } from '@grafana/ui';
  12. import LogsContainer from './LogsContainer';
  13. import QueryRows from './QueryRows';
  14. import TableContainer from './TableContainer';
  15. // Actions
  16. import {
  17. changeSize,
  18. initializeExplore,
  19. modifyQueries,
  20. scanStart,
  21. setQueries,
  22. refreshExplore,
  23. reconnectDatasource,
  24. updateTimeRange,
  25. toggleGraph,
  26. } from './state/actions';
  27. // Types
  28. import { RawTimeRange, GraphSeriesXY, TimeZone, AbsoluteTimeRange } from '@grafana/data';
  29. import {
  30. ExploreItemState,
  31. ExploreUrlState,
  32. ExploreId,
  33. ExploreUpdateState,
  34. ExploreUIState,
  35. ExploreMode,
  36. } from 'app/types/explore';
  37. import { StoreState } from 'app/types';
  38. import {
  39. ensureQueries,
  40. DEFAULT_RANGE,
  41. DEFAULT_UI_STATE,
  42. getTimeRangeFromUrl,
  43. lastUsedDatasourceKeyForOrgId,
  44. } from 'app/core/utils/explore';
  45. import { Emitter } from 'app/core/utils/emitter';
  46. import { ExploreToolbar } from './ExploreToolbar';
  47. import { NoDataSourceCallToAction } from './NoDataSourceCallToAction';
  48. import { FadeIn } from 'app/core/components/Animations/FadeIn';
  49. import { getTimeZone } from '../profile/state/selectors';
  50. import { ErrorContainer } from './ErrorContainer';
  51. import { scanStopAction } from './state/actionTypes';
  52. import { ExploreGraphPanel } from './ExploreGraphPanel';
  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. isLive: boolean;
  81. updateTimeRange: typeof updateTimeRange;
  82. graphResult?: GraphSeriesXY[];
  83. loading?: boolean;
  84. absoluteRange: AbsoluteTimeRange;
  85. showingGraph?: boolean;
  86. showingTable?: boolean;
  87. timeZone?: TimeZone;
  88. onHiddenSeriesChanged?: (hiddenSeries: string[]) => void;
  89. toggleGraph: typeof toggleGraph;
  90. queryResponse: PanelData;
  91. originPanelId: number;
  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 {
  126. initialized,
  127. exploreId,
  128. initialDatasource,
  129. initialQueries,
  130. initialRange,
  131. mode,
  132. initialUI,
  133. originPanelId,
  134. } = this.props;
  135. const width = this.el ? this.el.offsetWidth : 0;
  136. // initialize the whole explore first time we mount and if browser history contains a change in datasource
  137. if (!initialized) {
  138. this.props.initializeExplore(
  139. exploreId,
  140. initialDatasource,
  141. initialQueries,
  142. initialRange,
  143. mode,
  144. width,
  145. this.exploreEvents,
  146. initialUI,
  147. originPanelId
  148. );
  149. }
  150. }
  151. componentWillUnmount() {
  152. this.exploreEvents.removeAllListeners();
  153. }
  154. componentDidUpdate(prevProps: ExploreProps) {
  155. this.refreshExplore();
  156. }
  157. getRef = (el: any) => {
  158. this.el = el;
  159. };
  160. onChangeTime = (rawRange: RawTimeRange) => {
  161. const { updateTimeRange, exploreId } = this.props;
  162. updateTimeRange({ exploreId, rawRange });
  163. };
  164. // Use this in help pages to set page to a single query
  165. onClickExample = (query: DataQuery) => {
  166. this.props.setQueries(this.props.exploreId, [query]);
  167. };
  168. onClickLabel = (key: string, value: string) => {
  169. this.onModifyQueries({ type: 'ADD_FILTER', key, value });
  170. };
  171. onModifyQueries = (action: any, index?: number) => {
  172. const { datasourceInstance } = this.props;
  173. if (datasourceInstance && datasourceInstance.modifyQuery) {
  174. const modifier = (queries: DataQuery, modification: any) => datasourceInstance.modifyQuery(queries, modification);
  175. this.props.modifyQueries(this.props.exploreId, action, index, modifier);
  176. }
  177. };
  178. onResize = (size: { height: number; width: number }) => {
  179. this.props.changeSize(this.props.exploreId, size);
  180. };
  181. onStartScanning = () => {
  182. // Scanner will trigger a query
  183. this.props.scanStart(this.props.exploreId);
  184. };
  185. onStopScanning = () => {
  186. this.props.scanStopAction({ exploreId: this.props.exploreId });
  187. };
  188. onToggleGraph = (showingGraph: boolean) => {
  189. const { toggleGraph, exploreId } = this.props;
  190. toggleGraph(exploreId, showingGraph);
  191. };
  192. onUpdateTimeRange = (absoluteRange: AbsoluteTimeRange) => {
  193. const { updateTimeRange, exploreId } = this.props;
  194. updateTimeRange({ exploreId, absoluteRange });
  195. };
  196. refreshExplore = () => {
  197. const { exploreId, update } = this.props;
  198. if (update.queries || update.ui || update.range || update.datasource || update.mode) {
  199. this.props.refreshExplore(exploreId);
  200. }
  201. };
  202. renderEmptyState = () => {
  203. return (
  204. <div className="explore-container">
  205. <NoDataSourceCallToAction />
  206. </div>
  207. );
  208. };
  209. onReconnect = (event: React.MouseEvent<HTMLButtonElement>) => {
  210. const { exploreId, reconnectDatasource } = this.props;
  211. event.preventDefault();
  212. reconnectDatasource(exploreId);
  213. };
  214. render() {
  215. const {
  216. StartPage,
  217. datasourceInstance,
  218. datasourceError,
  219. datasourceLoading,
  220. datasourceMissing,
  221. exploreId,
  222. showingStartPage,
  223. split,
  224. queryKeys,
  225. mode,
  226. graphResult,
  227. loading,
  228. absoluteRange,
  229. showingGraph,
  230. showingTable,
  231. timeZone,
  232. queryResponse,
  233. } = this.props;
  234. const exploreClass = split ? 'explore explore-split' : 'explore';
  235. return (
  236. <div className={exploreClass} ref={this.getRef}>
  237. <ExploreToolbar exploreId={exploreId} onChangeTime={this.onChangeTime} />
  238. {datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
  239. {datasourceMissing ? this.renderEmptyState() : null}
  240. <FadeIn duration={datasourceError ? 150 : 5} in={datasourceError ? true : false}>
  241. <div className="explore-container">
  242. <Alert
  243. title={`Error connecting to datasource: ${datasourceError}`}
  244. button={{ text: 'Reconnect', onClick: this.onReconnect }}
  245. />
  246. </div>
  247. </FadeIn>
  248. {datasourceInstance && (
  249. <div className="explore-container">
  250. <QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
  251. <ErrorContainer queryErrors={[queryResponse.error]} />
  252. <AutoSizer onResize={this.onResize} disableHeight>
  253. {({ width }) => {
  254. if (width === 0) {
  255. return null;
  256. }
  257. return (
  258. <main className="m-t-2" style={{ width }}>
  259. <ErrorBoundaryAlert>
  260. {showingStartPage && (
  261. <div className="grafana-info-box grafana-info-box--max-lg">
  262. <StartPage onClickExample={this.onClickExample} datasource={datasourceInstance} />
  263. </div>
  264. )}
  265. {!showingStartPage && (
  266. <>
  267. {mode === ExploreMode.Metrics && (
  268. <ExploreGraphPanel
  269. series={graphResult}
  270. width={width}
  271. loading={loading}
  272. absoluteRange={absoluteRange}
  273. isStacked={false}
  274. showPanel={true}
  275. showingGraph={showingGraph}
  276. showingTable={showingTable}
  277. timeZone={timeZone}
  278. onToggleGraph={this.onToggleGraph}
  279. onUpdateTimeRange={this.onUpdateTimeRange}
  280. showBars={false}
  281. showLines={true}
  282. />
  283. )}
  284. {mode === ExploreMode.Metrics && (
  285. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  286. )}
  287. {mode === ExploreMode.Logs && (
  288. <LogsContainer
  289. width={width}
  290. exploreId={exploreId}
  291. onClickLabel={this.onClickLabel}
  292. onStartScanning={this.onStartScanning}
  293. onStopScanning={this.onStopScanning}
  294. />
  295. )}
  296. </>
  297. )}
  298. </ErrorBoundaryAlert>
  299. </main>
  300. );
  301. }}
  302. </AutoSizer>
  303. </div>
  304. )}
  305. </div>
  306. );
  307. }
  308. }
  309. const ensureQueriesMemoized = memoizeOne(ensureQueries);
  310. const getTimeRangeFromUrlMemoized = memoizeOne(getTimeRangeFromUrl);
  311. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  312. const explore = state.explore;
  313. const { split } = explore;
  314. const item: ExploreItemState = explore[exploreId];
  315. const timeZone = getTimeZone(state.user);
  316. const {
  317. StartPage,
  318. datasourceError,
  319. datasourceInstance,
  320. datasourceLoading,
  321. datasourceMissing,
  322. initialized,
  323. showingStartPage,
  324. queryKeys,
  325. urlState,
  326. update,
  327. isLive,
  328. supportedModes,
  329. mode,
  330. graphResult,
  331. loading,
  332. showingGraph,
  333. showingTable,
  334. absoluteRange,
  335. queryResponse,
  336. } = item;
  337. const { datasource, queries, range: urlRange, mode: urlMode, ui, originPanelId } = (urlState ||
  338. {}) as ExploreUrlState;
  339. const initialDatasource = datasource || store.get(lastUsedDatasourceKeyForOrgId(state.user.orgId));
  340. const initialQueries: DataQuery[] = ensureQueriesMemoized(queries);
  341. const initialRange = urlRange ? getTimeRangeFromUrlMemoized(urlRange, timeZone).raw : DEFAULT_RANGE;
  342. let newMode: ExploreMode;
  343. if (supportedModes.length) {
  344. const urlModeIsValid = supportedModes.includes(urlMode);
  345. const modeStateIsValid = supportedModes.includes(mode);
  346. if (modeStateIsValid) {
  347. newMode = mode;
  348. } else if (urlModeIsValid) {
  349. newMode = urlMode;
  350. } else {
  351. newMode = supportedModes[0];
  352. }
  353. } else {
  354. newMode = [ExploreMode.Metrics, ExploreMode.Logs].includes(mode) ? mode : ExploreMode.Metrics;
  355. }
  356. const initialUI = ui || DEFAULT_UI_STATE;
  357. return {
  358. StartPage,
  359. datasourceError,
  360. datasourceInstance,
  361. datasourceLoading,
  362. datasourceMissing,
  363. initialized,
  364. showingStartPage,
  365. split,
  366. queryKeys,
  367. update,
  368. initialDatasource,
  369. initialQueries,
  370. initialRange,
  371. mode: newMode,
  372. initialUI,
  373. isLive,
  374. graphResult,
  375. loading,
  376. showingGraph,
  377. showingTable,
  378. absoluteRange,
  379. queryResponse,
  380. originPanelId,
  381. };
  382. }
  383. const mapDispatchToProps = {
  384. changeSize,
  385. initializeExplore,
  386. modifyQueries,
  387. reconnectDatasource,
  388. refreshExplore,
  389. scanStart,
  390. scanStopAction,
  391. setQueries,
  392. updateTimeRange,
  393. toggleGraph,
  394. };
  395. export default hot(module)(
  396. connect(
  397. mapStateToProps,
  398. mapDispatchToProps
  399. )(Explore)
  400. ) as React.ComponentType<{ exploreId: ExploreId }>;