annotationsSrv.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. './editorCtrl'
  6. ], function (angular, _, moment) {
  7. 'use strict';
  8. var module = angular.module('grafana.services');
  9. module.service('annotationsSrv', function(datasourceSrv, $q, alertSrv, $rootScope, $sanitize) {
  10. var promiseCached;
  11. var list = [];
  12. var timezone;
  13. var self = this;
  14. this.init = function() {
  15. $rootScope.onAppEvent('refresh', this.clearCache);
  16. $rootScope.onAppEvent('setup-dashboard', this.clearCache);
  17. };
  18. this.clearCache = function() {
  19. promiseCached = null;
  20. list = [];
  21. };
  22. this.getAnnotations = function(rangeUnparsed, dashboard) {
  23. if (dashboard.annotations.list.length === 0) {
  24. return $q.when(null);
  25. }
  26. if (promiseCached) {
  27. return promiseCached;
  28. }
  29. timezone = dashboard.timezone;
  30. var annotations = _.where(dashboard.annotations.list, {enable: true});
  31. var promises = _.map(annotations, function(annotation) {
  32. return datasourceSrv.get(annotation.datasource).then(function(datasource) {
  33. return datasource.annotationQuery(annotation, rangeUnparsed)
  34. .then(self.receiveAnnotationResults)
  35. .then(null, errorHandler);
  36. }, this);
  37. });
  38. promiseCached = $q.all(promises)
  39. .then(function() {
  40. return list;
  41. });
  42. return promiseCached;
  43. };
  44. this.receiveAnnotationResults = function(results) {
  45. for (var i = 0; i < results.length; i++) {
  46. addAnnotation(results[i]);
  47. }
  48. };
  49. function errorHandler(err) {
  50. console.log('Annotation error: ', err);
  51. var message = err.message || "Annotation query failed";
  52. alertSrv.set('Annotations error', message,'error');
  53. }
  54. function addAnnotation(options) {
  55. var title = $sanitize(options.title);
  56. var tooltip = "<small><b>" + title + "</b><br/>";
  57. if (options.tags) {
  58. var tags = $sanitize(options.tags);
  59. tooltip += '<span class="tag label label-tag">' + (tags || '') + '</span><br/>';
  60. }
  61. if (timezone === 'browser') {
  62. tooltip += '<i>' + moment(options.time).format('YYYY-MM-DD HH:mm:ss') + '</i><br/>';
  63. }
  64. else {
  65. tooltip += '<i>' + moment.utc(options.time).format('YYYY-MM-DD HH:mm:ss') + '</i><br/>';
  66. }
  67. if (options.text) {
  68. var text = $sanitize(options.text);
  69. tooltip += text.replace(/\n/g, '<br/>');
  70. }
  71. tooltip += "</small>";
  72. list.push({
  73. annotation: options.annotation,
  74. min: options.time,
  75. max: options.time,
  76. eventType: options.annotation.name,
  77. title: null,
  78. description: tooltip,
  79. score: 1
  80. });
  81. }
  82. // Now init
  83. this.init();
  84. });
  85. });