backend_srv.ts 9.4 KB

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