abovethresholdratio.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package aggregator
  2. import (
  3. "math"
  4. "sync"
  5. "time"
  6. )
  7. // aboveThresholdRatioAggregator is a MetricAggregator which returns the
  8. // fraction of unique-timestamp samples whose value was at or above a fixed
  9. // threshold. It is used to derive time-over-threshold pressure signals such
  10. // as GPU memory pressure.
  11. type aboveThresholdRatioAggregator struct {
  12. lock sync.Mutex
  13. labelValues []string
  14. threshold float64
  15. count int
  16. aboveCount int
  17. currentTime *time.Time
  18. currentHit bool
  19. }
  20. // AboveThresholdRatio returns a MetricAggregatorFactory producing
  21. // aggregators that report the fraction of samples >= threshold.
  22. func AboveThresholdRatio(threshold float64) MetricAggregatorFactory {
  23. return func(labelValues []string) MetricAggregator {
  24. return &aboveThresholdRatioAggregator{
  25. labelValues: labelValues,
  26. threshold: threshold,
  27. }
  28. }
  29. }
  30. func (a *aboveThresholdRatioAggregator) AdditionInfo() map[string]string {
  31. return nil
  32. }
  33. func (a *aboveThresholdRatioAggregator) LabelValues() []string {
  34. return a.labelValues
  35. }
  36. func (a *aboveThresholdRatioAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  37. a.lock.Lock()
  38. defer a.lock.Unlock()
  39. hit := !math.IsNaN(value) && value >= a.threshold
  40. if a.currentTime == nil || !timestamp.Equal(*a.currentTime) {
  41. a.currentTime = &timestamp
  42. a.currentHit = false
  43. a.count++
  44. }
  45. if hit && !a.currentHit {
  46. a.currentHit = true
  47. a.aboveCount++
  48. }
  49. }
  50. func (a *aboveThresholdRatioAggregator) Value() []MetricValue {
  51. a.lock.Lock()
  52. defer a.lock.Unlock()
  53. if a.count == 0 {
  54. return []MetricValue{{Value: 0}}
  55. }
  56. return []MetricValue{
  57. {Value: float64(a.aboveCount) / float64(a.count)},
  58. }
  59. }