backend_srv.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import _ from 'lodash';
  2. import angular from 'angular';
  3. import coreModule from 'app/core/core_module';
  4. import appEvents from 'app/core/app_events';
  5. import config from 'app/core/config';
  6. import { DashboardModel } from 'app/features/dashboard/state/DashboardModel';
  7. import { DashboardSearchHit } from 'app/types/search';
  8. import { ContextSrv } from './context_srv';
  9. import { FolderInfo, DashboardDTO } from 'app/types';
  10. export class BackendSrv {
  11. private inFlightRequests: { [key: string]: Array<angular.IDeferred<any>> } = {};
  12. private HTTP_REQUEST_CANCELED = -1;
  13. private noBackendCache: boolean;
  14. /** @ngInject */
  15. constructor(
  16. private $http: any,
  17. private $q: angular.IQService,
  18. private $timeout: angular.ITimeoutService,
  19. private contextSrv: ContextSrv
  20. ) {}
  21. get(url: string, params?: any) {
  22. return this.request({ method: 'GET', url, params });
  23. }
  24. delete(url: string) {
  25. return this.request({ method: 'DELETE', url });
  26. }
  27. post(url: string, data: any) {
  28. return this.request({ method: 'POST', url, data });
  29. }
  30. patch(url: string, data: any) {
  31. return this.request({ method: 'PATCH', url, data });
  32. }
  33. put(url: string, data: any) {
  34. return this.request({ method: 'PUT', url, data });
  35. }
  36. withNoBackendCache(callback: any) {
  37. this.noBackendCache = true;
  38. return callback().finally(() => {
  39. this.noBackendCache = false;
  40. });
  41. }
  42. requestErrorHandler(err: any) {
  43. if (err.isHandled) {
  44. return;
  45. }
  46. let data = err.data || { message: 'Unexpected error' };
  47. if (_.isString(data)) {
  48. data = { message: data };
  49. }
  50. if (err.status === 422) {
  51. appEvents.emit('alert-warning', ['Validation failed', data.message]);
  52. throw data;
  53. }
  54. let severity = 'error';
  55. if (err.status < 500) {
  56. severity = 'warning';
  57. }
  58. if (data.message) {
  59. let description = '';
  60. let message = data.message;
  61. if (message.length > 80) {
  62. description = message;
  63. message = 'Error';
  64. }
  65. appEvents.emit('alert-' + severity, [message, description]);
  66. }
  67. throw data;
  68. }
  69. request(options: any) {
  70. options.retry = options.retry || 0;
  71. const requestIsLocal = !options.url.match(/^http/);
  72. const firstAttempt = options.retry === 0;
  73. if (requestIsLocal) {
  74. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  75. options.headers = options.headers || {};
  76. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  77. }
  78. if (options.url.indexOf('/') === 0) {
  79. options.url = options.url.substring(1);
  80. }
  81. }
  82. return this.$http(options).then(
  83. (results: any) => {
  84. if (options.method !== 'GET') {
  85. if (results && results.data.message) {
  86. if (options.showSuccessAlert !== false) {
  87. appEvents.emit('alert-success', [results.data.message]);
  88. }
  89. }
  90. }
  91. return results.data;
  92. },
  93. (err: any) => {
  94. // handle unauthorized
  95. if (err.status === 401 && this.contextSrv.user.isSignedIn && firstAttempt) {
  96. return this.loginPing()
  97. .then(() => {
  98. options.retry = 1;
  99. return this.request(options);
  100. })
  101. .catch((err: any) => {
  102. if (err.status === 401) {
  103. window.location.href = config.appSubUrl + '/logout';
  104. throw err;
  105. }
  106. });
  107. }
  108. this.$timeout(this.requestErrorHandler.bind(this, err), 50);
  109. throw err;
  110. }
  111. );
  112. }
  113. addCanceler(requestId: string, canceler: angular.IDeferred<any>) {
  114. if (requestId in this.inFlightRequests) {
  115. this.inFlightRequests[requestId].push(canceler);
  116. } else {
  117. this.inFlightRequests[requestId] = [canceler];
  118. }
  119. }
  120. resolveCancelerIfExists(requestId: string) {
  121. const cancelers = this.inFlightRequests[requestId];
  122. if (!_.isUndefined(cancelers) && cancelers.length) {
  123. cancelers[0].resolve();
  124. }
  125. }
  126. datasourceRequest(options: any) {
  127. let canceler: angular.IDeferred<any> = null;
  128. options.retry = options.retry || 0;
  129. // A requestID is provided by the datasource as a unique identifier for a
  130. // particular query. If the requestID exists, the promise it is keyed to
  131. // is canceled, canceling the previous datasource request if it is still
  132. // in-flight.
  133. const requestId = options.requestId;
  134. if (requestId) {
  135. this.resolveCancelerIfExists(requestId);
  136. // create new canceler
  137. canceler = this.$q.defer();
  138. options.timeout = canceler.promise;
  139. this.addCanceler(requestId, canceler);
  140. }
  141. const requestIsLocal = !options.url.match(/^http/);
  142. const firstAttempt = options.retry === 0;
  143. if (requestIsLocal) {
  144. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  145. options.headers = options.headers || {};
  146. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  147. }
  148. if (options.url.indexOf('/') === 0) {
  149. options.url = options.url.substring(1);
  150. }
  151. if (options.headers && options.headers.Authorization) {
  152. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  153. delete options.headers.Authorization;
  154. }
  155. if (this.noBackendCache) {
  156. options.headers['X-Grafana-NoCache'] = 'true';
  157. }
  158. }
  159. return this.$http(options)
  160. .then((response: any) => {
  161. if (!options.silent) {
  162. appEvents.emit('ds-request-response', response);
  163. }
  164. return response;
  165. })
  166. .catch((err: any) => {
  167. if (err.status === this.HTTP_REQUEST_CANCELED) {
  168. throw { err, cancelled: true };
  169. }
  170. // handle unauthorized for backend requests
  171. if (requestIsLocal && firstAttempt && err.status === 401) {
  172. return this.loginPing()
  173. .then(() => {
  174. options.retry = 1;
  175. if (canceler) {
  176. canceler.resolve();
  177. }
  178. return this.datasourceRequest(options);
  179. })
  180. .catch((err: any) => {
  181. if (err.status === 401) {
  182. window.location.href = config.appSubUrl + '/logout';
  183. throw err;
  184. }
  185. });
  186. }
  187. // populate error obj on Internal Error
  188. if (_.isString(err.data) && err.status === 500) {
  189. err.data = {
  190. error: err.statusText,
  191. response: err.data,
  192. };
  193. }
  194. // for Prometheus
  195. if (err.data && !err.data.message && _.isString(err.data.error)) {
  196. err.data.message = err.data.error;
  197. }
  198. if (!options.silent) {
  199. appEvents.emit('ds-request-error', err);
  200. }
  201. throw err;
  202. })
  203. .finally(() => {
  204. // clean up
  205. if (options.requestId) {
  206. this.inFlightRequests[options.requestId].shift();
  207. }
  208. });
  209. }
  210. loginPing() {
  211. return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
  212. }
  213. search(query: any): Promise<DashboardSearchHit[]> {
  214. return this.get('/api/search', query);
  215. }
  216. getDashboardBySlug(slug: string) {
  217. return this.get(`/api/dashboards/db/${slug}`);
  218. }
  219. getDashboardByUid(uid: string) {
  220. return this.get(`/api/dashboards/uid/${uid}`);
  221. }
  222. getFolderByUid(uid: string) {
  223. return this.get(`/api/folders/${uid}`);
  224. }
  225. saveDashboard(dash: DashboardModel, options: any) {
  226. options = options || {};
  227. return this.post('/api/dashboards/db/', {
  228. dashboard: dash,
  229. folderId: options.folderId,
  230. overwrite: options.overwrite === true,
  231. message: options.message || '',
  232. });
  233. }
  234. createFolder(payload: any) {
  235. return this.post('/api/folders', payload);
  236. }
  237. deleteFolder(uid: string, showSuccessAlert: boolean) {
  238. return this.request({ method: 'DELETE', url: `/api/folders/${uid}`, showSuccessAlert: showSuccessAlert === true });
  239. }
  240. deleteDashboard(uid: string, showSuccessAlert: boolean) {
  241. return this.request({
  242. method: 'DELETE',
  243. url: `/api/dashboards/uid/${uid}`,
  244. showSuccessAlert: showSuccessAlert === true,
  245. });
  246. }
  247. deleteFoldersAndDashboards(folderUids: string[], dashboardUids: string[]) {
  248. const tasks = [];
  249. for (const folderUid of folderUids) {
  250. tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true));
  251. }
  252. for (const dashboardUid of dashboardUids) {
  253. tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true));
  254. }
  255. return this.executeInOrder(tasks, []);
  256. }
  257. moveDashboards(dashboardUids: string[], toFolder: FolderInfo) {
  258. const tasks = [];
  259. for (const uid of dashboardUids) {
  260. tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder));
  261. }
  262. return this.executeInOrder(tasks, []).then((result: any) => {
  263. return {
  264. totalCount: result.length,
  265. successCount: _.filter(result, { succeeded: true }).length,
  266. alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }).length,
  267. };
  268. });
  269. }
  270. private moveDashboard(uid: string, toFolder: FolderInfo) {
  271. const deferred = this.$q.defer();
  272. this.getDashboardByUid(uid).then((fullDash: DashboardDTO) => {
  273. const model = new DashboardModel(fullDash.dashboard, fullDash.meta);
  274. if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
  275. deferred.resolve({ alreadyInFolder: true });
  276. return;
  277. }
  278. const clone = model.getSaveModelClone();
  279. const options = {
  280. folderId: toFolder.id,
  281. overwrite: false,
  282. };
  283. this.saveDashboard(clone, options)
  284. .then(() => {
  285. deferred.resolve({ succeeded: true });
  286. })
  287. .catch((err: any) => {
  288. if (err.data && err.data.status === 'plugin-dashboard') {
  289. err.isHandled = true;
  290. options.overwrite = true;
  291. this.saveDashboard(clone, options)
  292. .then(() => {
  293. deferred.resolve({ succeeded: true });
  294. })
  295. .catch((err: any) => {
  296. deferred.resolve({ succeeded: false });
  297. });
  298. } else {
  299. deferred.resolve({ succeeded: false });
  300. }
  301. });
  302. });
  303. return deferred.promise;
  304. }
  305. private createTask(fn: Function, ignoreRejections: boolean, ...args: any[]) {
  306. return (result: any) => {
  307. return fn
  308. .apply(null, args)
  309. .then((res: any) => {
  310. return Array.prototype.concat(result, [res]);
  311. })
  312. .catch((err: any) => {
  313. if (ignoreRejections) {
  314. return result;
  315. }
  316. throw err;
  317. });
  318. };
  319. }
  320. private executeInOrder(tasks: any[], initialValue: any[]) {
  321. return tasks.reduce(this.$q.when, initialValue);
  322. }
  323. }
  324. coreModule.service('backendSrv', BackendSrv);
  325. //
  326. // Code below is to expore the service to react components
  327. //
  328. let singletonInstance: BackendSrv;
  329. export function setBackendSrv(instance: BackendSrv) {
  330. singletonInstance = instance;
  331. }
  332. export function getBackendSrv(): BackendSrv {
  333. return singletonInstance;
  334. }