annotationsSrv.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. define([
  2. 'angular',
  3. 'lodash',
  4. './editorCtrl'
  5. ], function (angular, _) {
  6. 'use strict';
  7. var module = angular.module('grafana.services');
  8. module.service('annotationsSrv', function($rootScope, $q, datasourceSrv, alertSrv, timeSrv) {
  9. var promiseCached;
  10. var list = [];
  11. var self = this;
  12. this.init = function() {
  13. $rootScope.onAppEvent('refresh', this.clearCache, $rootScope);
  14. $rootScope.onAppEvent('dashboard-loaded', this.clearCache, $rootScope);
  15. };
  16. this.clearCache = function() {
  17. promiseCached = null;
  18. list = [];
  19. };
  20. this.getAnnotations = function(dashboard) {
  21. if (dashboard.annotations.list.length === 0) {
  22. return $q.when(null);
  23. }
  24. if (promiseCached) {
  25. return promiseCached;
  26. }
  27. self.dashboard = dashboard;
  28. var annotations = _.where(dashboard.annotations.list, {enable: true});
  29. var range = timeSrv.timeRange();
  30. var rangeRaw = timeSrv.timeRange(false);
  31. var promises = _.map(annotations, function(annotation) {
  32. return datasourceSrv.get(annotation.datasource).then(function(datasource) {
  33. var query = {range: range, rangeRaw: rangeRaw, annotation: annotation};
  34. return datasource.annotationQuery(query)
  35. .then(self.receiveAnnotationResults)
  36. .then(null, errorHandler);
  37. }, this);
  38. });
  39. promiseCached = $q.all(promises)
  40. .then(function() {
  41. return list;
  42. });
  43. return promiseCached;
  44. };
  45. this.receiveAnnotationResults = function(results) {
  46. for (var i = 0; i < results.length; i++) {
  47. self.addAnnotation(results[i]);
  48. }
  49. };
  50. this.addAnnotation = function(options) {
  51. list.push({
  52. annotation: options.annotation,
  53. min: options.time,
  54. max: options.time,
  55. eventType: options.annotation.name,
  56. title: options.title,
  57. tags: options.tags,
  58. text: options.text,
  59. score: 1
  60. });
  61. };
  62. function errorHandler(err) {
  63. console.log('Annotation error: ', err);
  64. var message = err.message || "Annotation query failed";
  65. alertSrv.set('Annotations error', message,'error');
  66. }
  67. // Now init
  68. this.init();
  69. });
  70. });