iratemax.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package aggregator
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // iRateMaxAggregator is a MetricAggregator which returns the max rate per second between any two samples.
  7. // to function properly calls to Update must have a timestamp greater than or equal to the last call to update.
  8. type iRateMaxAggregator struct {
  9. lock sync.Mutex
  10. name string
  11. labelValues []string
  12. initialized bool
  13. previousTime time.Time
  14. currentTime time.Time
  15. previous float64
  16. current float64
  17. max float64
  18. }
  19. func IRateMax(name string, labelValues []string) MetricAggregator {
  20. return &iRateMaxAggregator{
  21. name: name,
  22. labelValues: labelValues,
  23. }
  24. }
  25. func (a *iRateMaxAggregator) Name() string {
  26. return a.name
  27. }
  28. func (a *iRateMaxAggregator) AdditionInfo() map[string]string {
  29. return nil
  30. }
  31. func (a *iRateMaxAggregator) LabelValues() []string {
  32. return a.labelValues
  33. }
  34. func (a *iRateMaxAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  35. a.lock.Lock()
  36. defer a.lock.Unlock()
  37. if !a.initialized {
  38. a.previousTime = timestamp
  39. a.currentTime = timestamp
  40. a.initialized = true
  41. }
  42. if a.currentTime.Before(timestamp) {
  43. a.previousTime = a.currentTime
  44. a.previous = a.current
  45. a.currentTime = timestamp
  46. a.current = 0
  47. }
  48. a.current += value
  49. seconds := a.currentTime.Sub(a.previousTime).Seconds()
  50. if seconds == 0 {
  51. return
  52. }
  53. increase := a.current - a.previous
  54. irate := increase / seconds
  55. if irate > a.max {
  56. a.max = irate
  57. }
  58. }
  59. func (a *iRateMaxAggregator) Value() []MetricValue {
  60. a.lock.Lock()
  61. defer a.lock.Unlock()
  62. if !a.initialized {
  63. return []MetricValue{}
  64. }
  65. return []MetricValue{
  66. {Value: a.max},
  67. }
  68. }