test_notification.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package alerting
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/null"
  7. "github.com/grafana/grafana/pkg/components/simplejson"
  8. "github.com/grafana/grafana/pkg/infra/log"
  9. "github.com/grafana/grafana/pkg/models"
  10. )
  11. // NotificationTestCommand initiates an test
  12. // execution of an alert notification.
  13. type NotificationTestCommand struct {
  14. State models.AlertStateType
  15. Name string
  16. Type string
  17. Settings *simplejson.Json
  18. }
  19. var (
  20. logger = log.New("alerting.testnotification")
  21. )
  22. func init() {
  23. bus.AddHandler("alerting", handleNotificationTestCommand)
  24. }
  25. func handleNotificationTestCommand(cmd *NotificationTestCommand) error {
  26. notifier := newNotificationService(nil)
  27. model := &models.AlertNotification{
  28. Name: cmd.Name,
  29. Type: cmd.Type,
  30. Settings: cmd.Settings,
  31. }
  32. notifiers, err := InitNotifier(model)
  33. if err != nil {
  34. logger.Error("Failed to create notifier", "error", err.Error())
  35. return err
  36. }
  37. return notifier.sendNotifications(createTestEvalContext(cmd), notifierStateSlice{{notifier: notifiers}})
  38. }
  39. func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext {
  40. testRule := &Rule{
  41. DashboardID: 1,
  42. PanelID: 1,
  43. Name: "Test notification",
  44. Message: "Someone is testing the alert notification within grafana.",
  45. State: models.AlertStateAlerting,
  46. }
  47. ctx := NewEvalContext(context.Background(), testRule)
  48. if cmd.Settings.Get("uploadImage").MustBool(true) {
  49. ctx.ImagePublicURL = "https://grafana.com/assets/img/blog/mixed_styles.png"
  50. }
  51. ctx.IsTestRun = true
  52. ctx.Firing = true
  53. ctx.Error = fmt.Errorf("This is only a test")
  54. ctx.EvalMatches = evalMatchesBasedOnState()
  55. return ctx
  56. }
  57. func evalMatchesBasedOnState() []*EvalMatch {
  58. matches := make([]*EvalMatch, 0)
  59. matches = append(matches, &EvalMatch{
  60. Metric: "High value",
  61. Value: null.FloatFrom(100),
  62. })
  63. matches = append(matches, &EvalMatch{
  64. Metric: "Higher Value",
  65. Value: null.FloatFrom(200),
  66. })
  67. return matches
  68. }