backend_srv.ts 6.3 KB

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