backend_srv.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 alertSrv, 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. var data = err.data || { message: 'Unexpected error' };
  37. if (_.isString(data)) {
  38. data = { message: data };
  39. }
  40. if (err.status === 422) {
  41. this.alertSrv.set('Validation failed', data.message, 'warning', 4000);
  42. throw data;
  43. }
  44. data.severity = 'error';
  45. if (err.status < 500) {
  46. data.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. this.alertSrv.set(message, description, data.severity, 10000);
  56. }
  57. throw data;
  58. }
  59. request(options) {
  60. options.retry = options.retry || 0;
  61. var requestIsLocal = !options.url.match(/^http/);
  62. var 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. this.alertSrv.set(results.data.message, '', 'success', 3000);
  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. 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)
  142. .then(response => {
  143. if (!options.silent) {
  144. appEvents.emit('ds-request-response', response);
  145. }
  146. return response;
  147. })
  148. .catch(err => {
  149. if (err.status === this.HTTP_REQUEST_CANCELLED) {
  150. throw { err, cancelled: true };
  151. }
  152. // handle unauthorized for backend requests
  153. if (requestIsLocal && firstAttempt && err.status === 401) {
  154. return this.loginPing().then(() => {
  155. options.retry = 1;
  156. if (canceler) {
  157. canceler.resolve();
  158. }
  159. return this.datasourceRequest(options);
  160. });
  161. }
  162. // populate error obj on Internal Error
  163. if (_.isString(err.data) && err.status === 500) {
  164. err.data = {
  165. error: err.statusText,
  166. response: err.data,
  167. };
  168. }
  169. // for Prometheus
  170. if (err.data && !err.data.message && _.isString(err.data.error)) {
  171. err.data.message = err.data.error;
  172. }
  173. if (!options.silent) {
  174. appEvents.emit('ds-request-error', err);
  175. }
  176. throw err;
  177. })
  178. .finally(() => {
  179. // clean up
  180. if (options.requestId) {
  181. this.inFlightRequests[options.requestId].shift();
  182. }
  183. });
  184. }
  185. loginPing() {
  186. return this.request({ url: '/api/login/ping', method: 'GET', retry: 1 });
  187. }
  188. search(query) {
  189. return this.get('/api/search', query);
  190. }
  191. getDashboardBySlug(slug) {
  192. return this.get(`/api/dashboards/db/${slug}`);
  193. }
  194. getDashboardByUid(uid: string) {
  195. return this.get(`/api/dashboards/uid/${uid}`);
  196. }
  197. getFolderByUid(uid: string) {
  198. return this.get(`/api/folders/${uid}`);
  199. }
  200. saveDashboard(dash, options) {
  201. options = options || {};
  202. return this.post('/api/dashboards/db/', {
  203. dashboard: dash,
  204. folderId: options.folderId,
  205. overwrite: options.overwrite === true,
  206. message: options.message || '',
  207. });
  208. }
  209. createFolder(payload: any) {
  210. return this.post('/api/folders', payload);
  211. }
  212. updateFolder(folder, options) {
  213. options = options || {};
  214. return this.put(`/api/folders/${folder.uid}`, {
  215. title: folder.title,
  216. version: folder.version,
  217. overwrite: options.overwrite === true,
  218. });
  219. }
  220. deleteFolder(uid: string, showSuccessAlert) {
  221. return this.request({ method: 'DELETE', url: `/api/folders/${uid}`, showSuccessAlert: showSuccessAlert === true });
  222. }
  223. deleteDashboard(uid, showSuccessAlert) {
  224. return this.request({
  225. method: 'DELETE',
  226. url: `/api/dashboards/uid/${uid}`,
  227. showSuccessAlert: showSuccessAlert === true,
  228. });
  229. }
  230. deleteFoldersAndDashboards(folderUids, dashboardUids) {
  231. const tasks = [];
  232. for (const folderUid of folderUids) {
  233. tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true));
  234. }
  235. for (const dashboardUid of dashboardUids) {
  236. tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true));
  237. }
  238. return this.executeInOrder(tasks, []);
  239. }
  240. moveDashboards(dashboardUids, toFolder) {
  241. const tasks = [];
  242. for (const uid of dashboardUids) {
  243. tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder));
  244. }
  245. return this.executeInOrder(tasks, []).then(result => {
  246. return {
  247. totalCount: result.length,
  248. successCount: _.filter(result, { succeeded: true }).length,
  249. alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }).length,
  250. };
  251. });
  252. }
  253. private moveDashboard(uid, toFolder) {
  254. const deferred = this.$q.defer();
  255. this.getDashboardByUid(uid).then(fullDash => {
  256. const model = new DashboardModel(fullDash.dashboard, fullDash.meta);
  257. if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
  258. deferred.resolve({ alreadyInFolder: true });
  259. return;
  260. }
  261. const clone = model.getSaveModelClone();
  262. const options = {
  263. folderId: toFolder.id,
  264. overwrite: false,
  265. };
  266. this.saveDashboard(clone, options)
  267. .then(() => {
  268. deferred.resolve({ succeeded: true });
  269. })
  270. .catch(err => {
  271. if (err.data && err.data.status === 'plugin-dashboard') {
  272. err.isHandled = true;
  273. options.overwrite = true;
  274. this.saveDashboard(clone, options)
  275. .then(() => {
  276. deferred.resolve({ succeeded: true });
  277. })
  278. .catch(err => {
  279. deferred.resolve({ succeeded: false });
  280. });
  281. } else {
  282. deferred.resolve({ succeeded: false });
  283. }
  284. });
  285. });
  286. return deferred.promise;
  287. }
  288. private createTask(fn, ignoreRejections, ...args: any[]) {
  289. return result => {
  290. return fn
  291. .apply(null, args)
  292. .then(res => {
  293. return Array.prototype.concat(result, [res]);
  294. })
  295. .catch(err => {
  296. if (ignoreRejections) {
  297. return result;
  298. }
  299. throw err;
  300. });
  301. };
  302. }
  303. private executeInOrder(tasks, initialValue) {
  304. return tasks.reduce(this.$q.when, initialValue);
  305. }
  306. }
  307. coreModule.service('backendSrv', BackendSrv);
  308. //
  309. // Code below is to expore the service to react components
  310. //
  311. let singletonInstance: BackendSrv;
  312. export function setBackendSrv(instance: BackendSrv) {
  313. singletonInstance = instance;
  314. }
  315. export function getBackendSrv(): BackendSrv {
  316. return singletonInstance;
  317. }