webhook.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.Name, model.Type, model.Settings),
  20. Url: url,
  21. User: model.Settings.Get("user").MustString(),
  22. Password: model.Settings.Get("password").MustString(),
  23. log: log.New("alerting.notifier.webhook"),
  24. }, nil
  25. }
  26. type WebhookNotifier struct {
  27. NotifierBase
  28. Url string
  29. User string
  30. Password string
  31. log log.Logger
  32. }
  33. func (this *WebhookNotifier) Notify(evalContext *alerting.EvalContext) error {
  34. this.log.Info("Sending webhook")
  35. metrics.M_Alerting_Notification_Sent_Webhook.Inc(1)
  36. bodyJSON := simplejson.New()
  37. bodyJSON.Set("title", evalContext.GetNotificationTitle())
  38. bodyJSON.Set("ruleId", evalContext.Rule.Id)
  39. bodyJSON.Set("ruleName", evalContext.Rule.Name)
  40. bodyJSON.Set("state", evalContext.Rule.State)
  41. bodyJSON.Set("evalMatches", evalContext.EvalMatches)
  42. ruleUrl, err := evalContext.GetRuleUrl()
  43. if err == nil {
  44. bodyJSON.Set("rule_url", ruleUrl)
  45. }
  46. if evalContext.ImagePublicUrl != "" {
  47. bodyJSON.Set("image_url", evalContext.ImagePublicUrl)
  48. }
  49. body, _ := bodyJSON.MarshalJSON()
  50. cmd := &m.SendWebhookSync{
  51. Url: this.Url,
  52. User: this.User,
  53. Password: this.Password,
  54. Body: string(body),
  55. }
  56. if err := bus.DispatchCtx(evalContext, cmd); err != nil {
  57. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  58. }
  59. return nil
  60. }