slack.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. "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. // NewSlackNotifier is the constructor for the Slack notifier
  98. func NewSlackNotifier(model *models.AlertNotification) (alerting.Notifier, error) {
  99. url := model.Settings.Get("url").MustString()
  100. if url == "" {
  101. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  102. }
  103. recipient := model.Settings.Get("recipient").MustString()
  104. username := model.Settings.Get("username").MustString()
  105. iconEmoji := model.Settings.Get("icon_emoji").MustString()
  106. iconURL := model.Settings.Get("icon_url").MustString()
  107. mention := model.Settings.Get("mention").MustString()
  108. token := model.Settings.Get("token").MustString()
  109. uploadImage := model.Settings.Get("uploadImage").MustBool(true)
  110. return &SlackNotifier{
  111. NotifierBase: NewNotifierBase(model),
  112. URL: url,
  113. Recipient: recipient,
  114. Username: username,
  115. IconEmoji: iconEmoji,
  116. IconURL: iconURL,
  117. Mention: mention,
  118. Token: token,
  119. Upload: uploadImage,
  120. log: log.New("alerting.notifier.slack"),
  121. }, nil
  122. }
  123. // SlackNotifier is responsible for sending
  124. // alert notification to Slack.
  125. type SlackNotifier struct {
  126. NotifierBase
  127. URL string
  128. Recipient string
  129. Username string
  130. IconEmoji string
  131. IconURL string
  132. Mention string
  133. Token string
  134. Upload bool
  135. log log.Logger
  136. }
  137. // Notify send alert notification to Slack.
  138. func (sn *SlackNotifier) Notify(evalContext *alerting.EvalContext) error {
  139. sn.log.Info("Executing slack notification", "ruleId", evalContext.Rule.ID, "notification", sn.Name)
  140. ruleURL, err := evalContext.GetRuleURL()
  141. if err != nil {
  142. sn.log.Error("Failed get rule link", "error", err)
  143. return err
  144. }
  145. fields := make([]map[string]interface{}, 0)
  146. fieldLimitCount := 4
  147. for index, evt := range evalContext.EvalMatches {
  148. fields = append(fields, map[string]interface{}{
  149. "title": evt.Metric,
  150. "value": evt.Value,
  151. "short": true,
  152. })
  153. if index > fieldLimitCount {
  154. break
  155. }
  156. }
  157. if evalContext.Error != nil {
  158. fields = append(fields, map[string]interface{}{
  159. "title": "Error message",
  160. "value": evalContext.Error.Error(),
  161. "short": false,
  162. })
  163. }
  164. message := sn.Mention
  165. if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok.
  166. message += " " + evalContext.Rule.Message
  167. }
  168. imageURL := ""
  169. // default to file.upload API method if a token is provided
  170. if sn.Token == "" {
  171. imageURL = evalContext.ImagePublicURL
  172. }
  173. body := map[string]interface{}{
  174. "attachments": []map[string]interface{}{
  175. {
  176. "fallback": evalContext.GetNotificationTitle(),
  177. "color": evalContext.GetStateModel().Color,
  178. "title": evalContext.GetNotificationTitle(),
  179. "title_link": ruleURL,
  180. "text": message,
  181. "fields": fields,
  182. "image_url": imageURL,
  183. "footer": "Grafana v" + setting.BuildVersion,
  184. "footer_icon": "https://grafana.com/assets/img/fav32.png",
  185. "ts": time.Now().Unix(),
  186. },
  187. },
  188. "parse": "full", // to linkify urls, users and channels in alert message.
  189. }
  190. //recipient override
  191. if sn.Recipient != "" {
  192. body["channel"] = sn.Recipient
  193. }
  194. if sn.Username != "" {
  195. body["username"] = sn.Username
  196. }
  197. if sn.IconEmoji != "" {
  198. body["icon_emoji"] = sn.IconEmoji
  199. }
  200. if sn.IconURL != "" {
  201. body["icon_url"] = sn.IconURL
  202. }
  203. data, _ := json.Marshal(&body)
  204. cmd := &models.SendWebhookSync{Url: sn.URL, Body: string(data)}
  205. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  206. sn.log.Error("Failed to send slack notification", "error", err, "webhook", sn.Name)
  207. return err
  208. }
  209. if sn.Token != "" && sn.UploadImage {
  210. err = slackFileUpload(evalContext, sn.log, "https://slack.com/api/files.upload", sn.Recipient, sn.Token)
  211. if err != nil {
  212. return err
  213. }
  214. }
  215. return nil
  216. }
  217. func slackFileUpload(evalContext *alerting.EvalContext, log log.Logger, url string, recipient string, token string) error {
  218. if evalContext.ImageOnDiskPath == "" {
  219. evalContext.ImageOnDiskPath = filepath.Join(setting.HomePath, "public/img/mixed_styles.png")
  220. }
  221. log.Info("Uploading to slack via file.upload API")
  222. headers, uploadBody, err := generateSlackBody(evalContext.ImageOnDiskPath, token, recipient)
  223. if err != nil {
  224. return err
  225. }
  226. cmd := &models.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"}
  227. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  228. log.Error("Failed to upload slack image", "error", err, "webhook", "file.upload")
  229. return err
  230. }
  231. return nil
  232. }
  233. func generateSlackBody(file string, token string, recipient string) (map[string]string, bytes.Buffer, error) {
  234. // Slack requires all POSTs to files.upload to present
  235. // an "application/x-www-form-urlencoded" encoded querystring
  236. // See https://api.slack.com/methods/files.upload
  237. var b bytes.Buffer
  238. w := multipart.NewWriter(&b)
  239. // Add the generated image file
  240. f, err := os.Open(file)
  241. if err != nil {
  242. return nil, b, err
  243. }
  244. defer f.Close()
  245. fw, err := w.CreateFormFile("file", file)
  246. if err != nil {
  247. return nil, b, err
  248. }
  249. _, err = io.Copy(fw, f)
  250. if err != nil {
  251. return nil, b, err
  252. }
  253. // Add the authorization token
  254. err = w.WriteField("token", token)
  255. if err != nil {
  256. return nil, b, err
  257. }
  258. // Add the channel(s) to POST to
  259. err = w.WriteField("channels", recipient)
  260. if err != nil {
  261. return nil, b, err
  262. }
  263. w.Close()
  264. headers := map[string]string{
  265. "Content-Type": w.FormDataContentType(),
  266. "Authorization": "auth_token=\"" + token + "\"",
  267. }
  268. return headers, b, nil
  269. }