slack.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/infra/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">Username</span>
  41. <input type="text"
  42. class="gf-form-input max-width-30"
  43. ng-model="ctrl.model.settings.username"
  44. data-placement="right">
  45. </input>
  46. <info-popover mode="right-absolute">
  47. Set the username for the bot's message
  48. </info-popover>
  49. </div>
  50. <div class="gf-form max-width-30">
  51. <span class="gf-form-label width-6">Icon emoji</span>
  52. <input type="text"
  53. class="gf-form-input max-width-30"
  54. ng-model="ctrl.model.settings.icon_emoji"
  55. data-placement="right">
  56. </input>
  57. <info-popover mode="right-absolute">
  58. Provide an emoji to use as the icon for the bot's message. Overrides the icon URL
  59. </info-popover>
  60. </div>
  61. <div class="gf-form max-width-30">
  62. <span class="gf-form-label width-6">Icon URL</span>
  63. <input type="text"
  64. class="gf-form-input max-width-30"
  65. ng-model="ctrl.model.settings.icon_url"
  66. data-placement="right">
  67. </input>
  68. <info-popover mode="right-absolute">
  69. Provide a URL to an image to use as the icon for the bot's message
  70. </info-popover>
  71. </div>
  72. <div class="gf-form max-width-30">
  73. <span class="gf-form-label width-6">Mention</span>
  74. <input type="text"
  75. class="gf-form-input max-width-30"
  76. ng-model="ctrl.model.settings.mention"
  77. data-placement="right">
  78. </input>
  79. <info-popover mode="right-absolute">
  80. Mention a user or a group using @ when notifying in a channel
  81. </info-popover>
  82. </div>
  83. <div class="gf-form max-width-30">
  84. <span class="gf-form-label width-6">Token</span>
  85. <input type="text"
  86. class="gf-form-input max-width-30"
  87. ng-model="ctrl.model.settings.token"
  88. data-placement="right">
  89. </input>
  90. <info-popover mode="right-absolute">
  91. 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
  92. </info-popover>
  93. </div>
  94. `,
  95. })
  96. }
  97. func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  98. url := model.Settings.Get("url").MustString()
  99. if url == "" {
  100. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  101. }
  102. recipient := model.Settings.Get("recipient").MustString()
  103. username := model.Settings.Get("username").MustString()
  104. iconEmoji := model.Settings.Get("icon_emoji").MustString()
  105. iconUrl := model.Settings.Get("icon_url").MustString()
  106. mention := model.Settings.Get("mention").MustString()
  107. token := model.Settings.Get("token").MustString()
  108. uploadImage := model.Settings.Get("uploadImage").MustBool(true)
  109. return &SlackNotifier{
  110. NotifierBase: NewNotifierBase(model),
  111. Url: url,
  112. Recipient: recipient,
  113. Username: username,
  114. IconEmoji: iconEmoji,
  115. IconUrl: iconUrl,
  116. Mention: mention,
  117. Token: token,
  118. Upload: uploadImage,
  119. log: log.New("alerting.notifier.slack"),
  120. }, nil
  121. }
  122. type SlackNotifier struct {
  123. NotifierBase
  124. Url string
  125. Recipient string
  126. Username string
  127. IconEmoji string
  128. IconUrl string
  129. Mention string
  130. Token string
  131. Upload bool
  132. log log.Logger
  133. }
  134. func (this *SlackNotifier) Notify(evalContext *alerting.EvalContext) error {
  135. this.log.Info("Executing slack notification", "ruleId", evalContext.Rule.Id, "notification", this.Name)
  136. ruleUrl, err := evalContext.GetRuleUrl()
  137. if err != nil {
  138. this.log.Error("Failed get rule link", "error", err)
  139. return err
  140. }
  141. fields := make([]map[string]interface{}, 0)
  142. fieldLimitCount := 4
  143. for index, evt := range evalContext.EvalMatches {
  144. fields = append(fields, map[string]interface{}{
  145. "title": evt.Metric,
  146. "value": evt.Value,
  147. "short": true,
  148. })
  149. if index > fieldLimitCount {
  150. break
  151. }
  152. }
  153. if evalContext.Error != nil {
  154. fields = append(fields, map[string]interface{}{
  155. "title": "Error message",
  156. "value": evalContext.Error.Error(),
  157. "short": false,
  158. })
  159. }
  160. message := this.Mention
  161. if evalContext.Rule.State != m.AlertStateOK { //don't add message when going back to alert state ok.
  162. message += " " + evalContext.Rule.Message
  163. }
  164. image_url := ""
  165. // default to file.upload API method if a token is provided
  166. if this.Token == "" {
  167. image_url = evalContext.ImagePublicUrl
  168. }
  169. body := map[string]interface{}{
  170. "attachments": []map[string]interface{}{
  171. {
  172. "fallback": evalContext.GetNotificationTitle(),
  173. "color": evalContext.GetStateModel().Color,
  174. "title": evalContext.GetNotificationTitle(),
  175. "title_link": ruleUrl,
  176. "text": message,
  177. "fields": fields,
  178. "image_url": image_url,
  179. "footer": "Grafana v" + setting.BuildVersion,
  180. "footer_icon": "https://grafana.com/assets/img/fav32.png",
  181. "ts": time.Now().Unix(),
  182. },
  183. },
  184. "parse": "full", // to linkify urls, users and channels in alert message.
  185. }
  186. //recipient override
  187. if this.Recipient != "" {
  188. body["channel"] = this.Recipient
  189. }
  190. if this.Username != "" {
  191. body["username"] = this.Username
  192. }
  193. if this.IconEmoji != "" {
  194. body["icon_emoji"] = this.IconEmoji
  195. }
  196. if this.IconUrl != "" {
  197. body["icon_url"] = this.IconUrl
  198. }
  199. data, _ := json.Marshal(&body)
  200. cmd := &m.SendWebhookSync{Url: this.Url, Body: string(data)}
  201. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  202. this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name)
  203. return err
  204. }
  205. if this.Token != "" && this.UploadImage {
  206. err = SlackFileUpload(evalContext, this.log, "https://slack.com/api/files.upload", this.Recipient, this.Token)
  207. if err != nil {
  208. return err
  209. }
  210. }
  211. return nil
  212. }
  213. func SlackFileUpload(evalContext *alerting.EvalContext, log log.Logger, url string, recipient string, token string) error {
  214. if evalContext.ImageOnDiskPath == "" {
  215. evalContext.ImageOnDiskPath = filepath.Join(setting.HomePath, "public/img/mixed_styles.png")
  216. }
  217. log.Info("Uploading to slack via file.upload API")
  218. headers, uploadBody, err := GenerateSlackBody(evalContext.ImageOnDiskPath, token, recipient)
  219. if err != nil {
  220. return err
  221. }
  222. cmd := &m.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"}
  223. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  224. log.Error("Failed to upload slack image", "error", err, "webhook", "file.upload")
  225. return err
  226. }
  227. if err != nil {
  228. return err
  229. }
  230. return nil
  231. }
  232. func GenerateSlackBody(file string, token string, recipient string) (map[string]string, bytes.Buffer, error) {
  233. // Slack requires all POSTs to files.upload to present
  234. // an "application/x-www-form-urlencoded" encoded querystring
  235. // See https://api.slack.com/methods/files.upload
  236. var b bytes.Buffer
  237. w := multipart.NewWriter(&b)
  238. // Add the generated image file
  239. f, err := os.Open(file)
  240. if err != nil {
  241. return nil, b, err
  242. }
  243. defer f.Close()
  244. fw, err := w.CreateFormFile("file", file)
  245. if err != nil {
  246. return nil, b, err
  247. }
  248. _, err = io.Copy(fw, f)
  249. if err != nil {
  250. return nil, b, err
  251. }
  252. // Add the authorization token
  253. err = w.WriteField("token", token)
  254. if err != nil {
  255. return nil, b, err
  256. }
  257. // Add the channel(s) to POST to
  258. err = w.WriteField("channels", recipient)
  259. if err != nil {
  260. return nil, b, err
  261. }
  262. w.Close()
  263. headers := map[string]string{
  264. "Content-Type": w.FormDataContentType(),
  265. "Authorization": "auth_token=\"" + token + "\"",
  266. }
  267. return headers, b, nil
  268. }