googlechat.go 4.8 KB

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