actions.ts 17 KB

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