backend_srv.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. ///<reference path="../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import config from 'app/core/config';
  5. import coreModule from 'app/core/core_module';
  6. export class BackendSrv {
  7. inFlightRequests = {};
  8. HTTP_REQUEST_CANCELLED = -1;
  9. /** @ngInject */
  10. constructor(private $http, private alertSrv, private $rootScope, private $q, private $timeout, private contextSrv) {
  11. }
  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. requestErrorHandler(err) {
  28. if (err.isHandled) {
  29. return;
  30. }
  31. var data = err.data || { message: 'Unexpected error' };
  32. if (_.isString(data)) {
  33. data = { message: data };
  34. }
  35. if (err.status === 422) {
  36. this.alertSrv.set("Validation failed", data.message, "warning", 4000);
  37. throw data;
  38. }
  39. data.severity = 'error';
  40. if (err.status < 500) {
  41. data.severity = "warning";
  42. }
  43. if (data.message) {
  44. this.alertSrv.set("Problem!", data.message, data.severity, 10000);
  45. }
  46. throw data;
  47. }
  48. request(options) {
  49. options.retry = options.retry || 0;
  50. var requestIsLocal = !options.url.match(/^http/);
  51. var firstAttempt = options.retry === 0;
  52. if (requestIsLocal) {
  53. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  54. options.headers = options.headers || {};
  55. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  56. }
  57. if (options.url.indexOf("/") === 0) {
  58. options.url = options.url.substring(1);
  59. }
  60. }
  61. return this.$http(options).then(results => {
  62. if (options.method !== 'GET') {
  63. if (results && results.data.message) {
  64. if (options.showSuccessAlert !== false) {
  65. this.alertSrv.set(results.data.message, '', 'success', 3000);
  66. }
  67. }
  68. }
  69. return results.data;
  70. }, err => {
  71. // handle unauthorized
  72. if (err.status === 401 && firstAttempt) {
  73. return this.loginPing().then(() => {
  74. options.retry = 1;
  75. return this.request(options);
  76. });
  77. }
  78. this.$timeout(this.requestErrorHandler.bind(this, err), 50);
  79. throw err;
  80. });
  81. }
  82. addCanceler(requestId, canceler) {
  83. if (requestId in this.inFlightRequests) {
  84. this.inFlightRequests[requestId].push(canceler);
  85. } else {
  86. this.inFlightRequests[requestId] = [canceler];
  87. }
  88. }
  89. resolveCancelerIfExists(requestId) {
  90. var cancelers = this.inFlightRequests[requestId];
  91. if (!_.isUndefined(cancelers) && cancelers.length) {
  92. cancelers[0].resolve();
  93. }
  94. }
  95. datasourceRequest(options) {
  96. options.retry = options.retry || 0;
  97. // A requestID is provided by the datasource as a unique identifier for a
  98. // particular query. If the requestID exists, the promise it is keyed to
  99. // is canceled, canceling the previous datasource request if it is still
  100. // in-flight.
  101. var requestId = options.requestId;
  102. if (requestId) {
  103. this.resolveCancelerIfExists(requestId);
  104. // create new canceler
  105. var canceler = this.$q.defer();
  106. options.timeout = canceler.promise;
  107. this.addCanceler(requestId, canceler);
  108. }
  109. var requestIsLocal = !options.url.match(/^http/);
  110. var firstAttempt = options.retry === 0;
  111. if (requestIsLocal) {
  112. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  113. options.headers = options.headers || {};
  114. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  115. }
  116. if (options.url.indexOf("/") === 0) {
  117. options.url = options.url.substring(1);
  118. }
  119. if (options.headers && options.headers.Authorization) {
  120. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  121. delete options.headers.Authorization;
  122. }
  123. }
  124. return this.$http(options).catch(err => {
  125. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  126. throw {err, cancelled: true};
  127. }
  128. // handle unauthorized for backend requests
  129. if (requestIsLocal && firstAttempt && err.status === 401) {
  130. return this.loginPing().then(() => {
  131. options.retry = 1;
  132. if (canceler) {
  133. canceler.resolve();
  134. }
  135. return this.datasourceRequest(options);
  136. });
  137. }
  138. //populate error obj on Internal Error
  139. if (_.isString(err.data) && err.status === 500) {
  140. err.data = {
  141. error: err.statusText,
  142. response: err.data,
  143. };
  144. }
  145. // for Prometheus
  146. if (!err.data.message && _.isString(err.data.error)) {
  147. err.data.message = err.data.error;
  148. }
  149. throw err;
  150. }).finally(() => {
  151. // clean up
  152. if (options.requestId) {
  153. this.inFlightRequests[options.requestId].shift();
  154. }
  155. });
  156. }
  157. loginPing() {
  158. return this.request({url: '/api/login/ping', method: 'GET', retry: 1 });
  159. }
  160. search(query) {
  161. return this.get('/api/search', query);
  162. }
  163. getDashboard(type, slug) {
  164. return this.get('/api/dashboards/' + type + '/' + slug);
  165. }
  166. saveDashboard(dash, options) {
  167. options = (options || {});
  168. const message = options.message || '';
  169. return this.post('/api/dashboards/db/', {dashboard: dash, overwrite: options.overwrite === true, message});
  170. }
  171. }
  172. coreModule.service('backendSrv', BackendSrv);