pagerduty.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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("pagerduty", NewPagerdutyNotifier)
  12. }
  13. func NewPagerdutyNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  14. key := model.Settings.Get("integrationKey").MustString()
  15. if key == "" {
  16. return nil, alerting.ValidationError{Reason: "Could not find integration key property in settings"}
  17. }
  18. return &PagerdutyNotifier{
  19. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  20. Key: key,
  21. log: log.New("alerting.notifier.pagerduty"),
  22. }, nil
  23. }
  24. type PagerdutyNotifier struct {
  25. NotifierBase
  26. Key string
  27. log log.Logger
  28. }
  29. func (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error {
  30. this.log.Info("Notifying Pagerduty")
  31. metrics.M_Alerting_Notification_Sent_PagerDuty.Inc(1)
  32. if evalContext.Rule.State == m.AlertStateAlerting {
  33. // Pagerduty Events API URL
  34. pgEventsUrl := "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  35. bodyJSON := simplejson.New()
  36. bodyJSON.Set("service_key", this.Key)
  37. bodyJSON.Set("description", evalContext.Rule.Name + "-" + evalContext.Rule.Message)
  38. bodyJSON.Set("client", "Grafana")
  39. bodyJSON.Set("event_type", "trigger")
  40. ruleUrl, err := evalContext.GetRuleUrl()
  41. if err != nil {
  42. this.log.Error("Failed get rule link", "error", err)
  43. return err
  44. }
  45. bodyJSON.Set("client_url", ruleUrl)
  46. if evalContext.ImagePublicUrl != "" {
  47. var contexts []interface{}
  48. imageJSON := simplejson.New()
  49. imageJSON.Set("type", "image")
  50. imageJSON.Set("src", evalContext.ImagePublicUrl)
  51. contexts[0] = imageJSON
  52. bodyJSON.Set("contexts", contexts)
  53. }
  54. body, _ := bodyJSON.MarshalJSON()
  55. cmd := &m.SendWebhook{
  56. Url: pgEventsUrl,
  57. Body: string(body),
  58. HttpMethod: "POST",
  59. }
  60. if err := bus.Dispatch(cmd); err != nil {
  61. this.log.Error("Failed to send notification to Pagerduty", "error", err, "body", string(body))
  62. }
  63. } else {
  64. this.log.Info("Not sending a trigger to Pagerduty", "state", evalContext.Rule.State)
  65. }
  66. return nil
  67. }