2
0

rate.go 1.6 KB

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