webhook.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/services/alerting"
  8. )
  9. func init() {
  10. alerting.RegisterNotifier("webhook", NewWebHookNotifier)
  11. }
  12. func NewWebHookNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  13. url := model.Settings.Get("url").MustString()
  14. if url == "" {
  15. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  16. }
  17. return &WebhookNotifier{
  18. NotifierBase: NotifierBase{
  19. Name: model.Name,
  20. Type: model.Type,
  21. },
  22. Url: url,
  23. User: model.Settings.Get("user").MustString(),
  24. Password: model.Settings.Get("password").MustString(),
  25. log: log.New("alerting.notifier.webhook"),
  26. }, nil
  27. }
  28. type WebhookNotifier struct {
  29. NotifierBase
  30. Url string
  31. User string
  32. Password string
  33. log log.Logger
  34. }
  35. func (this *WebhookNotifier) Notify(context *alerting.EvalContext) {
  36. this.log.Info("Sending webhook")
  37. bodyJSON := simplejson.New()
  38. bodyJSON.Set("title", context.GetNotificationTitle())
  39. bodyJSON.Set("ruleId", context.Rule.Id)
  40. bodyJSON.Set("ruleName", context.Rule.Name)
  41. bodyJSON.Set("firing", context.Firing)
  42. bodyJSON.Set("severity", context.Rule.Severity)
  43. body, _ := bodyJSON.MarshalJSON()
  44. cmd := &m.SendWebhook{
  45. Url: this.Url,
  46. User: this.User,
  47. Password: this.Password,
  48. Body: string(body),
  49. }
  50. if err := bus.Dispatch(cmd); err != nil {
  51. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  52. }
  53. }