backend_srv.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import _ from 'lodash';
  2. import coreModule from 'app/core/core_module';
  3. import appEvents from 'app/core/app_events';
  4. import { DashboardModel } from 'app/features/dashboard/dashboard_model';
  5. export class BackendSrv {
  6. private inFlightRequests = {};
  7. private HTTP_REQUEST_CANCELLED = -1;
  8. private noBackendCache: boolean;
  9. /** @ngInject */
  10. constructor(private $http, private $q, private $timeout, private contextSrv) {}
  11. get(url, params?) {
  12. return this.request({ method: 'GET', url: url, params: params });
  13. }
  14. delete(url) {
  15. return this.request({ method: 'DELETE', url: url });
  16. }
  17. post(url, data) {
  18. return this.request({ method: 'POST', url: url, data: data });
  19. }
  20. patch(url, data) {
  21. return this.request({ method: 'PATCH', url: url, data: data });
  22. }
  23. put(url, data) {
  24. return this.request({ method: 'PUT', url: url, data: data });
  25. }
  26. withNoBackendCache(callback) {
  27. this.noBackendCache = true;
  28. return callback().finally(() => {
  29. this.noBackendCache = false;
  30. });
  31. }
  32. requestErrorHandler(err) {
  33. if (err.isHandled) {
  34. return;
  35. }
  36. let data = err.data || { message: 'Unexpected error' };
  37. if (_.isString(data)) {
  38. data = { message: data };
  39. }
  40. if (err.status === 422) {
  41. appEvents.emit('alert-warning', ['Validation failed', data.message]);
  42. throw data;
  43. }
  44. let severity = 'error';
  45. if (err.status < 500) {
  46. severity = 'warning';
  47. }
  48. if (data.message) {
  49. let description = '';
  50. let message = data.message;
  51. if (message.length > 80) {
  52. description = message;
  53. message = 'Error';
  54. }
  55. appEvents.emit('alert-' + severity, [message, description]);
  56. }
  57. throw data;
  58. }
  59. request(options) {
  60. options.retry = options.retry || 0;
  61. const requestIsLocal = !options.url.match(/^http/);
  62. const firstAttempt = options.retry === 0;
  63. if (requestIsLocal) {
  64. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  65. options.headers = options.headers || {};
  66. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  67. }
  68. if (options.url.indexOf('/') === 0) {
  69. options.url = options.url.substring(1);
  70. }
  71. }
  72. return this.$http(options).then(
  73. results => {
  74. if (options.method !== 'GET') {
  75. if (results && results.data.message) {
  76. if (options.showSuccessAlert !== false) {
  77. appEvents.emit('alert-success', [results.data.message]);
  78. }
  79. }
  80. }
  81. return results.data;
  82. },
  83. err => {
  84. // handle unauthorized
  85. if (err.status === 401 && this.contextSrv.user.isSignedIn && firstAttempt) {
  86. return this.loginPing().then(() => {
  87. options.retry = 1;
  88. return this.request(options);
  89. });
  90. }
  91. this.$timeout(this.requestErrorHandler.bind(this, err), 50);
  92. throw err;
  93. }
  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. const cancelers = this.inFlightRequests[requestId];
  105. if (!_.isUndefined(cancelers) && cancelers.length) {
  106. cancelers[0].resolve();
  107. }
  108. }
  109. datasourceRequest(options) {
  110. let canceler = null;
  111. options.retry = options.retry || 0;
  112. // A requestID is provided by the datasource as a unique identifier for a
  113. // particular query. If the requestID exists, the promise it is keyed to
  114. // is canceled, canceling the previous datasource request if it is still
  115. // in-flight.
  116. const requestId = options.requestId;
  117. if (requestId) {
  118. this.resolveCancelerIfExists(requestId);
  119. // create new canceler
  120. canceler = this.$q.defer();
  121. options.timeout = canceler.promise;
  122. this.addCanceler(requestId, canceler);
  123. }
  124. const requestIsLocal = !options.url.match(/^http/);
  125. const firstAttempt = options.retry === 0;
  126. if (requestIsLocal) {
  127. if (this.contextSrv.user && this.contextSrv.user.orgId) {
  128. options.headers = options.headers || {};
  129. options.headers['X-Grafana-Org-Id'] = this.contextSrv.user.orgId;
  130. }
  131. if (options.url.indexOf('/') === 0) {
  132. options.url = options.url.substring(1);
  133. }
  134. if (options.headers && options.headers.Authorization) {
  135. options.headers['X-DS-Authorization'] = options.headers.Authorization;
  136. delete options.headers.Authorization;
  137. }
  138. if (this.noBackendCache) {
  139. options.headers['X-Grafana-NoCache'] = 'true';
  140. }
  141. }
  142. return this.$http(options)
  143. .then(response => {
  144. if (!options.silent) {
  145. appEvents.emit('ds-request-response', response);
  146. }
  147. return response;
  148. })
  149. .catch(err => {
  150. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  151. throw { err, cancelled: true };
  152. }
  153. // handle unauthorized for backend requests
  154. if (requestIsLocal && firstAttempt && err.status === 401) {
  155. return this.loginPing().then(() => {
  156. options.retry = 1;
  157. if (canceler) {
  158. canceler.resolve();
  159. }
  160. return this.datasourceRequest(options);
  161. });
  162. }
  163. // populate error obj on Internal Error
  164. if (_.isString(err.data) && err.status === 500) {
  165. err.data = {
  166. error: err.statusText,
  167. response: err.data,
  168. };
  169. }
  170. // for Prometheus
  171. if (err.data && !err.data.message && _.isString(err.data.error)) {
  172. err.data.message = err.data.error;
  173. }
  174. if (!options.silent) {
  175. appEvents.emit('ds-request-error', err);
  176. }
  177. throw err;
  178. })
  179. .finally(() => {
  180. // clean up
  181. if (options.requestId) {
  182. this.inFlightRequests[options.requestId].shift();
  183. }
  184. });
  185. }
  186. loginPing() {
  187. return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
  188. }
  189. search(query) {
  190. return this.get('/api/search', query);
  191. }
  192. getDashboardBySlug(slug) {
  193. return this.get(`/api/dashboards/db/${slug}`);
  194. }
  195. getDashboardByUid(uid: string) {
  196. return this.get(`/api/dashboards/uid/${uid}`);
  197. }
  198. getFolderByUid(uid: string) {
  199. return this.get(`/api/folders/${uid}`);
  200. }
  201. saveDashboard(dash, options) {
  202. options = options || {};
  203. return this.post('/api/dashboards/db/', {
  204. dashboard: dash,
  205. folderId: options.folderId,
  206. overwrite: options.overwrite === true,
  207. message: options.message || '',
  208. });
  209. }
  210. createFolder(payload: any) {
  211. return this.post('/api/folders', payload);
  212. }
  213. deleteFolder(uid: string, showSuccessAlert) {
  214. return this.request({ method: 'DELETE', url: `/api/folders/${uid}`, showSuccessAlert: showSuccessAlert === true });
  215. }
  216. deleteDashboard(uid, showSuccessAlert) {
  217. return this.request({
  218. method: 'DELETE',
  219. url: `/api/dashboards/uid/${uid}`,
  220. showSuccessAlert: showSuccessAlert === true,
  221. });
  222. }
  223. deleteFoldersAndDashboards(folderUids, dashboardUids) {
  224. const tasks = [];
  225. for (const folderUid of folderUids) {
  226. tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true));
  227. }
  228. for (const dashboardUid of dashboardUids) {
  229. tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true));
  230. }
  231. return this.executeInOrder(tasks, []);
  232. }
  233. moveDashboards(dashboardUids, toFolder) {
  234. const tasks = [];
  235. for (const uid of dashboardUids) {
  236. tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder));
  237. }
  238. return this.executeInOrder(tasks, []).then(result => {
  239. return {
  240. totalCount: result.length,
  241. successCount: _.filter(result, { succeeded: true }).length,
  242. alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }).length,
  243. };
  244. });
  245. }
  246. private moveDashboard(uid, toFolder) {
  247. const deferred = this.$q.defer();
  248. this.getDashboardByUid(uid).then(fullDash => {
  249. const model = new DashboardModel(fullDash.dashboard, fullDash.meta);
  250. if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
  251. deferred.resolve({ alreadyInFolder: true });
  252. return;
  253. }
  254. const clone = model.getSaveModelClone();
  255. const options = {
  256. folderId: toFolder.id,
  257. overwrite: false,
  258. };
  259. this.saveDashboard(clone, options)
  260. .then(() => {
  261. deferred.resolve({ succeeded: true });
  262. })
  263. .catch(err => {
  264. if (err.data && err.data.status === 'plugin-dashboard') {
  265. err.isHandled = true;
  266. options.overwrite = true;
  267. this.saveDashboard(clone, options)
  268. .then(() => {
  269. deferred.resolve({ succeeded: true });
  270. })
  271. .catch(err => {
  272. deferred.resolve({ succeeded: false });
  273. });
  274. } else {
  275. deferred.resolve({ succeeded: false });
  276. }
  277. });
  278. });
  279. return deferred.promise;
  280. }
  281. private createTask(fn, ignoreRejections, ...args: any[]) {
  282. return result => {
  283. return fn
  284. .apply(null, args)
  285. .then(res => {
  286. return Array.prototype.concat(result, [res]);
  287. })
  288. .catch(err => {
  289. if (ignoreRejections) {
  290. return result;
  291. }
  292. throw err;
  293. });
  294. };
  295. }
  296. private executeInOrder(tasks, initialValue) {
  297. return tasks.reduce(this.$q.when, initialValue);
  298. }
  299. }
  300. coreModule.service('backendSrv', BackendSrv);
  301. //
  302. // Code below is to expore the service to react components
  303. //
  304. let singletonInstance: BackendSrv;
  305. export function setBackendSrv(instance: BackendSrv) {
  306. singletonInstance = instance;
  307. }
  308. export function getBackendSrv(): BackendSrv {
  309. return singletonInstance;
  310. }