test_notification.go 1.9 KB

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