webhook.go 1.7 KB

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