test_notification.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package alerting
  2. import (
  3. "github.com/grafana/grafana/pkg/bus"
  4. "github.com/grafana/grafana/pkg/components/simplejson"
  5. "github.com/grafana/grafana/pkg/log"
  6. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. type NotificationTestCommand struct {
  9. State m.AlertStateType
  10. Name string
  11. Type string
  12. Settings *simplejson.Json
  13. }
  14. func init() {
  15. bus.AddHandler("alerting", handleNotificationTestCommand)
  16. }
  17. func handleNotificationTestCommand(cmd *NotificationTestCommand) error {
  18. notifier := NewRootNotifier()
  19. model := &m.AlertNotification{
  20. Name: cmd.Name,
  21. Type: cmd.Type,
  22. Settings: cmd.Settings,
  23. }
  24. notifiers, err := notifier.createNotifierFor(model)
  25. if err != nil {
  26. log.Error2("Failed to create notifier", "error", err.Error())
  27. return err
  28. }
  29. notifier.sendNotifications([]Notifier{notifiers}, createTestEvalContext(cmd.State))
  30. return nil
  31. }
  32. func createTestEvalContext(state m.AlertStateType) *EvalContext {
  33. testRule := &Rule{
  34. DashboardId: 1,
  35. PanelId: 1,
  36. Name: "Test notification",
  37. Message: "Someone is testing the alert notification within grafana.",
  38. State: state,
  39. }
  40. ctx := NewEvalContext(testRule)
  41. ctx.ImagePublicUrl = "http://grafana.org/assets/img/blog/mixed_styles.png"
  42. ctx.IsTestRun = true
  43. ctx.Firing = state == m.AlertStateAlerting
  44. ctx.Error = nil
  45. ctx.EvalMatches = evalMatchesBasedOnState(state)
  46. return ctx
  47. }
  48. func evalMatchesBasedOnState(state m.AlertStateType) []*EvalMatch {
  49. matches := make([]*EvalMatch, 0)
  50. if state == m.AlertStateOK {
  51. return matches
  52. }
  53. matches = append(matches, &EvalMatch{
  54. Metric: "High value",
  55. Value: 100,
  56. })
  57. matches = append(matches, &EvalMatch{
  58. Metric: "Higher Value",
  59. Value: 200,
  60. })
  61. return matches
  62. }