webhook.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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("name", context.Rule.Name)
  39. bodyJSON.Set("firing", context.Firing)
  40. bodyJSON.Set("severity", context.Rule.Severity)
  41. body, _ := bodyJSON.MarshalJSON()
  42. cmd := &m.SendWebhook{
  43. Url: this.Url,
  44. User: this.User,
  45. Password: this.Password,
  46. Body: string(body),
  47. }
  48. if err := bus.Dispatch(cmd); err != nil {
  49. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  50. }
  51. }