slack.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package notifiers
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "mime/multipart"
  7. "os"
  8. "path/filepath"
  9. "time"
  10. "github.com/grafana/grafana/pkg/bus"
  11. "github.com/grafana/grafana/pkg/log"
  12. m "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/services/alerting"
  14. "github.com/grafana/grafana/pkg/setting"
  15. )
  16. func init() {
  17. alerting.RegisterNotifier(&alerting.NotifierPlugin{
  18. Type: "slack",
  19. Name: "Slack",
  20. Description: "Sends notifications to Slack via Slack Webhooks",
  21. Factory: NewSlackNotifier,
  22. OptionsTemplate: `
  23. <h3 class="page-heading">Slack settings</h3>
  24. <div class="gf-form max-width-30">
  25. <span class="gf-form-label width-6">Url</span>
  26. <input type="text" required class="gf-form-input max-width-30" ng-model="ctrl.model.settings.url" placeholder="Slack incoming webhook url"></input>
  27. </div>
  28. <div class="gf-form max-width-30">
  29. <span class="gf-form-label width-6">Recipient</span>
  30. <input type="text"
  31. class="gf-form-input max-width-30"
  32. ng-model="ctrl.model.settings.recipient"
  33. data-placement="right">
  34. </input>
  35. <info-popover mode="right-absolute">
  36. Override default channel or user, use #channel-name or @username
  37. </info-popover>
  38. </div>
  39. <div class="gf-form max-width-30">
  40. <span class="gf-form-label width-6">Mention</span>
  41. <input type="text"
  42. class="gf-form-input max-width-30"
  43. ng-model="ctrl.model.settings.mention"
  44. data-placement="right">
  45. </input>
  46. <info-popover mode="right-absolute">
  47. Mention a user or a group using @ when notifying in a channel
  48. </info-popover>
  49. </div>
  50. <div class="gf-form max-width-30">
  51. <span class="gf-form-label width-6">Token</span>
  52. <input type="text"
  53. class="gf-form-input max-width-30"
  54. ng-model="ctrl.model.settings.token"
  55. data-placement="right">
  56. </input>
  57. <info-popover mode="right-absolute">
  58. Provide a bot token to use the Slack file.upload API (starts with "xoxb")
  59. </info-popover>
  60. </div>
  61. `,
  62. })
  63. }
  64. func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  65. url := model.Settings.Get("url").MustString()
  66. if url == "" {
  67. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  68. }
  69. recipient := model.Settings.Get("recipient").MustString()
  70. mention := model.Settings.Get("mention").MustString()
  71. token := model.Settings.Get("token").MustString()
  72. uploadImage := model.Settings.Get("uploadImage").MustBool(true)
  73. return &SlackNotifier{
  74. NotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),
  75. Url: url,
  76. Recipient: recipient,
  77. Mention: mention,
  78. Token: token,
  79. Upload: uploadImage,
  80. log: log.New("alerting.notifier.slack"),
  81. }, nil
  82. }
  83. type SlackNotifier struct {
  84. NotifierBase
  85. Url string
  86. Recipient string
  87. Mention string
  88. Token string
  89. Upload bool
  90. log log.Logger
  91. }
  92. func (this *SlackNotifier) ShouldNotify(context *alerting.EvalContext) bool {
  93. return defaultShouldNotify(context)
  94. }
  95. func (this *SlackNotifier) Notify(evalContext *alerting.EvalContext) error {
  96. this.log.Info("Executing slack notification", "ruleId", evalContext.Rule.Id, "notification", this.Name)
  97. ruleUrl, err := evalContext.GetRuleUrl()
  98. if err != nil {
  99. this.log.Error("Failed get rule link", "error", err)
  100. return err
  101. }
  102. fields := make([]map[string]interface{}, 0)
  103. fieldLimitCount := 4
  104. for index, evt := range evalContext.EvalMatches {
  105. fields = append(fields, map[string]interface{}{
  106. "title": evt.Metric,
  107. "value": evt.Value,
  108. "short": true,
  109. })
  110. if index > fieldLimitCount {
  111. break
  112. }
  113. }
  114. if evalContext.Error != nil {
  115. fields = append(fields, map[string]interface{}{
  116. "title": "Error message",
  117. "value": evalContext.Error.Error(),
  118. "short": false,
  119. })
  120. }
  121. message := this.Mention
  122. if evalContext.Rule.State != m.AlertStateOK { //dont add message when going back to alert state ok.
  123. message += " " + evalContext.Rule.Message
  124. }
  125. image_url := ""
  126. // default to file.upload API method if a token is provided
  127. if this.Token == "" {
  128. image_url = evalContext.ImagePublicUrl
  129. }
  130. body := map[string]interface{}{
  131. "attachments": []map[string]interface{}{
  132. {
  133. "fallback": evalContext.GetNotificationTitle(),
  134. "color": evalContext.GetStateModel().Color,
  135. "title": evalContext.GetNotificationTitle(),
  136. "title_link": ruleUrl,
  137. "text": message,
  138. "fields": fields,
  139. "image_url": image_url,
  140. "footer": "Grafana v" + setting.BuildVersion,
  141. "footer_icon": "https://grafana.com/assets/img/fav32.png",
  142. "ts": time.Now().Unix(),
  143. },
  144. },
  145. "parse": "full", // to linkify urls, users and channels in alert message.
  146. }
  147. //recipient override
  148. if this.Recipient != "" {
  149. body["channel"] = this.Recipient
  150. }
  151. data, _ := json.Marshal(&body)
  152. cmd := &m.SendWebhookSync{Url: this.Url, Body: string(data)}
  153. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  154. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  155. return err
  156. }
  157. if this.Token != "" && this.UploadImage {
  158. err = SlackFileUpload(evalContext, this.log, "https://slack.com/api/files.upload", this.Recipient, this.Token)
  159. if err != nil {
  160. return err
  161. }
  162. }
  163. return nil
  164. }
  165. func SlackFileUpload(evalContext *alerting.EvalContext, log log.Logger, url string, recipient string, token string) error {
  166. if evalContext.ImageOnDiskPath == "" {
  167. evalContext.ImageOnDiskPath = filepath.Join(setting.HomePath, "public/img/mixed_styles.png")
  168. }
  169. log.Info("Uploading to slack via file.upload API")
  170. headers, uploadBody, err := GenerateSlackBody(evalContext.ImageOnDiskPath, token, recipient)
  171. if err != nil {
  172. return err
  173. }
  174. cmd := &m.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"}
  175. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  176. log.Error("Failed to upload slack image", "error", err, "webhook", "file.upload")
  177. return err
  178. }
  179. if err != nil {
  180. return err
  181. }
  182. return nil
  183. }
  184. func GenerateSlackBody(file string, token string, recipient string) (map[string]string, bytes.Buffer, error) {
  185. // Slack requires all POSTs to files.upload to present
  186. // an "application/x-www-form-urlencoded" encoded querystring
  187. // See https://api.slack.com/methods/files.upload
  188. var b bytes.Buffer
  189. w := multipart.NewWriter(&b)
  190. // Add the generated image file
  191. f, err := os.Open(file)
  192. if err != nil {
  193. return nil, b, err
  194. }
  195. defer f.Close()
  196. fw, err := w.CreateFormFile("file", file)
  197. if err != nil {
  198. return nil, b, err
  199. }
  200. _, err = io.Copy(fw, f)
  201. if err != nil {
  202. return nil, b, err
  203. }
  204. // Add the authorization token
  205. err = w.WriteField("token", token)
  206. if err != nil {
  207. return nil, b, err
  208. }
  209. // Add the channel(s) to POST to
  210. err = w.WriteField("channels", recipient)
  211. if err != nil {
  212. return nil, b, err
  213. }
  214. w.Close()
  215. headers := map[string]string{
  216. "Content-Type": w.FormDataContentType(),
  217. "Authorization": "auth_token=\"" + token + "\"",
  218. }
  219. return headers, b, nil
  220. }