googlechat.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "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 *models.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. // GoogleChatNotifier is responsible for sending
  40. // alert notifications to Google chat.
  41. type GoogleChatNotifier struct {
  42. NotifierBase
  43. URL string
  44. log log.Logger
  45. }
  46. /**
  47. Structs used to build a custom Google Hangouts Chat message card.
  48. See: https://developers.google.com/hangouts/chat/reference/message-formats/cards
  49. */
  50. type outerStruct struct {
  51. Cards []card `json:"cards"`
  52. }
  53. type card struct {
  54. Header header `json:"header"`
  55. Sections []section `json:"sections"`
  56. }
  57. type header struct {
  58. Title string `json:"title"`
  59. }
  60. type section struct {
  61. Widgets []widget `json:"widgets"`
  62. }
  63. // "generic" widget used to add different types of widgets (buttonWidget, textParagraphWidget, imageWidget)
  64. type widget interface {
  65. }
  66. type buttonWidget struct {
  67. Buttons []button `json:"buttons"`
  68. }
  69. type textParagraphWidget struct {
  70. Text text `json:"textParagraph"`
  71. }
  72. type text struct {
  73. Text string `json:"text"`
  74. }
  75. type imageWidget struct {
  76. Image image `json:"image"`
  77. }
  78. type image struct {
  79. ImageURL string `json:"imageUrl"`
  80. }
  81. type button struct {
  82. TextButton textButton `json:"textButton"`
  83. }
  84. type textButton struct {
  85. Text string `json:"text"`
  86. OnClick onClick `json:"onClick"`
  87. }
  88. type onClick struct {
  89. OpenLink openLink `json:"openLink"`
  90. }
  91. type openLink struct {
  92. URL string `json:"url"`
  93. }
  94. // Notify send an alert notification to Google Chat.
  95. func (gcn *GoogleChatNotifier) Notify(evalContext *alerting.EvalContext) error {
  96. gcn.log.Info("Executing Google Chat notification")
  97. headers := map[string]string{
  98. "Content-Type": "application/json; charset=UTF-8",
  99. }
  100. ruleURL, err := evalContext.GetRuleURL()
  101. if err != nil {
  102. gcn.log.Error("evalContext returned an invalid rule URL")
  103. }
  104. // add a text paragraph widget for the message
  105. widgets := []widget{
  106. textParagraphWidget{
  107. Text: text{
  108. Text: evalContext.Rule.Message,
  109. },
  110. },
  111. }
  112. // add a text paragraph widget for the fields
  113. var fields []textParagraphWidget
  114. fieldLimitCount := 4
  115. for index, evt := range evalContext.EvalMatches {
  116. fields = append(fields,
  117. textParagraphWidget{
  118. Text: text{
  119. Text: "<i>" + evt.Metric + ": " + fmt.Sprint(evt.Value) + "</i>",
  120. },
  121. },
  122. )
  123. if index > fieldLimitCount {
  124. break
  125. }
  126. }
  127. widgets = append(widgets, fields)
  128. // if an image exists, add it as an image widget
  129. if evalContext.ImagePublicURL != "" {
  130. widgets = append(widgets, imageWidget{
  131. Image: image{
  132. ImageURL: evalContext.ImagePublicURL,
  133. },
  134. })
  135. } else {
  136. gcn.log.Info("Could not retrieve a public image URL.")
  137. }
  138. // add a button widget (link to Grafana)
  139. widgets = append(widgets, buttonWidget{
  140. Buttons: []button{
  141. {
  142. TextButton: textButton{
  143. Text: "OPEN IN GRAFANA",
  144. OnClick: onClick{
  145. OpenLink: openLink{
  146. URL: ruleURL,
  147. },
  148. },
  149. },
  150. },
  151. },
  152. })
  153. // add text paragraph widget for the build version and timestamp
  154. widgets = append(widgets, textParagraphWidget{
  155. Text: text{
  156. Text: "Grafana v" + setting.BuildVersion + " | " + (time.Now()).Format(time.RFC822),
  157. },
  158. })
  159. // nest the required structs
  160. res1D := &outerStruct{
  161. Cards: []card{
  162. {
  163. Header: header{
  164. Title: evalContext.GetNotificationTitle(),
  165. },
  166. Sections: []section{
  167. {
  168. Widgets: widgets,
  169. },
  170. },
  171. },
  172. },
  173. }
  174. body, _ := json.Marshal(res1D)
  175. cmd := &models.SendWebhookSync{
  176. Url: gcn.URL,
  177. HttpMethod: "POST",
  178. HttpHeader: headers,
  179. Body: string(body),
  180. }
  181. if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
  182. gcn.log.Error("Failed to send Google Hangouts Chat alert", "error", err, "webhook", gcn.Name)
  183. return err
  184. }
  185. return nil
  186. }