Explore.tsx 13 KB

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