webhook.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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("rule_url", ruleUrl)
  47. }
  48. if evalContext.ImagePublicUrl != "" {
  49. bodyJSON.Set("image_url", evalContext.ImagePublicUrl)
  50. }
  51. body, _ := bodyJSON.MarshalJSON()
  52. cmd := &m.SendWebhookSync{
  53. Url: this.Url,
  54. User: this.User,
  55. Password: this.Password,
  56. Body: string(body),
  57. HttpMethod: this.HttpMethod,
  58. }
  59. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  60. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  61. }
  62. return nil
  63. }