googlechat.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package notifiers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/infra/log"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/services/alerting"
  10. "github.com/grafana/grafana/pkg/setting"
  11. )
  12. func init() {
  13. alerting.RegisterNotifier(&alerting.NotifierPlugin{
  14. Type: "googlechat",
  15. Name: "Google Hangouts Chat",
  16. Description: "Sends notifications to Google Hangouts Chat via webhooks based on the official JSON message " +
  17. "format (https://developers.google.com/hangouts/chat/reference/message-formats/).",
  18. Factory: NewGoogleChatNotifier,
  19. OptionsTemplate: `
  20. <h3 class="page-heading">Google Hangouts Chat settings</h3>
  21. <div class="gf-form max-width-30">
  22. <span class="gf-form-label width-6">Url</span>
  23. <input type="text" required class="gf-form-input max-width-30" ng-model="ctrl.model.settings.url" placeholder="Google Hangouts Chat incoming webhook url"></input>
  24. </div>
  25. `,
  26. })
  27. }
  28. func NewGoogleChatNotifier(model *m.AlertNotification) (alerting.Notifier, error) {
  29. url := model.Settings.Get("url").MustString()
  30. if url == "" {
  31. return nil, alerting.ValidationError{Reason: "Could not find url property in settings"}
  32. }
  33. return &GoogleChatNotifier{
  34. NotifierBase: NewNotifierBase(model),
  35. Url: url,
  36. log: log.New("alerting.notifier.googlechat"),
  37. }, nil
  38. }
  39. type GoogleChatNotifier struct {
  40. NotifierBase
  41. Url string
  42. log log.Logger
  43. }
  44. /**
  45. Structs used to build a custom Google Hangouts Chat message card.
  46. See: https://developers.google.com/hangouts/chat/reference/message-formats/cards
  47. */
  48. type outerStruct struct {
  49. Cards []card `json:"cards"`
  50. }
  51. type card struct {
  52. Header header `json:"header"`
  53. Sections []section `json:"sections"`
  54. }
  55. type header struct {
  56. Title string `json:"title"`
  57. }
  58. type section struct {
  59. Widgets []widget `json:"widgets"`
  60. }
  61. // "generic" widget used to add different types of widgets (buttonWidget, textParagraphWidget, imageWidget)
  62. type widget interface {
  63. }
  64. type buttonWidget struct {
  65. Buttons []button `json:"buttons"`
  66. }
  67. type textParagraphWidget struct {
  68. Text text `json:"textParagraph"`
  69. }
  70. type text struct {
  71. Text string `json:"text"`
  72. }
  73. type imageWidget struct {
  74. Image image `json:"image"`
  75. }
  76. type image struct {
  77. ImageUrl string `json:"imageUrl"`
  78. }
  79. type button struct {
  80. TextButton textButton `json:"textButton"`
  81. }
  82. type textButton struct {
  83. Text string `json:"text"`
  84. OnClick onClick `json:"onClick"`
  85. }
  86. type onClick struct {
  87. OpenLink openLink `json:"openLink"`
  88. }
  89. type openLink struct {
  90. Url string `json:"url"`
  91. }
  92. func (this *GoogleChatNotifier) Notify(evalContext *alerting.EvalContext) error {
  93. this.log.Info("Executing Google Chat notification")
  94. headers := map[string]string{
  95. "Content-Type": "application/json; charset=UTF-8",
  96. }
  97. ruleUrl, err := evalContext.GetRuleUrl()
  98. if err != nil {
  99. this.log.Error("evalContext returned an invalid rule URL")
  100. }
  101. // add a text paragraph widget for the message
  102. widgets := []widget{
  103. textParagraphWidget{
  104. Text: text{
  105. Text: evalContext.Rule.Message,
  106. },
  107. },
  108. }
  109. // add a text paragraph widget for the fields
  110. var fields []textParagraphWidget
  111. fieldLimitCount := 4
  112. for index, evt := range evalContext.EvalMatches {
  113. fields = append(fields,
  114. textParagraphWidget{
  115. Text: text{
  116. Text: "<i>" + evt.Metric + ": " + fmt.Sprint(evt.Value) + "</i>",
  117. },
  118. },
  119. )
  120. if index > fieldLimitCount {
  121. break
  122. }
  123. }
  124. widgets = append(widgets, fields)
  125. // if an image exists, add it as an image widget
  126. if evalContext.ImagePublicUrl != "" {
  127. widgets = append(widgets, imageWidget{
  128. Image: image{
  129. ImageUrl: evalContext.ImagePublicUrl,
  130. },
  131. })
  132. } else {
  133. this.log.Info("Could not retrieve a public image URL.")
  134. }
  135. // add a button widget (link to Grafana)
  136. widgets = append(widgets, buttonWidget{
  137. Buttons: []button{
  138. {
  139. TextButton: textButton{
  140. Text: "OPEN IN GRAFANA",
  141. OnClick: onClick{
  142. OpenLink: openLink{
  143. Url: ruleUrl,
  144. },
  145. },
  146. },
  147. },
  148. },
  149. })
  150. // add text paragraph widget for the build version and timestamp
  151. widgets = append(widgets, textParagraphWidget{
  152. Text: text{
  153. Text: "Grafana v" + setting.BuildVersion + " | " + (time.Now()).Format(time.RFC822),
  154. },
  155. })
  156. // nest the required structs
  157. res1D := &outerStruct{
  158. Cards: []card{
  159. {
  160. Header: header{
  161. Title: evalContext.GetNotificationTitle(),
  162. },
  163. Sections: []section{
  164. {
  165. Widgets: widgets,
  166. },
  167. },
  168. },
  169. },
  170. }
  171. body, _ := json.Marshal(res1D)
  172. cmd := &m.SendWebhookSync{
  173. Url: this.Url,
  174. HttpMethod: "POST",
  175. HttpHeader: headers,
  176. Body: string(body),
  177. }
  178. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  179. this.log.Error("Failed to send Google Hangouts Chat alert", "error", err, "webhook", this.Name)
  180. return err
  181. }
  182. return nil
  183. }