annotationsSrv.js 2.5 KB

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