webhook.go 1.9 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: NotifierBase{
  20. Name: model.Name,
  21. Type: model.Type,
  22. },
  23. Url: url,
  24. User: model.Settings.Get("user").MustString(),
  25. Password: model.Settings.Get("password").MustString(),
  26. log: log.New("alerting.notifier.webhook"),
  27. }, nil
  28. }
  29. type WebhookNotifier struct {
  30. NotifierBase
  31. Url string
  32. User string
  33. Password string
  34. log log.Logger
  35. }
  36. func (this *WebhookNotifier) Notify(context *alerting.EvalContext) {
  37. this.log.Info("Sending webhook")
  38. metrics.M_Alerting_Notification_Sent_Webhook.Inc(1)
  39. bodyJSON := simplejson.New()
  40. bodyJSON.Set("title", context.GetNotificationTitle())
  41. bodyJSON.Set("ruleId", context.Rule.Id)
  42. bodyJSON.Set("ruleName", context.Rule.Name)
  43. bodyJSON.Set("state", context.Rule.State)
  44. bodyJSON.Set("severity", context.Rule.Severity)
  45. bodyJSON.Set("evalMatches", context.EvalMatches)
  46. ruleUrl, err := context.GetRuleUrl()
  47. if err == nil {
  48. bodyJSON.Set("rule_url", ruleUrl)
  49. }
  50. imageUrl, err := context.GetImageUrl()
  51. if err == nil {
  52. bodyJSON.Set("image_url", imageUrl)
  53. }
  54. body, _ := bodyJSON.MarshalJSON()
  55. cmd := &m.SendWebhook{
  56. Url: this.Url,
  57. User: this.User,
  58. Password: this.Password,
  59. Body: string(body),
  60. }
  61. if err := bus.Dispatch(cmd); err != nil {
  62. this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
  63. }
  64. }