actions.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. // Libraries
  2. import _ from 'lodash';
  3. // Services & Utils
  4. import store from 'app/core/store';
  5. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  6. import { Emitter } from 'app/core/core';
  7. import {
  8. LAST_USED_DATASOURCE_KEY,
  9. ensureQueries,
  10. generateEmptyQuery,
  11. parseUrlState,
  12. getTimeRange,
  13. getTimeRangeFromUrl,
  14. generateNewKeyAndAddRefIdIfMissing,
  15. } from 'app/core/utils/explore';
  16. // Types
  17. import { ThunkResult } from 'app/types';
  18. import {
  19. RawTimeRange,
  20. DataSourceApi,
  21. DataQuery,
  22. DataSourceSelectItem,
  23. QueryFixAction,
  24. LogsDedupStrategy,
  25. AbsoluteTimeRange,
  26. } from '@grafana/ui';
  27. import { ExploreId, RangeScanner, ExploreUIState, QueryTransaction, ExploreMode } from 'app/types/explore';
  28. import {
  29. updateDatasourceInstanceAction,
  30. changeQueryAction,
  31. changeRefreshIntervalAction,
  32. ChangeRefreshIntervalPayload,
  33. changeSizeAction,
  34. ChangeSizePayload,
  35. clearQueriesAction,
  36. initializeExploreAction,
  37. loadDatasourceMissingAction,
  38. loadDatasourcePendingAction,
  39. queriesImportedAction,
  40. LoadDatasourceReadyPayload,
  41. loadDatasourceReadyAction,
  42. modifyQueriesAction,
  43. scanStartAction,
  44. setQueriesAction,
  45. splitCloseAction,
  46. splitOpenAction,
  47. addQueryRowAction,
  48. toggleGraphAction,
  49. toggleTableAction,
  50. ToggleGraphPayload,
  51. ToggleTablePayload,
  52. updateUIStateAction,
  53. testDataSourcePendingAction,
  54. testDataSourceSuccessAction,
  55. testDataSourceFailureAction,
  56. loadExploreDatasources,
  57. changeModeAction,
  58. scanStopAction,
  59. scanRangeAction,
  60. runQueriesAction,
  61. stateSaveAction,
  62. updateTimeRangeAction,
  63. } from './actionTypes';
  64. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  65. import { getTimeZone } from 'app/features/profile/state/selectors';
  66. import { offOption } from '@grafana/ui/src/components/RefreshPicker/RefreshPicker';
  67. /**
  68. * Updates UI state and save it to the URL
  69. */
  70. const updateExploreUIState = (exploreId: ExploreId, uiStateFragment: Partial<ExploreUIState>): ThunkResult<void> => {
  71. return dispatch => {
  72. dispatch(updateUIStateAction({ exploreId, ...uiStateFragment }));
  73. dispatch(stateSaveAction());
  74. };
  75. };
  76. /**
  77. * Adds a query row after the row with the given index.
  78. */
  79. export function addQueryRow(exploreId: ExploreId, index: number): ThunkResult<void> {
  80. return (dispatch, getState) => {
  81. const queries = getState().explore[exploreId].queries;
  82. const query = generateEmptyQuery(queries, index);
  83. dispatch(addQueryRowAction({ exploreId, index, query }));
  84. };
  85. }
  86. /**
  87. * Loads a new datasource identified by the given name.
  88. */
  89. export function changeDatasource(exploreId: ExploreId, datasource: string): ThunkResult<void> {
  90. return async (dispatch, getState) => {
  91. let newDataSourceInstance: DataSourceApi = null;
  92. if (!datasource) {
  93. newDataSourceInstance = await getDatasourceSrv().get();
  94. } else {
  95. newDataSourceInstance = await getDatasourceSrv().get(datasource);
  96. }
  97. const currentDataSourceInstance = getState().explore[exploreId].datasourceInstance;
  98. const queries = getState().explore[exploreId].queries;
  99. await dispatch(importQueries(exploreId, queries, currentDataSourceInstance, newDataSourceInstance));
  100. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: newDataSourceInstance }));
  101. if (getState().explore[exploreId].isLive) {
  102. dispatch(changeRefreshInterval(exploreId, offOption.value));
  103. }
  104. await dispatch(loadDatasource(exploreId, newDataSourceInstance));
  105. dispatch(runQueries(exploreId));
  106. };
  107. }
  108. /**
  109. * Change the display mode in Explore.
  110. */
  111. export function changeMode(exploreId: ExploreId, mode: ExploreMode): ThunkResult<void> {
  112. return dispatch => {
  113. dispatch(clearQueries(exploreId));
  114. dispatch(changeModeAction({ exploreId, mode }));
  115. dispatch(runQueries(exploreId));
  116. };
  117. }
  118. /**
  119. * Query change handler for the query row with the given index.
  120. * If `override` is reset the query modifications and run the queries. Use this to set queries via a link.
  121. */
  122. export function changeQuery(
  123. exploreId: ExploreId,
  124. query: DataQuery,
  125. index: number,
  126. override: boolean
  127. ): ThunkResult<void> {
  128. return (dispatch, getState) => {
  129. // Null query means reset
  130. if (query === null) {
  131. const queries = getState().explore[exploreId].queries;
  132. const { refId, key } = queries[index];
  133. query = generateNewKeyAndAddRefIdIfMissing({ refId, key }, queries, index);
  134. }
  135. dispatch(changeQueryAction({ exploreId, query, index, override }));
  136. if (override) {
  137. dispatch(runQueries(exploreId));
  138. }
  139. };
  140. }
  141. /**
  142. * Keep track of the Explore container size, in particular the width.
  143. * The width will be used to calculate graph intervals (number of datapoints).
  144. */
  145. export function changeSize(
  146. exploreId: ExploreId,
  147. { height, width }: { height: number; width: number }
  148. ): ActionOf<ChangeSizePayload> {
  149. return changeSizeAction({ exploreId, height, width });
  150. }
  151. export const updateTimeRange = (options: {
  152. exploreId: ExploreId;
  153. rawRange?: RawTimeRange;
  154. absoluteRange?: AbsoluteTimeRange;
  155. }): ThunkResult<void> => {
  156. return dispatch => {
  157. dispatch(updateTimeRangeAction({ ...options }));
  158. dispatch(runQueries(options.exploreId));
  159. };
  160. };
  161. /**
  162. * Change the refresh interval of Explore. Called from the Refresh picker.
  163. */
  164. export function changeRefreshInterval(
  165. exploreId: ExploreId,
  166. refreshInterval: string
  167. ): ActionOf<ChangeRefreshIntervalPayload> {
  168. return changeRefreshIntervalAction({ exploreId, refreshInterval });
  169. }
  170. /**
  171. * Clear all queries and results.
  172. */
  173. export function clearQueries(exploreId: ExploreId): ThunkResult<void> {
  174. return dispatch => {
  175. dispatch(scanStopAction({ exploreId }));
  176. dispatch(clearQueriesAction({ exploreId }));
  177. dispatch(stateSaveAction());
  178. };
  179. }
  180. /**
  181. * Loads all explore data sources and sets the chosen datasource.
  182. * If there are no datasources a missing datasource action is dispatched.
  183. */
  184. export function loadExploreDatasourcesAndSetDatasource(
  185. exploreId: ExploreId,
  186. datasourceName: string
  187. ): ThunkResult<void> {
  188. return dispatch => {
  189. const exploreDatasources: DataSourceSelectItem[] = getDatasourceSrv()
  190. .getExternal()
  191. .map(
  192. (ds: any) =>
  193. ({
  194. value: ds.name,
  195. name: ds.name,
  196. meta: ds.meta,
  197. } as DataSourceSelectItem)
  198. );
  199. dispatch(loadExploreDatasources({ exploreId, exploreDatasources }));
  200. if (exploreDatasources.length >= 1) {
  201. dispatch(changeDatasource(exploreId, datasourceName));
  202. } else {
  203. dispatch(loadDatasourceMissingAction({ exploreId }));
  204. }
  205. };
  206. }
  207. /**
  208. * Initialize Explore state with state from the URL and the React component.
  209. * Call this only on components for with the Explore state has not been initialized.
  210. */
  211. export function initializeExplore(
  212. exploreId: ExploreId,
  213. datasourceName: string,
  214. queries: DataQuery[],
  215. rawRange: RawTimeRange,
  216. containerWidth: number,
  217. eventBridge: Emitter,
  218. ui: ExploreUIState
  219. ): ThunkResult<void> {
  220. return async (dispatch, getState) => {
  221. const timeZone = getTimeZone(getState().user);
  222. const range = getTimeRange(timeZone, rawRange);
  223. dispatch(loadExploreDatasourcesAndSetDatasource(exploreId, datasourceName));
  224. dispatch(
  225. initializeExploreAction({
  226. exploreId,
  227. containerWidth,
  228. eventBridge,
  229. queries,
  230. range,
  231. ui,
  232. })
  233. );
  234. };
  235. }
  236. /**
  237. * Datasource loading was successfully completed.
  238. */
  239. export const loadDatasourceReady = (
  240. exploreId: ExploreId,
  241. instance: DataSourceApi
  242. ): ActionOf<LoadDatasourceReadyPayload> => {
  243. const historyKey = `grafana.explore.history.${instance.meta.id}`;
  244. const history = store.getObject(historyKey, []);
  245. // Save last-used datasource
  246. store.set(LAST_USED_DATASOURCE_KEY, instance.name);
  247. return loadDatasourceReadyAction({
  248. exploreId,
  249. history,
  250. });
  251. };
  252. export function importQueries(
  253. exploreId: ExploreId,
  254. queries: DataQuery[],
  255. sourceDataSource: DataSourceApi,
  256. targetDataSource: DataSourceApi
  257. ): ThunkResult<void> {
  258. return async dispatch => {
  259. if (!sourceDataSource) {
  260. // explore not initialized
  261. dispatch(queriesImportedAction({ exploreId, queries }));
  262. return;
  263. }
  264. let importedQueries = queries;
  265. // Check if queries can be imported from previously selected datasource
  266. if (sourceDataSource.meta.id === targetDataSource.meta.id) {
  267. // Keep same queries if same type of datasource
  268. importedQueries = [...queries];
  269. } else if (targetDataSource.importQueries) {
  270. // Datasource-specific importers
  271. importedQueries = await targetDataSource.importQueries(queries, sourceDataSource.meta);
  272. } else {
  273. // Default is blank queries
  274. importedQueries = ensureQueries();
  275. }
  276. const nextQueries = ensureQueries(importedQueries);
  277. dispatch(queriesImportedAction({ exploreId, queries: nextQueries }));
  278. };
  279. }
  280. /**
  281. * Tests datasource.
  282. */
  283. export const testDatasource = (exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> => {
  284. return async dispatch => {
  285. let datasourceError = null;
  286. dispatch(testDataSourcePendingAction({ exploreId }));
  287. try {
  288. const testResult = await instance.testDatasource();
  289. datasourceError = testResult.status === 'success' ? null : testResult.message;
  290. } catch (error) {
  291. datasourceError = (error && error.statusText) || 'Network error';
  292. }
  293. if (datasourceError) {
  294. dispatch(testDataSourceFailureAction({ exploreId, error: datasourceError }));
  295. return;
  296. }
  297. dispatch(testDataSourceSuccessAction({ exploreId }));
  298. };
  299. };
  300. /**
  301. * Reconnects datasource when there is a connection failure.
  302. */
  303. export const reconnectDatasource = (exploreId: ExploreId): ThunkResult<void> => {
  304. return async (dispatch, getState) => {
  305. const instance = getState().explore[exploreId].datasourceInstance;
  306. dispatch(changeDatasource(exploreId, instance.name));
  307. };
  308. };
  309. /**
  310. * Main action to asynchronously load a datasource. Dispatches lots of smaller actions for feedback.
  311. */
  312. export function loadDatasource(exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> {
  313. return async (dispatch, getState) => {
  314. const datasourceName = instance.name;
  315. // Keep ID to track selection
  316. dispatch(loadDatasourcePendingAction({ exploreId, requestedDatasourceName: datasourceName }));
  317. await dispatch(testDatasource(exploreId, instance));
  318. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  319. // User already changed datasource again, discard results
  320. return;
  321. }
  322. if (instance.init) {
  323. try {
  324. instance.init();
  325. } catch (err) {
  326. console.log(err);
  327. }
  328. }
  329. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  330. // User already changed datasource again, discard results
  331. return;
  332. }
  333. dispatch(loadDatasourceReady(exploreId, instance));
  334. };
  335. }
  336. /**
  337. * Action to modify a query given a datasource-specific modifier action.
  338. * @param exploreId Explore area
  339. * @param modification Action object with a type, e.g., ADD_FILTER
  340. * @param index Optional query row index. If omitted, the modification is applied to all query rows.
  341. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
  342. */
  343. export function modifyQueries(
  344. exploreId: ExploreId,
  345. modification: QueryFixAction,
  346. index: number,
  347. modifier: any
  348. ): ThunkResult<void> {
  349. return dispatch => {
  350. dispatch(modifyQueriesAction({ exploreId, modification, index, modifier }));
  351. if (!modification.preventSubmit) {
  352. dispatch(runQueries(exploreId));
  353. }
  354. };
  355. }
  356. /**
  357. * Main action to run queries and dispatches sub-actions based on which result viewers are active
  358. */
  359. export function runQueries(exploreId: ExploreId): ThunkResult<void> {
  360. return (dispatch, getState) => {
  361. dispatch(updateTimeRangeAction({ exploreId }));
  362. dispatch(runQueriesAction({ exploreId }));
  363. };
  364. }
  365. /**
  366. * Start a scan for more results using the given scanner.
  367. * @param exploreId Explore area
  368. * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range
  369. */
  370. export function scanStart(exploreId: ExploreId, scanner: RangeScanner): ThunkResult<void> {
  371. return dispatch => {
  372. // Register the scanner
  373. dispatch(scanStartAction({ exploreId, scanner }));
  374. // Scanning must trigger query run, and return the new range
  375. const range = scanner();
  376. // Set the new range to be displayed
  377. dispatch(scanRangeAction({ exploreId, range }));
  378. };
  379. }
  380. /**
  381. * Reset queries to the given queries. Any modifications will be discarded.
  382. * Use this action for clicks on query examples. Triggers a query run.
  383. */
  384. export function setQueries(exploreId: ExploreId, rawQueries: DataQuery[]): ThunkResult<void> {
  385. return (dispatch, getState) => {
  386. // Inject react keys into query objects
  387. const queries = getState().explore[exploreId].queries;
  388. const nextQueries = rawQueries.map((query, index) => generateNewKeyAndAddRefIdIfMissing(query, queries, index));
  389. dispatch(setQueriesAction({ exploreId, queries: nextQueries }));
  390. dispatch(runQueries(exploreId));
  391. };
  392. }
  393. /**
  394. * Close the split view and save URL state.
  395. */
  396. export function splitClose(itemId: ExploreId): ThunkResult<void> {
  397. return dispatch => {
  398. dispatch(splitCloseAction({ itemId }));
  399. dispatch(stateSaveAction());
  400. };
  401. }
  402. /**
  403. * Open the split view and copy the left state to be the right state.
  404. * The right state is automatically initialized.
  405. * The copy keeps all query modifications but wipes the query results.
  406. */
  407. export function splitOpen(): ThunkResult<void> {
  408. return (dispatch, getState) => {
  409. // Clone left state to become the right state
  410. const leftState = getState().explore[ExploreId.left];
  411. const queryState = getState().location.query[ExploreId.left] as string;
  412. const urlState = parseUrlState(queryState);
  413. const queryTransactions: QueryTransaction[] = [];
  414. const itemState = {
  415. ...leftState,
  416. queryTransactions,
  417. queries: leftState.queries.slice(),
  418. exploreId: ExploreId.right,
  419. urlState,
  420. };
  421. dispatch(splitOpenAction({ itemState }));
  422. dispatch(stateSaveAction());
  423. };
  424. }
  425. /**
  426. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  427. * queries won't be run
  428. */
  429. const togglePanelActionCreator = (
  430. actionCreator: ActionCreator<ToggleGraphPayload> | ActionCreator<ToggleTablePayload>
  431. ) => (exploreId: ExploreId, isPanelVisible: boolean): ThunkResult<void> => {
  432. return dispatch => {
  433. let uiFragmentStateUpdate: Partial<ExploreUIState>;
  434. const shouldRunQueries = !isPanelVisible;
  435. switch (actionCreator.type) {
  436. case toggleGraphAction.type:
  437. uiFragmentStateUpdate = { showingGraph: !isPanelVisible };
  438. break;
  439. case toggleTableAction.type:
  440. uiFragmentStateUpdate = { showingTable: !isPanelVisible };
  441. break;
  442. }
  443. dispatch(actionCreator({ exploreId }));
  444. dispatch(updateExploreUIState(exploreId, uiFragmentStateUpdate));
  445. if (shouldRunQueries) {
  446. dispatch(runQueries(exploreId));
  447. }
  448. };
  449. };
  450. /**
  451. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  452. */
  453. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  454. /**
  455. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  456. */
  457. export const toggleTable = togglePanelActionCreator(toggleTableAction);
  458. /**
  459. * Change logs deduplication strategy and update URL.
  460. */
  461. export const changeDedupStrategy = (exploreId: ExploreId, dedupStrategy: LogsDedupStrategy): ThunkResult<void> => {
  462. return dispatch => {
  463. dispatch(updateExploreUIState(exploreId, { dedupStrategy }));
  464. };
  465. };
  466. export function refreshExplore(exploreId: ExploreId): ThunkResult<void> {
  467. return (dispatch, getState) => {
  468. const itemState = getState().explore[exploreId];
  469. if (!itemState.initialized) {
  470. return;
  471. }
  472. const { urlState, update, containerWidth, eventBridge } = itemState;
  473. const { datasource, queries, range: urlRange, ui } = urlState;
  474. const refreshQueries: DataQuery[] = [];
  475. for (let index = 0; index < queries.length; index++) {
  476. const query = queries[index];
  477. refreshQueries.push(generateNewKeyAndAddRefIdIfMissing(query, refreshQueries, index));
  478. }
  479. const timeZone = getTimeZone(getState().user);
  480. const range = getTimeRangeFromUrl(urlRange, timeZone);
  481. // need to refresh datasource
  482. if (update.datasource) {
  483. const initialQueries = ensureQueries(queries);
  484. dispatch(initializeExplore(exploreId, datasource, initialQueries, range, containerWidth, eventBridge, ui));
  485. return;
  486. }
  487. if (update.range) {
  488. dispatch(updateTimeRangeAction({ exploreId, rawRange: range.raw }));
  489. }
  490. // need to refresh ui state
  491. if (update.ui) {
  492. dispatch(updateUIStateAction({ ...ui, exploreId }));
  493. }
  494. // need to refresh queries
  495. if (update.queries) {
  496. dispatch(setQueriesAction({ exploreId, queries: refreshQueries }));
  497. }
  498. // always run queries when refresh is needed
  499. if (update.queries || update.ui || update.range) {
  500. dispatch(runQueries(exploreId));
  501. }
  502. };
  503. }