webhook.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package notifiers
  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/metrics"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/alerting"
  9. )
  10. func init() {
  11. alerting.RegisterNotifier("webhook", NewWebHookNotifier)
  12. }
  13. func NewWebHookNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  14. url := model.Settings.Get("url").MustString()
  15. if url == "" {
  16. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  17. }
  18. return &WebhookNotifier{
  19. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  20. Url: url,
  21. User: model.Settings.Get("user").MustString(),
  22. Password: model.Settings.Get("password").MustString(),
  23. HttpMethod: model.Settings.Get("httpMethod").MustString("POST"),
  24. log: log.New("alerting.notifier.webhook"),
  25. }, nil
  26. }
  27. type WebhookNotifier struct {
  28. NotifierBase
  29. Url string
  30. User string
  31. Password string
  32. HttpMethod string
  33. log log.Logger
  34. }
  35. func (this *WebhookNotifier) Notify(evalContext *alerting.EvalContext) error {
  36. this.log.Info("Sending webhook")
  37. metrics.M_Alerting_Notification_Sent_Webhook.Inc(1)
  38. bodyJSON := simplejson.New()
  39. bodyJSON.Set("title", evalContext.GetNotificationTitle())
  40. bodyJSON.Set("ruleId", evalContext.Rule.Id)
  41. bodyJSON.Set("ruleName", evalContext.Rule.Name)
  42. bodyJSON.Set("state", evalContext.Rule.State)
  43. bodyJSON.Set("evalMatches", evalContext.EvalMatches)
  44. ruleUrl, err := evalContext.GetRuleUrl()
  45. if err == nil {
  46. bodyJSON.Set("ruleUrl", ruleUrl)
  47. }
  48. if evalContext.ImagePublicUrl != "" {
  49. bodyJSON.Set("imageUrl", evalContext.ImagePublicUrl)
  50. }
  51. if evalContext.Rule.Message != "" {
  52. bodyJSON.Set("message", evalContext.Rule.Message)
  53. }
  54. body, _ := bodyJSON.MarshalJSON()
  55. cmd := &m.SendWebhookSync{
  56. Url: this.Url,
  57. User: this.User,
  58. Password: this.Password,
  59. Body: string(body),
  60. HttpMethod: this.HttpMethod,
  61. }
  62. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  63. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  64. return err
  65. }
  66. return nil
  67. }