test_notification.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "github.com/grafana/grafana/pkg/models"
  7. )
  8. type NotificationTestCommand struct {
  9. Severity string
  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 := &models.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. severity := models.AlertSeverityType(cmd.Severity)
  30. notifier.sendNotifications([]Notifier{notifiers}, createTestEvalContext(severity))
  31. return nil
  32. }
  33. func createTestEvalContext(severity models.AlertSeverityType) *EvalContext {
  34. state := models.AlertStateOK
  35. firing := false
  36. if severity == models.AlertSeverityCritical {
  37. state = models.AlertStateCritical
  38. firing = true
  39. }
  40. if severity == models.AlertSeverityWarning {
  41. state = models.AlertStateWarning
  42. firing = true
  43. }
  44. testRule := &Rule{
  45. DashboardId: 1,
  46. PanelId: 1,
  47. Name: "Test notification",
  48. Message: "Someone is testing the alert notification within grafana.",
  49. State: state,
  50. Severity: severity,
  51. }
  52. ctx := NewEvalContext(testRule)
  53. ctx.ImagePublicUrl = "http://grafana.org/assets/img/blog/mixed_styles.png"
  54. ctx.IsTestRun = true
  55. ctx.Firing = firing
  56. ctx.Error = nil
  57. ctx.EvalMatches = evalMatchesBasedOnSeverity(severity)
  58. return ctx
  59. }
  60. func evalMatchesBasedOnSeverity(severity models.AlertSeverityType) []*EvalMatch {
  61. matches := make([]*EvalMatch, 0)
  62. if severity == models.AlertSeverityOK {
  63. return matches
  64. }
  65. matches = append(matches, &EvalMatch{
  66. Metric: "High value",
  67. Value: 100,
  68. })
  69. matches = append(matches, &EvalMatch{
  70. Metric: "Higher Value",
  71. Value: 200,
  72. })
  73. return matches
  74. }