iratemax.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(labelValues []string) MetricAggregator {
  20. return &iRateMaxAggregator{
  21. labelValues: labelValues,
  22. }
  23. }
  24. func (a *iRateMaxAggregator) AdditionInfo() map[string]string {
  25. return nil
  26. }
  27. func (a *iRateMaxAggregator) LabelValues() []string {
  28. return a.labelValues
  29. }
  30. func (a *iRateMaxAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  31. a.lock.Lock()
  32. defer a.lock.Unlock()
  33. if !a.initialized {
  34. a.previousTime = timestamp
  35. a.currentTime = timestamp
  36. a.initialized = true
  37. }
  38. if a.currentTime.Before(timestamp) {
  39. a.previousTime = a.currentTime
  40. a.previous = a.current
  41. a.currentTime = timestamp
  42. a.current = 0
  43. }
  44. a.current += value
  45. seconds := a.currentTime.Sub(a.previousTime).Seconds()
  46. if seconds == 0 {
  47. return
  48. }
  49. increase := a.current - a.previous
  50. irate := increase / seconds
  51. if irate > a.max {
  52. a.max = irate
  53. }
  54. }
  55. func (a *iRateMaxAggregator) Value() []MetricValue {
  56. a.lock.Lock()
  57. defer a.lock.Unlock()
  58. return []MetricValue{
  59. {Value: a.max},
  60. }
  61. }