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. 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.ValidationError{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.EvalContext) {
  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. fields := make([]map[string]interface{}, 0)
  41. fieldLimitCount := 4
  42. for index, evt := range context.Events {
  43. fields = append(fields, map[string]interface{}{
  44. "title": evt.Metric,
  45. "value": evt.Value,
  46. "short": true,
  47. })
  48. if index > fieldLimitCount {
  49. break
  50. }
  51. }
  52. body := map[string]interface{}{
  53. "attachments": []map[string]interface{}{
  54. map[string]interface{}{
  55. "color": context.GetColor(),
  56. //"pretext": "Optional text that appears above the attachment block",
  57. // "author_name": "Bobby Tables",
  58. // "author_link": "http://flickr.com/bobby/",
  59. // "author_icon": "http://flickr.com/icons/bobby.jpg",
  60. "title": "[" + context.GetStateText() + "] " + rule.Name,
  61. "title_link": ruleLink,
  62. // "text": "Optional text that appears within the attachment",
  63. "fields": fields,
  64. // "image_url": "http://my-website.com/path/to/image.jpg",
  65. // "thumb_url": "http://example.com/path/to/thumb.png",
  66. "footer": "Grafana v4.0.0",
  67. "footer_icon": "http://grafana.org/assets/img/fav32.png",
  68. "ts": time.Now().Unix(),
  69. },
  70. },
  71. }
  72. data, _ := json.Marshal(&body)
  73. cmd := &m.SendWebhook{Url: this.Url, Body: string(data)}
  74. if err := bus.Dispatch(cmd); err != nil {
  75. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  76. }
  77. }