evaluator.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package conditions
  2. import (
  3. "encoding/json"
  4. "github.com/grafana/grafana/pkg/components/simplejson"
  5. "github.com/grafana/grafana/pkg/services/alerting"
  6. "github.com/grafana/grafana/pkg/tsdb"
  7. )
  8. type AlertEvaluator interface {
  9. Eval(timeSeries *tsdb.TimeSeries, reducedValue float64) bool
  10. }
  11. type DefaultAlertEvaluator struct {
  12. Type string
  13. Threshold float64
  14. }
  15. func (e *DefaultAlertEvaluator) Eval(series *tsdb.TimeSeries, reducedValue float64) bool {
  16. switch e.Type {
  17. case "gt":
  18. return reducedValue > e.Threshold
  19. case "lt":
  20. return reducedValue < e.Threshold
  21. }
  22. return false
  23. }
  24. func NewDefaultAlertEvaluator(model *simplejson.Json) (*DefaultAlertEvaluator, error) {
  25. evaluator := &DefaultAlertEvaluator{}
  26. evaluator.Type = model.Get("type").MustString()
  27. if evaluator.Type == "" {
  28. return nil, alerting.ValidationError{Reason: "Evaluator missing type property"}
  29. }
  30. params := model.Get("params").MustArray()
  31. if len(params) == 0 {
  32. return nil, alerting.ValidationError{Reason: "Evaluator missing threshold parameter"}
  33. }
  34. threshold, ok := params[0].(json.Number)
  35. if !ok {
  36. return nil, alerting.ValidationError{Reason: "Evaluator has invalid threshold parameter"}
  37. }
  38. evaluator.Threshold, _ = threshold.Float64()
  39. return evaluator, nil
  40. }