webhook.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package notifications
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "time"
  10. "golang.org/x/net/context/ctxhttp"
  11. "github.com/grafana/grafana/pkg/log"
  12. "github.com/grafana/grafana/pkg/util"
  13. )
  14. type Webhook struct {
  15. Url string
  16. User string
  17. Password string
  18. Body string
  19. HttpMethod string
  20. HttpHeader map[string]string
  21. }
  22. var netTransport = &http.Transport{
  23. Proxy: http.ProxyFromEnvironment,
  24. Dial: (&net.Dialer{
  25. Timeout: 30 * time.Second,
  26. }).Dial,
  27. TLSHandshakeTimeout: 5 * time.Second,
  28. }
  29. var netClient = &http.Client{
  30. Timeout: time.Second * 30,
  31. Transport: netTransport,
  32. }
  33. var (
  34. webhookQueue chan *Webhook
  35. webhookLog log.Logger
  36. )
  37. func initWebhookQueue() {
  38. webhookLog = log.New("notifications.webhook")
  39. webhookQueue = make(chan *Webhook, 10)
  40. go processWebhookQueue()
  41. }
  42. func processWebhookQueue() {
  43. for {
  44. select {
  45. case webhook := <-webhookQueue:
  46. err := sendWebRequestSync(context.Background(), webhook)
  47. if err != nil {
  48. webhookLog.Error("Failed to send webrequest ", "error", err)
  49. }
  50. }
  51. }
  52. }
  53. func sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
  54. webhookLog.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
  55. if webhook.HttpMethod == "" {
  56. webhook.HttpMethod = http.MethodPost
  57. }
  58. request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  59. if err != nil {
  60. return err
  61. }
  62. request.Header.Add("Content-Type", "application/json")
  63. request.Header.Add("User-Agent", "Grafana")
  64. if webhook.User != "" && webhook.Password != "" {
  65. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  66. }
  67. for k, v := range webhook.HttpHeader {
  68. request.Header.Set(k, v)
  69. }
  70. resp, err := ctxhttp.Do(ctx, netClient, request)
  71. if err != nil {
  72. return err
  73. }
  74. if resp.StatusCode/100 == 2 {
  75. return nil
  76. }
  77. defer resp.Body.Close()
  78. body, err := ioutil.ReadAll(resp.Body)
  79. if err != nil {
  80. return err
  81. }
  82. webhookLog.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
  83. return fmt.Errorf("Webhook response status %v", resp.Status)
  84. }
  85. var addToWebhookQueue = func(msg *Webhook) {
  86. webhookQueue <- msg
  87. }