slack.go 6.9 KB

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