conditions.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package alerting
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/grafana/grafana/pkg/components/simplejson"
  6. )
  7. type QueryCondition struct {
  8. Query AlertQuery
  9. Reducer QueryReducer
  10. Evaluator AlertEvaluator
  11. }
  12. func (c *QueryCondition) Eval() {
  13. }
  14. func NewQueryCondition(model *simplejson.Json) (*QueryCondition, error) {
  15. condition := QueryCondition{}
  16. queryJson := model.Get("query")
  17. condition.Query.Query = queryJson.Get("query").MustString()
  18. condition.Query.From = queryJson.Get("params").MustArray()[1].(string)
  19. condition.Query.To = queryJson.Get("params").MustArray()[2].(string)
  20. condition.Query.DatasourceId = queryJson.Get("datasourceId").MustInt64()
  21. reducerJson := model.Get("reducer")
  22. condition.Reducer = NewSimpleReducer(reducerJson.Get("type").MustString())
  23. evaluatorJson := model.Get("evaluator")
  24. evaluator, err := NewDefaultAlertEvaluator(evaluatorJson)
  25. if err != nil {
  26. return nil, err
  27. }
  28. condition.Evaluator = evaluator
  29. return &condition, nil
  30. }
  31. type SimpleReducer struct {
  32. Type string
  33. }
  34. func (s *SimpleReducer) Reduce() float64 {
  35. return 0
  36. }
  37. func NewSimpleReducer(typ string) *SimpleReducer {
  38. return &SimpleReducer{Type: typ}
  39. }
  40. type DefaultAlertEvaluator struct {
  41. Type string
  42. Threshold float64
  43. }
  44. func (e *DefaultAlertEvaluator) Eval() bool {
  45. return true
  46. }
  47. func NewDefaultAlertEvaluator(model *simplejson.Json) (*DefaultAlertEvaluator, error) {
  48. evaluator := &DefaultAlertEvaluator{}
  49. evaluator.Type = model.Get("type").MustString()
  50. if evaluator.Type == "" {
  51. return nil, errors.New("Alert evaluator missing type property")
  52. }
  53. params := model.Get("params").MustArray()
  54. if len(params) == 0 {
  55. return nil, errors.New("Alert evaluator missing threshold parameter")
  56. }
  57. threshold, ok := params[0].(json.Number)
  58. if !ok {
  59. return nil, errors.New("Alert evaluator has invalid threshold parameter")
  60. }
  61. evaluator.Threshold, _ = threshold.Float64()
  62. return evaluator, nil
  63. }