test_rule.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package alerting
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. "github.com/grafana/grafana/pkg/models"
  8. )
  9. // AlertTestCommand initiates an test evaluation
  10. // of an alert rule.
  11. type AlertTestCommand struct {
  12. Dashboard *simplejson.Json
  13. PanelID int64
  14. OrgID int64
  15. User *models.SignedInUser
  16. Result *EvalContext
  17. }
  18. func init() {
  19. bus.AddHandler("alerting", handleAlertTestCommand)
  20. }
  21. func handleAlertTestCommand(cmd *AlertTestCommand) error {
  22. dash := models.NewDashboardFromJson(cmd.Dashboard)
  23. extractor := NewDashAlertExtractor(dash, cmd.OrgID, cmd.User)
  24. alerts, err := extractor.GetAlerts()
  25. if err != nil {
  26. return err
  27. }
  28. for _, alert := range alerts {
  29. if alert.PanelId == cmd.PanelID {
  30. rule, err := NewRuleFromDBAlert(alert)
  31. if err != nil {
  32. return err
  33. }
  34. cmd.Result = testAlertRule(rule)
  35. return nil
  36. }
  37. }
  38. return fmt.Errorf("Could not find alert with panel id %d", cmd.PanelID)
  39. }
  40. func testAlertRule(rule *Rule) *EvalContext {
  41. handler := NewEvalHandler()
  42. context := NewEvalContext(context.Background(), rule)
  43. context.IsTestRun = true
  44. context.IsDebug = true
  45. handler.Eval(context)
  46. context.Rule.State = context.GetNewState()
  47. return context
  48. }