backend_srv.ts 10 KB

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