actions.ts 17 KB

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