backend_srv.ts 5.7 KB

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