Explore.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 && <StartPage onClickExample={this.onClickExample} />}
  261. {!showingStartPage && (
  262. <>
  263. {mode === ExploreMode.Metrics && (
  264. <ExploreGraphPanel
  265. series={graphResult}
  266. width={width}
  267. loading={loading}
  268. absoluteRange={absoluteRange}
  269. isStacked={false}
  270. showPanel={true}
  271. showingGraph={showingGraph}
  272. showingTable={showingTable}
  273. timeZone={timeZone}
  274. onToggleGraph={this.onToggleGraph}
  275. onUpdateTimeRange={this.onUpdateTimeRange}
  276. showBars={false}
  277. showLines={true}
  278. />
  279. )}
  280. {mode === ExploreMode.Metrics && (
  281. <TableContainer exploreId={exploreId} onClickCell={this.onClickLabel} />
  282. )}
  283. {mode === ExploreMode.Logs && (
  284. <LogsContainer
  285. width={width}
  286. exploreId={exploreId}
  287. onClickLabel={this.onClickLabel}
  288. onStartScanning={this.onStartScanning}
  289. onStopScanning={this.onStopScanning}
  290. />
  291. )}
  292. </>
  293. )}
  294. </ErrorBoundaryAlert>
  295. </main>
  296. );
  297. }}
  298. </AutoSizer>
  299. </div>
  300. )}
  301. </div>
  302. );
  303. }
  304. }
  305. const ensureQueriesMemoized = memoizeOne(ensureQueries);
  306. const getTimeRangeFromUrlMemoized = memoizeOne(getTimeRangeFromUrl);
  307. function mapStateToProps(state: StoreState, { exploreId }: ExploreProps) {
  308. const explore = state.explore;
  309. const { split } = explore;
  310. const item: ExploreItemState = explore[exploreId];
  311. const timeZone = getTimeZone(state.user);
  312. const {
  313. StartPage,
  314. datasourceError,
  315. datasourceInstance,
  316. datasourceLoading,
  317. datasourceMissing,
  318. initialized,
  319. showingStartPage,
  320. queryKeys,
  321. urlState,
  322. update,
  323. isLive,
  324. supportedModes,
  325. mode,
  326. graphResult,
  327. loading,
  328. showingGraph,
  329. showingTable,
  330. absoluteRange,
  331. queryResponse,
  332. } = item;
  333. const { datasource, queries, range: urlRange, mode: urlMode, ui, originPanelId } = (urlState ||
  334. {}) as ExploreUrlState;
  335. const initialDatasource = datasource || store.get(lastUsedDatasourceKeyForOrgId(state.user.orgId));
  336. const initialQueries: DataQuery[] = ensureQueriesMemoized(queries);
  337. const initialRange = urlRange ? getTimeRangeFromUrlMemoized(urlRange, timeZone).raw : DEFAULT_RANGE;
  338. let newMode: ExploreMode;
  339. if (supportedModes.length) {
  340. const urlModeIsValid = supportedModes.includes(urlMode);
  341. const modeStateIsValid = supportedModes.includes(mode);
  342. if (modeStateIsValid) {
  343. newMode = mode;
  344. } else if (urlModeIsValid) {
  345. newMode = urlMode;
  346. } else {
  347. newMode = supportedModes[0];
  348. }
  349. } else {
  350. newMode = [ExploreMode.Metrics, ExploreMode.Logs].includes(mode) ? mode : ExploreMode.Metrics;
  351. }
  352. const initialUI = ui || DEFAULT_UI_STATE;
  353. return {
  354. StartPage,
  355. datasourceError,
  356. datasourceInstance,
  357. datasourceLoading,
  358. datasourceMissing,
  359. initialized,
  360. showingStartPage,
  361. split,
  362. queryKeys,
  363. update,
  364. initialDatasource,
  365. initialQueries,
  366. initialRange,
  367. mode: newMode,
  368. initialUI,
  369. isLive,
  370. graphResult,
  371. loading,
  372. showingGraph,
  373. showingTable,
  374. absoluteRange,
  375. queryResponse,
  376. originPanelId,
  377. };
  378. }
  379. const mapDispatchToProps = {
  380. changeSize,
  381. initializeExplore,
  382. modifyQueries,
  383. reconnectDatasource,
  384. refreshExplore,
  385. scanStart,
  386. scanStopAction,
  387. setQueries,
  388. updateTimeRange,
  389. toggleGraph,
  390. };
  391. export default hot(module)(
  392. connect(
  393. mapStateToProps,
  394. mapDispatchToProps
  395. )(Explore)
  396. ) as React.ComponentType<{ exploreId: ExploreId }>;