slack.go 2.4 KB

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