avgovertime.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package aggregator
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // averageOverTimeAggregator is a MetricAggregator which returns the average of values it is aggregating by dividing the
  7. // total of all values by the count of unique timestamps
  8. type averageOverTimeAggregator struct {
  9. lock sync.Mutex
  10. name string
  11. labelValues []string
  12. total float64
  13. count int
  14. currentTime *time.Time
  15. }
  16. func AverageOverTime(name string, labelValues []string) MetricAggregator {
  17. return &averageOverTimeAggregator{
  18. name: name,
  19. labelValues: labelValues,
  20. }
  21. }
  22. func (a *averageOverTimeAggregator) Name() string {
  23. return a.name
  24. }
  25. func (a *averageOverTimeAggregator) AdditionInfo() map[string]string {
  26. return nil
  27. }
  28. func (a *averageOverTimeAggregator) LabelValues() []string {
  29. return a.labelValues
  30. }
  31. func (a *averageOverTimeAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  32. a.lock.Lock()
  33. defer a.lock.Unlock()
  34. a.total += value
  35. if a.currentTime == nil || !timestamp.Equal(*a.currentTime) {
  36. a.currentTime = &timestamp
  37. a.count++
  38. }
  39. }
  40. func (a *averageOverTimeAggregator) Value() []MetricValue {
  41. a.lock.Lock()
  42. defer a.lock.Unlock()
  43. if a.count == 0 {
  44. return []MetricValue{}
  45. }
  46. return []MetricValue{
  47. {a.total / float64(a.count), nil},
  48. }
  49. }