slack.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package notifiers
  2. import (
  3. "fmt"
  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("slack", NewSlackNotifier)
  12. }
  13. func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  14. url := model.Settings.Get("url").MustString()
  15. if url == "" {
  16. return nil, alerting.AlertValidationError{Reason: "Could not find url property in settings"}
  17. }
  18. return &SlackNotifier{
  19. NotifierBase: NotifierBase{
  20. Name: model.Name,
  21. Type: model.Type,
  22. },
  23. Url: url,
  24. log: log.New("alerting.notifier.slack"),
  25. }, nil
  26. }
  27. type SlackNotifier struct {
  28. NotifierBase
  29. Url string
  30. log log.Logger
  31. }
  32. func (this *SlackNotifier) Notify(context *alerting.AlertResultContext) {
  33. this.log.Info("Executing slack notification", "ruleId", context.Rule.Id, "notification", this.Name)
  34. rule := context.Rule
  35. ruleLink, err := getRuleLink(rule)
  36. if err != nil {
  37. this.log.Error("Failed get rule link", "error", err)
  38. return
  39. }
  40. stateText := string(rule.Severity)
  41. if !context.Firing {
  42. stateText = "ok"
  43. }
  44. text := fmt.Sprintf("[%s]: <%s|%s>", stateText, ruleLink, rule.Name)
  45. body := simplejson.New()
  46. body.Set("text", text)
  47. data, _ := body.MarshalJSON()
  48. cmd := &m.SendWebhook{Url: this.Url, Body: string(data)}
  49. if err := bus.Dispatch(cmd); err != nil {
  50. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  51. }
  52. }