initDashboard.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Services & Utils
  2. import { createErrorNotification } from 'app/core/copy/appNotification';
  3. import { getBackendSrv } from 'app/core/services/backend_srv';
  4. import { DashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
  5. import { DashboardLoaderSrv } from 'app/features/dashboard/services/DashboardLoaderSrv';
  6. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  7. import { AnnotationsSrv } from 'app/features/annotations/annotations_srv';
  8. import { VariableSrv } from 'app/features/templating/variable_srv';
  9. import { KeybindingSrv } from 'app/core/services/keybindingSrv';
  10. // Actions
  11. import { updateLocation } from 'app/core/actions';
  12. import { notifyApp } from 'app/core/actions';
  13. import locationUtil from 'app/core/utils/location_util';
  14. import {
  15. dashboardInitFetching,
  16. dashboardInitCompleted,
  17. dashboardInitFailed,
  18. dashboardInitSlow,
  19. dashboardInitServices,
  20. } from './actions';
  21. // Types
  22. import { DashboardRouteInfo, StoreState, ThunkDispatch, ThunkResult, DashboardDTO, ExploreItemState } from 'app/types';
  23. import { DashboardModel } from './DashboardModel';
  24. import { resetExploreAction } from 'app/features/explore/state/actionTypes';
  25. import { DataQuery } from '@grafana/ui';
  26. export interface InitDashboardArgs {
  27. $injector: any;
  28. $scope: any;
  29. urlUid?: string;
  30. urlSlug?: string;
  31. urlType?: string;
  32. urlFolderId?: string;
  33. routeInfo: DashboardRouteInfo;
  34. fixUrl: boolean;
  35. }
  36. async function redirectToNewUrl(slug: string, dispatch: ThunkDispatch, currentPath: string) {
  37. const res = await getBackendSrv().getDashboardBySlug(slug);
  38. if (res) {
  39. let newUrl = res.meta.url;
  40. // fix solo route urls
  41. if (currentPath.indexOf('dashboard-solo') !== -1) {
  42. newUrl = newUrl.replace('/d/', '/d-solo/');
  43. }
  44. const url = locationUtil.stripBaseFromUrl(newUrl);
  45. dispatch(updateLocation({ path: url, partial: true, replace: true }));
  46. }
  47. }
  48. async function fetchDashboard(
  49. args: InitDashboardArgs,
  50. dispatch: ThunkDispatch,
  51. getState: () => StoreState
  52. ): Promise<DashboardDTO | null> {
  53. try {
  54. switch (args.routeInfo) {
  55. case DashboardRouteInfo.Home: {
  56. // load home dash
  57. const dashDTO: DashboardDTO = await getBackendSrv().get('/api/dashboards/home');
  58. // if user specified a custom home dashboard redirect to that
  59. if (dashDTO.redirectUri) {
  60. const newUrl = locationUtil.stripBaseFromUrl(dashDTO.redirectUri);
  61. dispatch(updateLocation({ path: newUrl, replace: true }));
  62. return null;
  63. }
  64. // disable some actions on the default home dashboard
  65. dashDTO.meta.canSave = false;
  66. dashDTO.meta.canShare = false;
  67. dashDTO.meta.canStar = false;
  68. return dashDTO;
  69. }
  70. case DashboardRouteInfo.Normal: {
  71. // for old db routes we redirect
  72. if (args.urlType === 'db') {
  73. redirectToNewUrl(args.urlSlug, dispatch, getState().location.path);
  74. return null;
  75. }
  76. const loaderSrv: DashboardLoaderSrv = args.$injector.get('dashboardLoaderSrv');
  77. const dashDTO: DashboardDTO = await loaderSrv.loadDashboard(args.urlType, args.urlSlug, args.urlUid);
  78. if (args.fixUrl && dashDTO.meta.url) {
  79. // check if the current url is correct (might be old slug)
  80. const dashboardUrl = locationUtil.stripBaseFromUrl(dashDTO.meta.url);
  81. const currentPath = getState().location.path;
  82. if (dashboardUrl !== currentPath) {
  83. // replace url to not create additional history items and then return so that initDashboard below isn't executed multiple times.
  84. dispatch(updateLocation({ path: dashboardUrl, partial: true, replace: true }));
  85. return null;
  86. }
  87. }
  88. return dashDTO;
  89. }
  90. case DashboardRouteInfo.New: {
  91. return getNewDashboardModelData(args.urlFolderId);
  92. }
  93. default:
  94. throw { message: 'Unknown route ' + args.routeInfo };
  95. }
  96. } catch (err) {
  97. dispatch(dashboardInitFailed({ message: 'Failed to fetch dashboard', error: err }));
  98. console.log(err);
  99. return null;
  100. }
  101. }
  102. /**
  103. * This action (or saga) does everything needed to bootstrap a dashboard & dashboard model.
  104. * First it handles the process of fetching the dashboard, correcting the url if required (causing redirects/url updates)
  105. *
  106. * This is used both for single dashboard & solo panel routes, home & new dashboard routes.
  107. *
  108. * Then it handles the initializing of the old angular services that the dashboard components & panels still depend on
  109. *
  110. */
  111. export function initDashboard(args: InitDashboardArgs): ThunkResult<void> {
  112. return async (dispatch, getState) => {
  113. // set fetching state
  114. dispatch(dashboardInitFetching());
  115. // Detect slow loading / initializing and set state flag
  116. // This is in order to not show loading indication for fast loading dashboards as it creates blinking/flashing
  117. setTimeout(() => {
  118. if (getState().dashboard.model === null) {
  119. dispatch(dashboardInitSlow());
  120. }
  121. }, 500);
  122. // fetch dashboard data
  123. const dashDTO = await fetchDashboard(args, dispatch, getState);
  124. // returns null if there was a redirect or error
  125. if (!dashDTO) {
  126. return;
  127. }
  128. // set initializing state
  129. dispatch(dashboardInitServices());
  130. // create model
  131. let dashboard: DashboardModel;
  132. try {
  133. dashboard = new DashboardModel(dashDTO.dashboard, dashDTO.meta);
  134. } catch (err) {
  135. dispatch(dashboardInitFailed({ message: 'Failed create dashboard model', error: err }));
  136. console.log(err);
  137. return;
  138. }
  139. // add missing orgId query param
  140. const storeState = getState();
  141. if (!storeState.location.query.orgId) {
  142. dispatch(updateLocation({ query: { orgId: storeState.user.orgId }, partial: true, replace: true }));
  143. }
  144. // init services
  145. const timeSrv: TimeSrv = args.$injector.get('timeSrv');
  146. const annotationsSrv: AnnotationsSrv = args.$injector.get('annotationsSrv');
  147. const variableSrv: VariableSrv = args.$injector.get('variableSrv');
  148. const keybindingSrv: KeybindingSrv = args.$injector.get('keybindingSrv');
  149. const unsavedChangesSrv = args.$injector.get('unsavedChangesSrv');
  150. const dashboardSrv: DashboardSrv = args.$injector.get('dashboardSrv');
  151. timeSrv.init(dashboard);
  152. annotationsSrv.init(dashboard);
  153. const left = storeState.explore && storeState.explore.left;
  154. dashboard.meta.fromExplore = !!(left && left.originPanelId);
  155. // template values service needs to initialize completely before
  156. // the rest of the dashboard can load
  157. try {
  158. await variableSrv.init(dashboard);
  159. } catch (err) {
  160. dispatch(notifyApp(createErrorNotification('Templating init failed', err)));
  161. console.log(err);
  162. }
  163. try {
  164. dashboard.processRepeats();
  165. dashboard.updateSubmenuVisibility();
  166. // handle auto fix experimental feature
  167. const queryParams = getState().location.query;
  168. if (queryParams.autofitpanels) {
  169. dashboard.autoFitPanels(window.innerHeight, queryParams.kiosk);
  170. }
  171. // init unsaved changes tracking
  172. unsavedChangesSrv.init(dashboard, args.$scope);
  173. keybindingSrv.setupDashboardBindings(args.$scope, dashboard);
  174. } catch (err) {
  175. dispatch(notifyApp(createErrorNotification('Dashboard init failed', err)));
  176. console.log(err);
  177. }
  178. if (dashboard.meta.fromExplore) {
  179. updateQueriesWhenComingFromExplore(dispatch, dashboard, left);
  180. }
  181. // legacy srv state
  182. dashboardSrv.setCurrent(dashboard);
  183. // yay we are done
  184. dispatch(dashboardInitCompleted(dashboard));
  185. };
  186. }
  187. function getNewDashboardModelData(urlFolderId?: string): any {
  188. const data = {
  189. meta: {
  190. canStar: false,
  191. canShare: false,
  192. isNew: true,
  193. folderId: 0,
  194. },
  195. dashboard: {
  196. title: 'New dashboard',
  197. panels: [
  198. {
  199. type: 'add-panel',
  200. gridPos: { x: 0, y: 0, w: 12, h: 9 },
  201. title: 'Panel Title',
  202. },
  203. ],
  204. },
  205. };
  206. if (urlFolderId) {
  207. data.meta.folderId = parseInt(urlFolderId, 10);
  208. }
  209. return data;
  210. }
  211. function updateQueriesWhenComingFromExplore(
  212. dispatch: ThunkDispatch,
  213. dashboard: DashboardModel,
  214. left: ExploreItemState
  215. ) {
  216. // When returning to the origin panel from explore, if we're doing
  217. // so with changes all the explore state is reset _except_ the queries
  218. // and the origin panel ID.
  219. const panelArrId = dashboard.panels.findIndex(panel => panel.id === left.originPanelId);
  220. if (panelArrId > -1) {
  221. dashboard.panels[panelArrId].targets = left.queries.map((query: DataQuery & { context?: string }) => {
  222. delete query.context;
  223. delete query.key;
  224. return query;
  225. });
  226. }
  227. dashboard.startRefresh();
  228. // Force-reset explore so that on subsequent dashboard loads we aren't
  229. // taking the modified queries from explore again.
  230. dispatch(resetExploreAction({ force: true }));
  231. }