backend_srv.ts 6.2 KB

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