backend_srv.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. var 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. var requestIsLocal = !options.url.match(/^http/);
  62. var 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. var cancelers = this.inFlightRequests[requestId];
  105. if (!_.isUndefined(cancelers) && cancelers.length) {
  106. cancelers[0].resolve();
  107. }
  108. }
  109. datasourceRequest(options) {
  110. options.retry = options.retry || 0;
  111. // A requestID is provided by the datasource as a unique identifier for a
  112. // particular query. If the requestID exists, the promise it is keyed to
  113. // is canceled, canceling the previous datasource request if it is still
  114. // in-flight.
  115. var requestId = options.requestId;
  116. if (requestId) {
  117. this.resolveCancelerIfExists(requestId);
  118. // create new canceler
  119. var canceler = this.$q.defer();
  120. options.timeout = canceler.promise;
  121. this.addCanceler(requestId, canceler);
  122. }
  123. var requestIsLocal = !options.url.match(/^http/);
  124. var firstAttempt = options.retry === 0;
  125. if (requestIsLocal) {
  126. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  127. options.headers = options.headers || {};
  128. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  129. }
  130. if (options.url.indexOf('/') === 0) {
  131. options.url = options.url.substring(1);
  132. }
  133. if (options.headers && options.headers.Authorization) {
  134. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  135. delete options.headers.Authorization;
  136. }
  137. if (this.noBackendCache) {
  138. options.headers['X-Grafana-NoCache'] = 'true';
  139. }
  140. }
  141. return this.$http(options)
  142. .then(response => {
  143. appEvents.emit('ds-request-response', response);
  144. return response;
  145. })
  146. .catch(err => {
  147. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  148. throw { err, cancelled: true };
  149. }
  150. // handle unauthorized for backend requests
  151. if (requestIsLocal && firstAttempt && err.status === 401) {
  152. return this.loginPing().then(() => {
  153. options.retry = 1;
  154. if (canceler) {
  155. canceler.resolve();
  156. }
  157. return this.datasourceRequest(options);
  158. });
  159. }
  160. // populate error obj on Internal Error
  161. if (_.isString(err.data) && err.status === 500) {
  162. err.data = {
  163. error: err.statusText,
  164. response: err.data,
  165. };
  166. }
  167. // for Prometheus
  168. if (err.data && !err.data.message && _.isString(err.data.error)) {
  169. err.data.message = err.data.error;
  170. }
  171. appEvents.emit('ds-request-error', err);
  172. throw err;
  173. })
  174. .finally(() => {
  175. // clean up
  176. if (options.requestId) {
  177. this.inFlightRequests[options.requestId].shift();
  178. }
  179. });
  180. }
  181. loginPing() {
  182. return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
  183. }
  184. search(query) {
  185. return this.get('/api/search', query);
  186. }
  187. getDashboard(type, slug) {
  188. return this.get('/api/dashboards/' + type + '/' + slug);
  189. }
  190. saveDashboard(dash, options) {
  191. options = options || {};
  192. return this.post('/api/dashboards/db/', {
  193. dashboard: dash,
  194. folderId: options.folderId,
  195. overwrite: options.overwrite === true,
  196. message: options.message || '',
  197. });
  198. }
  199. createDashboardFolder(name) {
  200. const dash = {
  201. schemaVersion: 16,
  202. title: name.trim(),
  203. editable: true,
  204. panels: [],
  205. };
  206. return this.post('/api/dashboards/db/', {
  207. dashboard: dash,
  208. isFolder: true,
  209. overwrite: false,
  210. }).then(res => {
  211. return this.getDashboard('db', res.slug);
  212. });
  213. }
  214. deleteDashboard(slug) {
  215. let deferred = this.$q.defer();
  216. this.getDashboard('db', slug).then(fullDash => {
  217. this.delete(`/api/dashboards/db/${slug}`)
  218. .then(() => {
  219. deferred.resolve(fullDash);
  220. })
  221. .catch(err => {
  222. deferred.reject(err);
  223. });
  224. });
  225. return deferred.promise;
  226. }
  227. deleteDashboards(dashboardSlugs) {
  228. const tasks = [];
  229. for (let slug of dashboardSlugs) {
  230. tasks.push(this.createTask(this.deleteDashboard.bind(this), true, slug));
  231. }
  232. return this.executeInOrder(tasks, []);
  233. }
  234. moveDashboards(dashboardSlugs, toFolder) {
  235. const tasks = [];
  236. for (let slug of dashboardSlugs) {
  237. tasks.push(this.createTask(this.moveDashboard.bind(this), true, slug, toFolder));
  238. }
  239. return this.executeInOrder(tasks, []).then(result => {
  240. return {
  241. totalCount: result.length,
  242. successCount: _.filter(result, { succeeded: true }).length,
  243. alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }).length,
  244. };
  245. });
  246. }
  247. private moveDashboard(slug, toFolder) {
  248. let deferred = this.$q.defer();
  249. this.getDashboard('db', slug).then(fullDash => {
  250. const model = new DashboardModel(fullDash.dashboard, fullDash.meta);
  251. if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
  252. deferred.resolve({ alreadyInFolder: true });
  253. return;
  254. }
  255. const clone = model.getSaveModelClone();
  256. let options = {
  257. folderId: toFolder.id,
  258. overwrite: false,
  259. };
  260. this.saveDashboard(clone, options)
  261. .then(() => {
  262. deferred.resolve({ succeeded: true });
  263. })
  264. .catch(err => {
  265. if (err.data && err.data.status === 'plugin-dashboard') {
  266. err.isHandled = true;
  267. options.overwrite = true;
  268. this.saveDashboard(clone, options)
  269. .then(() => {
  270. deferred.resolve({ succeeded: true });
  271. })
  272. .catch(err => {
  273. deferred.resolve({ succeeded: false });
  274. });
  275. } else {
  276. deferred.resolve({ succeeded: false });
  277. }
  278. });
  279. });
  280. return deferred.promise;
  281. }
  282. private createTask(fn, ignoreRejections, ...args: any[]) {
  283. return result => {
  284. return fn
  285. .apply(null, args)
  286. .then(res => {
  287. return Array.prototype.concat(result, [res]);
  288. })
  289. .catch(err => {
  290. if (ignoreRejections) {
  291. return result;
  292. }
  293. throw err;
  294. });
  295. };
  296. }
  297. private executeInOrder(tasks, initialValue) {
  298. return tasks.reduce(this.$q.when, initialValue);
  299. }
  300. }
  301. coreModule.service('backendSrv', BackendSrv);