backend_srv.ts 10 KB

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