backend_srv.ts 9.2 KB

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