webhook.go 1.9 KB

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