backend_srv.ts 11 KB

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