backend_srv.ts 9.5 KB

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