slack.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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"). Specify #channel-name or @username in Recipient for this to work
  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) Notify(evalContext *alerting.EvalContext) error {
  93. this.log.Info("Executing slack notification", "ruleId", evalContext.Rule.Id, "notification", this.Name)
  94. ruleUrl, err := evalContext.GetRuleUrl()
  95. if err != nil {
  96. this.log.Error("Failed get rule link", "error", err)
  97. return err
  98. }
  99. fields := make([]map[string]interface{}, 0)
  100. fieldLimitCount := 4
  101. for index, evt := range evalContext.EvalMatches {
  102. fields = append(fields, map[string]interface{}{
  103. "title": evt.Metric,
  104. "value": evt.Value,
  105. "short": true,
  106. })
  107. if index > fieldLimitCount {
  108. break
  109. }
  110. }
  111. if evalContext.Error != nil {
  112. fields = append(fields, map[string]interface{}{
  113. "title": "Error message",
  114. "value": evalContext.Error.Error(),
  115. "short": false,
  116. })
  117. }
  118. message := this.Mention
  119. if evalContext.Rule.State != m.AlertStateOK { //don't add message when going back to alert state ok.
  120. message += " " + evalContext.Rule.Message
  121. }
  122. image_url := ""
  123. // default to file.upload API method if a token is provided
  124. if this.Token == "" {
  125. image_url = evalContext.ImagePublicUrl
  126. }
  127. body := map[string]interface{}{
  128. "attachments": []map[string]interface{}{
  129. {
  130. "fallback": evalContext.GetNotificationTitle(),
  131. "color": evalContext.GetStateModel().Color,
  132. "title": evalContext.GetNotificationTitle(),
  133. "title_link": ruleUrl,
  134. "text": message,
  135. "fields": fields,
  136. "image_url": image_url,
  137. "footer": "Grafana v" + setting.BuildVersion,
  138. "footer_icon": "https://grafana.com/assets/img/fav32.png",
  139. "ts": time.Now().Unix(),
  140. },
  141. },
  142. "parse": "full", // to linkify urls, users and channels in alert message.
  143. }
  144. //recipient override
  145. if this.Recipient != "" {
  146. body["channel"] = this.Recipient
  147. }
  148. data, _ := json.Marshal(&body)
  149. cmd := &m.SendWebhookSync{Url: this.Url, Body: string(data)}
  150. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  151. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  152. return err
  153. }
  154. if this.Token != "" && this.UploadImage {
  155. err = SlackFileUpload(evalContext, this.log, "https://slack.com/api/files.upload", this.Recipient, this.Token)
  156. if err != nil {
  157. return err
  158. }
  159. }
  160. return nil
  161. }
  162. func SlackFileUpload(evalContext *alerting.EvalContext, log log.Logger, url string, recipient string, token string) error {
  163. if evalContext.ImageOnDiskPath == "" {
  164. evalContext.ImageOnDiskPath = filepath.Join(setting.HomePath, "public/img/mixed_styles.png")
  165. }
  166. log.Info("Uploading to slack via file.upload API")
  167. headers, uploadBody, err := GenerateSlackBody(evalContext.ImageOnDiskPath, token, recipient)
  168. if err != nil {
  169. return err
  170. }
  171. cmd := &m.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"}
  172. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  173. log.Error("Failed to upload slack image", "error", err, "webhook", "file.upload")
  174. return err
  175. }
  176. if err != nil {
  177. return err
  178. }
  179. return nil
  180. }
  181. func GenerateSlackBody(file string, token string, recipient string) (map[string]string, bytes.Buffer, error) {
  182. // Slack requires all POSTs to files.upload to present
  183. // an "application/x-www-form-urlencoded" encoded querystring
  184. // See https://api.slack.com/methods/files.upload
  185. var b bytes.Buffer
  186. w := multipart.NewWriter(&b)
  187. // Add the generated image file
  188. f, err := os.Open(file)
  189. if err != nil {
  190. return nil, b, err
  191. }
  192. defer f.Close()
  193. fw, err := w.CreateFormFile("file", file)
  194. if err != nil {
  195. return nil, b, err
  196. }
  197. _, err = io.Copy(fw, f)
  198. if err != nil {
  199. return nil, b, err
  200. }
  201. // Add the authorization token
  202. err = w.WriteField("token", token)
  203. if err != nil {
  204. return nil, b, err
  205. }
  206. // Add the channel(s) to POST to
  207. err = w.WriteField("channels", recipient)
  208. if err != nil {
  209. return nil, b, err
  210. }
  211. w.Close()
  212. headers := map[string]string{
  213. "Content-Type": w.FormDataContentType(),
  214. "Authorization": "auth_token=\"" + token + "\"",
  215. }
  216. return headers, b, nil
  217. }