Explore.tsx 13 KB

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