reducer.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package conditions
  2. import (
  3. "math"
  4. "github.com/grafana/grafana/pkg/tsdb"
  5. "gopkg.in/guregu/null.v3"
  6. )
  7. type QueryReducer interface {
  8. Reduce(timeSeries *tsdb.TimeSeries) null.Float
  9. }
  10. type SimpleReducer struct {
  11. Type string
  12. }
  13. func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float {
  14. if len(series.Points) == 0 {
  15. return null.FloatFromPtr(nil)
  16. }
  17. value := float64(0)
  18. allNull := true
  19. switch s.Type {
  20. case "avg":
  21. for _, point := range series.Points {
  22. if point[0].Valid {
  23. value += point[0].Float64
  24. allNull = false
  25. }
  26. }
  27. value = value / float64(len(series.Points))
  28. case "sum":
  29. for _, point := range series.Points {
  30. if point[0].Valid {
  31. value += point[0].Float64
  32. allNull = false
  33. }
  34. }
  35. case "min":
  36. value = math.MaxFloat64
  37. for _, point := range series.Points {
  38. if point[0].Valid {
  39. allNull = false
  40. if value > point[0].Float64 {
  41. value = point[0].Float64
  42. }
  43. }
  44. }
  45. case "max":
  46. value = -math.MaxFloat64
  47. for _, point := range series.Points {
  48. if point[0].Valid {
  49. allNull = false
  50. if value < point[0].Float64 {
  51. value = point[0].Float64
  52. }
  53. }
  54. }
  55. case "count":
  56. value = float64(len(series.Points))
  57. allNull = false
  58. }
  59. if allNull {
  60. return null.FloatFromPtr(nil)
  61. }
  62. return null.FloatFrom(value)
  63. }
  64. func NewSimpleReducer(typ string) *SimpleReducer {
  65. return &SimpleReducer{Type: typ}
  66. }