webhook.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(context *alerting.EvalContext) {
  34. this.log.Info("Sending webhook")
  35. metrics.M_Alerting_Notification_Sent_Webhook.Inc(1)
  36. bodyJSON := simplejson.New()
  37. bodyJSON.Set("title", context.GetNotificationTitle())
  38. bodyJSON.Set("ruleId", context.Rule.Id)
  39. bodyJSON.Set("ruleName", context.Rule.Name)
  40. bodyJSON.Set("state", context.Rule.State)
  41. bodyJSON.Set("evalMatches", context.EvalMatches)
  42. ruleUrl, err := context.GetRuleUrl()
  43. if err == nil {
  44. bodyJSON.Set("rule_url", ruleUrl)
  45. }
  46. if context.ImagePublicUrl != "" {
  47. bodyJSON.Set("image_url", context.ImagePublicUrl)
  48. }
  49. body, _ := bodyJSON.MarshalJSON()
  50. cmd := &m.SendWebhook{
  51. Url: this.Url,
  52. User: this.User,
  53. Password: this.Password,
  54. Body: string(body),
  55. }
  56. if err := bus.Dispatch(cmd); err != nil {
  57. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  58. }
  59. }