slack.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package notifiers
  2. import (
  3. "encoding/json"
  4. "time"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/log"
  7. "github.com/grafana/grafana/pkg/metrics"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/services/alerting"
  10. "github.com/grafana/grafana/pkg/setting"
  11. )
  12. func init() {
  13. alerting.RegisterNotifier("slack", NewSlackNotifier)
  14. }
  15. func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  16. url := model.Settings.Get("url").MustString()
  17. if url == "" {
  18. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  19. }
  20. return &SlackNotifier{
  21. NotifierBase: NotifierBase{
  22. Name: model.Name,
  23. Type: model.Type,
  24. },
  25. Url: url,
  26. log: log.New("alerting.notifier.slack"),
  27. }, nil
  28. }
  29. type SlackNotifier struct {
  30. NotifierBase
  31. Url string
  32. log log.Logger
  33. }
  34. func (this *SlackNotifier) Notify(context *alerting.EvalContext) {
  35. this.log.Info("Executing slack notification", "ruleId", context.Rule.Id, "notification", this.Name)
  36. metrics.M_Alerting_Notification_Sent_Slack.Inc(1)
  37. ruleUrl, err := context.GetRuleUrl()
  38. if err != nil {
  39. this.log.Error("Failed get rule link", "error", err)
  40. return
  41. }
  42. fields := make([]map[string]interface{}, 0)
  43. fieldLimitCount := 4
  44. for index, evt := range context.EvalMatches {
  45. fields = append(fields, map[string]interface{}{
  46. "title": evt.Metric,
  47. "value": evt.Value,
  48. "short": true,
  49. })
  50. if index > fieldLimitCount {
  51. break
  52. }
  53. }
  54. body := map[string]interface{}{
  55. "attachments": []map[string]interface{}{
  56. {
  57. "color": context.GetColor(),
  58. //"pretext": "Optional text that appears above the attachment block",
  59. // "author_name": "Bobby Tables",
  60. // "author_link": "http://flickr.com/bobby/",
  61. // "author_icon": "http://flickr.com/icons/bobby.jpg",
  62. "title": context.GetNotificationTitle(),
  63. "title_link": ruleUrl,
  64. "text": context.Rule.Message,
  65. "fields": fields,
  66. "image_url": context.ImagePublicUrl,
  67. // "thumb_url": "http://example.com/path/to/thumb.png",
  68. "footer": "Grafana v" + setting.BuildVersion,
  69. "footer_icon": "http://grafana.org/assets/img/fav32.png",
  70. "ts": time.Now().Unix(),
  71. },
  72. },
  73. }
  74. data, _ := json.Marshal(&body)
  75. cmd := &m.SendWebhook{Url: this.Url, Body: string(data)}
  76. if err := bus.Dispatch(cmd); err != nil {
  77. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  78. }
  79. }