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