alertmanager.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package notifiers
  2. import (
  3. "time"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/simplejson"
  6. "github.com/grafana/grafana/pkg/log"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/alerting"
  9. )
  10. func init() {
  11. alerting.RegisterNotifier(&alerting.NotifierPlugin{
  12. Type: "prometheus-alertmanager",
  13. Name: "Prometheus Alertmanager",
  14. Description: "Sends alert to Prometheus Alertmanager",
  15. Factory: NewAlertmanagerNotifier,
  16. OptionsTemplate: `
  17. <h3 class="page-heading">Alertmanager settings</h3>
  18. <div class="gf-form">
  19. <span class="gf-form-label width-10">Url</span>
  20. <input type="text" required class="gf-form-input max-width-26" ng-model="ctrl.model.settings.url" placeholder="http://localhost:9093"></input>
  21. </div>
  22. `,
  23. })
  24. }
  25. func NewAlertmanagerNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  26. url := model.Settings.Get("url").MustString()
  27. if url == "" {
  28. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  29. }
  30. return &AlertmanagerNotifier{
  31. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  32. Url: url,
  33. log: log.New("alerting.notifier.prometheus-alertmanager"),
  34. }, nil
  35. }
  36. type AlertmanagerNotifier struct {
  37. NotifierBase
  38. Url string
  39. log log.Logger
  40. }
  41. func (this *AlertmanagerNotifier) ShouldNotify(evalContext *alerting.EvalContext) bool {
  42. this.log.Debug("Should notify", "ruleId", evalContext.Rule.Id, "state", evalContext.Rule.State, "previousState", evalContext.PrevAlertState)
  43. // Do not notify when we become OK for the first time.
  44. if (evalContext.PrevAlertState == m.AlertStatePending) && (evalContext.Rule.State == m.AlertStateOK) {
  45. return false
  46. }
  47. // Notify on Alerting -> OK to resolve before alertmanager timeout.
  48. if (evalContext.PrevAlertState == m.AlertStateAlerting) && (evalContext.Rule.State == m.AlertStateOK) {
  49. return true
  50. }
  51. return evalContext.Rule.State == m.AlertStateAlerting
  52. }
  53. func (this *AlertmanagerNotifier) createAlert(evalContext *alerting.EvalContext, match *alerting.EvalMatch, ruleUrl string) *simplejson.Json {
  54. alertJSON := simplejson.New()
  55. alertJSON.Set("startsAt", evalContext.StartTime.UTC().Format(time.RFC3339))
  56. if evalContext.Rule.State == m.AlertStateOK {
  57. alertJSON.Set("endsAt", time.Now().UTC().Format(time.RFC3339))
  58. }
  59. alertJSON.Set("generatorURL", ruleUrl)
  60. // Annotations (summary and description are very commonly used).
  61. alertJSON.SetPath([]string{"annotations", "summary"}, evalContext.Rule.Name)
  62. description := ""
  63. if evalContext.Rule.Message != "" {
  64. description += evalContext.Rule.Message
  65. }
  66. if evalContext.Error != nil {
  67. if description != "" {
  68. description += "\n"
  69. }
  70. description += "Error: " + evalContext.Error.Error()
  71. }
  72. if description != "" {
  73. alertJSON.SetPath([]string{"annotations", "description"}, description)
  74. }
  75. if evalContext.ImagePublicUrl != "" {
  76. alertJSON.SetPath([]string{"annotations", "image"}, evalContext.ImagePublicUrl)
  77. }
  78. // Labels (from metrics tags + mandatory alertname).
  79. tags := make(map[string]string)
  80. if match != nil {
  81. if len(match.Tags) == 0 {
  82. tags["metric"] = match.Metric
  83. } else {
  84. for k, v := range match.Tags {
  85. tags[k] = v
  86. }
  87. }
  88. }
  89. tags["alertname"] = evalContext.Rule.Name
  90. alertJSON.Set("labels", tags)
  91. return alertJSON
  92. }
  93. func (this *AlertmanagerNotifier) Notify(evalContext *alerting.EvalContext) error {
  94. this.log.Info("Sending Alertmanager alert", "ruleId", evalContext.Rule.Id, "notification", this.Name)
  95. ruleUrl, err := evalContext.GetRuleUrl()
  96. if err != nil {
  97. this.log.Error("Failed get rule link", "error", err)
  98. return err
  99. }
  100. // Send one alert per matching series.
  101. alerts := make([]interface{}, 0)
  102. for _, match := range evalContext.EvalMatches {
  103. alert := this.createAlert(evalContext, match, ruleUrl)
  104. alerts = append(alerts, alert)
  105. }
  106. // This happens on ExecutionError or NoData
  107. if len(alerts) == 0 {
  108. alert := this.createAlert(evalContext, nil, ruleUrl)
  109. alerts = append(alerts, alert)
  110. }
  111. bodyJSON := simplejson.NewFromAny(alerts)
  112. body, _ := bodyJSON.MarshalJSON()
  113. cmd := &m.SendWebhookSync{
  114. Url: this.Url + "/api/v1/alerts",
  115. HttpMethod: "POST",
  116. Body: string(body),
  117. }
  118. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  119. this.log.Error("Failed to send alertmanager", "error", err, "alertmanager", this.Name)
  120. return err
  121. }
  122. return nil
  123. }