slack.go 2.3 KB

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