backend_srv.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. this.alertSrv.set("Problem!", data.message, data.severity, 10000);
  53. }
  54. throw data;
  55. }
  56. request(options) {
  57. options.retry = options.retry || 0;
  58. var requestIsLocal = !options.url.match(/^http/);
  59. var firstAttempt = options.retry === 0;
  60. if (requestIsLocal) {
  61. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  62. options.headers = options.headers || {};
  63. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  64. }
  65. if (options.url.indexOf("/") === 0) {
  66. options.url = options.url.substring(1);
  67. }
  68. }
  69. return this.$http(options).then(results => {
  70. if (options.method !== 'GET') {
  71. if (results && results.data.message) {
  72. if (options.showSuccessAlert !== false) {
  73. this.alertSrv.set(results.data.message, '', 'success', 3000);
  74. }
  75. }
  76. }
  77. return results.data;
  78. }, err => {
  79. // handle unauthorized
  80. if (err.status === 401 && firstAttempt) {
  81. return this.loginPing().then(() => {
  82. options.retry = 1;
  83. return this.request(options);
  84. });
  85. }
  86. this.$timeout(this.requestErrorHandler.bind(this, err), 50);
  87. throw err;
  88. });
  89. }
  90. addCanceler(requestId, canceler) {
  91. if (requestId in this.inFlightRequests) {
  92. this.inFlightRequests[requestId].push(canceler);
  93. } else {
  94. this.inFlightRequests[requestId] = [canceler];
  95. }
  96. }
  97. resolveCancelerIfExists(requestId) {
  98. var cancelers = this.inFlightRequests[requestId];
  99. if (!_.isUndefined(cancelers) && cancelers.length) {
  100. cancelers[0].resolve();
  101. }
  102. }
  103. datasourceRequest(options) {
  104. options.retry = options.retry || 0;
  105. // A requestID is provided by the datasource as a unique identifier for a
  106. // particular query. If the requestID exists, the promise it is keyed to
  107. // is canceled, canceling the previous datasource request if it is still
  108. // in-flight.
  109. var requestId = options.requestId;
  110. if (requestId) {
  111. this.resolveCancelerIfExists(requestId);
  112. // create new canceler
  113. var canceler = this.$q.defer();
  114. options.timeout = canceler.promise;
  115. this.addCanceler(requestId, canceler);
  116. }
  117. var requestIsLocal = !options.url.match(/^http/);
  118. var firstAttempt = options.retry === 0;
  119. if (requestIsLocal) {
  120. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  121. options.headers = options.headers || {};
  122. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  123. }
  124. if (options.url.indexOf("/") === 0) {
  125. options.url = options.url.substring(1);
  126. }
  127. if (options.headers && options.headers.Authorization) {
  128. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  129. delete options.headers.Authorization;
  130. }
  131. if (this.noBackendCache) {
  132. options.headers['X-Grafana-NoCache'] = 'true';
  133. }
  134. }
  135. return this.$http(options).then(response => {
  136. appEvents.emit('ds-request-response', response);
  137. return response;
  138. }).catch(err => {
  139. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  140. throw {err, cancelled: true};
  141. }
  142. // handle unauthorized for backend requests
  143. if (requestIsLocal && firstAttempt && err.status === 401) {
  144. return this.loginPing().then(() => {
  145. options.retry = 1;
  146. if (canceler) {
  147. canceler.resolve();
  148. }
  149. return this.datasourceRequest(options);
  150. });
  151. }
  152. // populate error obj on Internal Error
  153. if (_.isString(err.data) && err.status === 500) {
  154. err.data = {
  155. error: err.statusText,
  156. response: err.data,
  157. };
  158. }
  159. // for Prometheus
  160. if (err.data && !err.data.message && _.isString(err.data.error)) {
  161. err.data.message = err.data.error;
  162. }
  163. appEvents.emit('ds-request-error', err);
  164. throw err;
  165. }).finally(() => {
  166. // clean up
  167. if (options.requestId) {
  168. this.inFlightRequests[options.requestId].shift();
  169. }
  170. });
  171. }
  172. loginPing() {
  173. return this.request({url: '/api/login/ping', method: 'GET', retry: 1 });
  174. }
  175. search(query) {
  176. return this.get('/api/search', query);
  177. }
  178. getDashboard(type, slug) {
  179. return this.get('/api/dashboards/' + type + '/' + slug);
  180. }
  181. saveDashboard(dash, options) {
  182. options = (options || {});
  183. return this.post('/api/dashboards/db/', {
  184. dashboard: dash,
  185. folderId: dash.folderId,
  186. overwrite: options.overwrite === true,
  187. message: options.message || '',
  188. });
  189. }
  190. createDashboardFolder(name) {
  191. const dash = {
  192. title: name,
  193. editable: true,
  194. hideControls: true,
  195. rows: [
  196. {
  197. panels: [
  198. {
  199. folderId: 0,
  200. headings: false,
  201. limit: 1000,
  202. links: [],
  203. query: '',
  204. recent: false,
  205. search: true,
  206. span: 4,
  207. starred: false,
  208. tags: [],
  209. title: 'Dashboards in this folder',
  210. type: 'dashlist'
  211. },
  212. {
  213. onlyAlertsOnDashboard: true,
  214. span: 4,
  215. title: 'Alerts in this folder',
  216. type: 'alertlist'
  217. },
  218. {
  219. span: 4,
  220. title: 'Permissions for this folder',
  221. type: 'permissionlist',
  222. folderId: 0
  223. }
  224. ],
  225. showTitle: true,
  226. title: name,
  227. titleSize: 'h1'
  228. }
  229. ]
  230. };
  231. return this.post('/api/dashboards/db/', {dashboard: dash, isFolder: true, overwrite: false})
  232. .then(res => {
  233. return this.getDashboard('db', res.slug);
  234. })
  235. .then(res => {
  236. res.dashboard.rows[0].panels[0].folderId = res.dashboard.id;
  237. res.dashboard.rows[0].panels[2].folderId = res.dashboard.id;
  238. return this.saveDashboard(res.dashboard, {overwrite: false});
  239. });
  240. }
  241. }
  242. coreModule.service('backendSrv', BackendSrv);