webhook.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. imageUrl, err := context.GetImageUrl()
  47. if err == nil {
  48. bodyJSON.Set("image_url", imageUrl)
  49. }
  50. body, _ := bodyJSON.MarshalJSON()
  51. cmd := &m.SendWebhook{
  52. Url: this.Url,
  53. User: this.User,
  54. Password: this.Password,
  55. Body: string(body),
  56. }
  57. if err := bus.Dispatch(cmd); err != nil {
  58. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  59. }
  60. }