actions.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. ensureQueries,
  9. generateEmptyQuery,
  10. parseUrlState,
  11. getTimeRange,
  12. getTimeRangeFromUrl,
  13. generateNewKeyAndAddRefIdIfMissing,
  14. lastUsedDatasourceKeyForOrgId,
  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, 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. runQueriesAction,
  60. stateSaveAction,
  61. updateTimeRangeAction,
  62. } from './actionTypes';
  63. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  64. import { getTimeZone } from 'app/features/profile/state/selectors';
  65. import { offOption } from '@grafana/ui/src/components/RefreshPicker/RefreshPicker';
  66. import { getShiftedTimeRange } from 'app/core/utils/timePicker';
  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. const orgId = getState().user.orgId;
  100. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: newDataSourceInstance }));
  101. await dispatch(importQueries(exploreId, queries, currentDataSourceInstance, newDataSourceInstance));
  102. if (getState().explore[exploreId].isLive) {
  103. dispatch(changeRefreshInterval(exploreId, offOption.value));
  104. }
  105. await dispatch(loadDatasource(exploreId, newDataSourceInstance, orgId));
  106. dispatch(runQueries(exploreId));
  107. };
  108. }
  109. /**
  110. * Change the display mode in Explore.
  111. */
  112. export function changeMode(exploreId: ExploreId, mode: ExploreMode): ThunkResult<void> {
  113. return dispatch => {
  114. dispatch(clearQueriesAction({ exploreId }));
  115. dispatch(changeModeAction({ exploreId, mode }));
  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. mode: ExploreMode,
  217. containerWidth: number,
  218. eventBridge: Emitter,
  219. ui: ExploreUIState
  220. ): ThunkResult<void> {
  221. return async (dispatch, getState) => {
  222. const timeZone = getTimeZone(getState().user);
  223. const range = getTimeRange(timeZone, rawRange);
  224. dispatch(loadExploreDatasourcesAndSetDatasource(exploreId, datasourceName));
  225. dispatch(
  226. initializeExploreAction({
  227. exploreId,
  228. containerWidth,
  229. eventBridge,
  230. queries,
  231. range,
  232. mode,
  233. ui,
  234. })
  235. );
  236. };
  237. }
  238. /**
  239. * Datasource loading was successfully completed.
  240. */
  241. export const loadDatasourceReady = (
  242. exploreId: ExploreId,
  243. instance: DataSourceApi,
  244. orgId: number
  245. ): ActionOf<LoadDatasourceReadyPayload> => {
  246. const historyKey = `grafana.explore.history.${instance.meta.id}`;
  247. const history = store.getObject(historyKey, []);
  248. // Save last-used datasource
  249. store.set(lastUsedDatasourceKeyForOrgId(orgId), instance.name);
  250. return loadDatasourceReadyAction({
  251. exploreId,
  252. history,
  253. });
  254. };
  255. export function importQueries(
  256. exploreId: ExploreId,
  257. queries: DataQuery[],
  258. sourceDataSource: DataSourceApi,
  259. targetDataSource: DataSourceApi
  260. ): ThunkResult<void> {
  261. return async dispatch => {
  262. if (!sourceDataSource) {
  263. // explore not initialized
  264. dispatch(queriesImportedAction({ exploreId, queries }));
  265. return;
  266. }
  267. let importedQueries = queries;
  268. // Check if queries can be imported from previously selected datasource
  269. if (sourceDataSource.meta.id === targetDataSource.meta.id) {
  270. // Keep same queries if same type of datasource
  271. importedQueries = [...queries];
  272. } else if (targetDataSource.importQueries) {
  273. // Datasource-specific importers
  274. importedQueries = await targetDataSource.importQueries(queries, sourceDataSource.meta);
  275. } else {
  276. // Default is blank queries
  277. importedQueries = ensureQueries();
  278. }
  279. const nextQueries = ensureQueries(importedQueries);
  280. dispatch(queriesImportedAction({ exploreId, queries: nextQueries }));
  281. };
  282. }
  283. /**
  284. * Tests datasource.
  285. */
  286. export const testDatasource = (exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> => {
  287. return async dispatch => {
  288. let datasourceError = null;
  289. dispatch(testDataSourcePendingAction({ exploreId }));
  290. try {
  291. const testResult = await instance.testDatasource();
  292. datasourceError = testResult.status === 'success' ? null : testResult.message;
  293. } catch (error) {
  294. datasourceError = (error && error.statusText) || 'Network error';
  295. }
  296. if (datasourceError) {
  297. dispatch(testDataSourceFailureAction({ exploreId, error: datasourceError }));
  298. return;
  299. }
  300. dispatch(testDataSourceSuccessAction({ exploreId }));
  301. };
  302. };
  303. /**
  304. * Reconnects datasource when there is a connection failure.
  305. */
  306. export const reconnectDatasource = (exploreId: ExploreId): ThunkResult<void> => {
  307. return async (dispatch, getState) => {
  308. const instance = getState().explore[exploreId].datasourceInstance;
  309. dispatch(changeDatasource(exploreId, instance.name));
  310. };
  311. };
  312. /**
  313. * Main action to asynchronously load a datasource. Dispatches lots of smaller actions for feedback.
  314. */
  315. export function loadDatasource(exploreId: ExploreId, instance: DataSourceApi, orgId: number): ThunkResult<void> {
  316. return async (dispatch, getState) => {
  317. const datasourceName = instance.name;
  318. // Keep ID to track selection
  319. dispatch(loadDatasourcePendingAction({ exploreId, requestedDatasourceName: datasourceName }));
  320. await dispatch(testDatasource(exploreId, instance));
  321. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  322. // User already changed datasource again, discard results
  323. return;
  324. }
  325. if (instance.init) {
  326. try {
  327. instance.init();
  328. } catch (err) {
  329. console.log(err);
  330. }
  331. }
  332. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  333. // User already changed datasource again, discard results
  334. return;
  335. }
  336. dispatch(loadDatasourceReady(exploreId, instance, orgId));
  337. };
  338. }
  339. /**
  340. * Action to modify a query given a datasource-specific modifier action.
  341. * @param exploreId Explore area
  342. * @param modification Action object with a type, e.g., ADD_FILTER
  343. * @param index Optional query row index. If omitted, the modification is applied to all query rows.
  344. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
  345. */
  346. export function modifyQueries(
  347. exploreId: ExploreId,
  348. modification: QueryFixAction,
  349. index: number,
  350. modifier: any
  351. ): ThunkResult<void> {
  352. return dispatch => {
  353. dispatch(modifyQueriesAction({ exploreId, modification, index, modifier }));
  354. if (!modification.preventSubmit) {
  355. dispatch(runQueries(exploreId));
  356. }
  357. };
  358. }
  359. /**
  360. * Main action to run queries and dispatches sub-actions based on which result viewers are active
  361. */
  362. export function runQueries(exploreId: ExploreId): ThunkResult<void> {
  363. return (dispatch, getState) => {
  364. dispatch(updateTimeRangeAction({ exploreId }));
  365. dispatch(runQueriesAction({ exploreId }));
  366. };
  367. }
  368. /**
  369. * Start a scan for more results using the given scanner.
  370. * @param exploreId Explore area
  371. * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range
  372. */
  373. export function scanStart(exploreId: ExploreId): ThunkResult<void> {
  374. return (dispatch, getState) => {
  375. // Register the scanner
  376. dispatch(scanStartAction({ exploreId }));
  377. // Scanning must trigger query run, and return the new range
  378. const range = getShiftedTimeRange(-1, getState().explore[exploreId].range);
  379. // Set the new range to be displayed
  380. dispatch(updateTimeRangeAction({ exploreId, absoluteRange: range }));
  381. dispatch(runQueriesAction({ exploreId }));
  382. };
  383. }
  384. /**
  385. * Reset queries to the given queries. Any modifications will be discarded.
  386. * Use this action for clicks on query examples. Triggers a query run.
  387. */
  388. export function setQueries(exploreId: ExploreId, rawQueries: DataQuery[]): ThunkResult<void> {
  389. return (dispatch, getState) => {
  390. // Inject react keys into query objects
  391. const queries = getState().explore[exploreId].queries;
  392. const nextQueries = rawQueries.map((query, index) => generateNewKeyAndAddRefIdIfMissing(query, queries, index));
  393. dispatch(setQueriesAction({ exploreId, queries: nextQueries }));
  394. dispatch(runQueries(exploreId));
  395. };
  396. }
  397. /**
  398. * Close the split view and save URL state.
  399. */
  400. export function splitClose(itemId: ExploreId): ThunkResult<void> {
  401. return dispatch => {
  402. dispatch(splitCloseAction({ itemId }));
  403. dispatch(stateSaveAction());
  404. };
  405. }
  406. /**
  407. * Open the split view and copy the left state to be the right state.
  408. * The right state is automatically initialized.
  409. * The copy keeps all query modifications but wipes the query results.
  410. */
  411. export function splitOpen(): ThunkResult<void> {
  412. return (dispatch, getState) => {
  413. // Clone left state to become the right state
  414. const leftState = getState().explore[ExploreId.left];
  415. const queryState = getState().location.query[ExploreId.left] as string;
  416. const urlState = parseUrlState(queryState);
  417. const queryTransactions: QueryTransaction[] = [];
  418. const itemState = {
  419. ...leftState,
  420. queryTransactions,
  421. queries: leftState.queries.slice(),
  422. exploreId: ExploreId.right,
  423. urlState,
  424. };
  425. dispatch(splitOpenAction({ itemState }));
  426. dispatch(stateSaveAction());
  427. };
  428. }
  429. /**
  430. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  431. * queries won't be run
  432. */
  433. const togglePanelActionCreator = (
  434. actionCreator: ActionCreator<ToggleGraphPayload> | ActionCreator<ToggleTablePayload>
  435. ) => (exploreId: ExploreId, isPanelVisible: boolean): ThunkResult<void> => {
  436. return dispatch => {
  437. let uiFragmentStateUpdate: Partial<ExploreUIState>;
  438. const shouldRunQueries = !isPanelVisible;
  439. switch (actionCreator.type) {
  440. case toggleGraphAction.type:
  441. uiFragmentStateUpdate = { showingGraph: !isPanelVisible };
  442. break;
  443. case toggleTableAction.type:
  444. uiFragmentStateUpdate = { showingTable: !isPanelVisible };
  445. break;
  446. }
  447. dispatch(actionCreator({ exploreId }));
  448. dispatch(updateExploreUIState(exploreId, uiFragmentStateUpdate));
  449. if (shouldRunQueries) {
  450. dispatch(runQueries(exploreId));
  451. }
  452. };
  453. };
  454. /**
  455. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  456. */
  457. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  458. /**
  459. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  460. */
  461. export const toggleTable = togglePanelActionCreator(toggleTableAction);
  462. /**
  463. * Change logs deduplication strategy and update URL.
  464. */
  465. export const changeDedupStrategy = (exploreId: ExploreId, dedupStrategy: LogsDedupStrategy): ThunkResult<void> => {
  466. return dispatch => {
  467. dispatch(updateExploreUIState(exploreId, { dedupStrategy }));
  468. };
  469. };
  470. export function refreshExplore(exploreId: ExploreId): ThunkResult<void> {
  471. return (dispatch, getState) => {
  472. const itemState = getState().explore[exploreId];
  473. if (!itemState.initialized) {
  474. return;
  475. }
  476. const { urlState, update, containerWidth, eventBridge } = itemState;
  477. const { datasource, queries, range: urlRange, mode, ui } = urlState;
  478. const refreshQueries: DataQuery[] = [];
  479. for (let index = 0; index < queries.length; index++) {
  480. const query = queries[index];
  481. refreshQueries.push(generateNewKeyAndAddRefIdIfMissing(query, refreshQueries, index));
  482. }
  483. const timeZone = getTimeZone(getState().user);
  484. const range = getTimeRangeFromUrl(urlRange, timeZone);
  485. // need to refresh datasource
  486. if (update.datasource) {
  487. const initialQueries = ensureQueries(queries);
  488. dispatch(initializeExplore(exploreId, datasource, initialQueries, range, mode, containerWidth, eventBridge, ui));
  489. return;
  490. }
  491. if (update.range) {
  492. dispatch(updateTimeRangeAction({ exploreId, rawRange: range.raw }));
  493. }
  494. // need to refresh ui state
  495. if (update.ui) {
  496. dispatch(updateUIStateAction({ ...ui, exploreId }));
  497. }
  498. // need to refresh queries
  499. if (update.queries) {
  500. dispatch(setQueriesAction({ exploreId, queries: refreshQueries }));
  501. }
  502. // need to refresh mode
  503. if (update.mode) {
  504. dispatch(changeModeAction({ exploreId, mode }));
  505. }
  506. // always run queries when refresh is needed
  507. if (update.queries || update.ui || update.range) {
  508. dispatch(runQueries(exploreId));
  509. }
  510. };
  511. }