webhook.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. DualStack: true,
  27. }).Dial,
  28. TLSHandshakeTimeout: 5 * time.Second,
  29. }
  30. var netClient = &http.Client{
  31. Timeout: time.Second * 30,
  32. Transport: netTransport,
  33. }
  34. var (
  35. webhookQueue chan *Webhook
  36. webhookLog log.Logger
  37. )
  38. func initWebhookQueue() {
  39. webhookLog = log.New("notifications.webhook")
  40. webhookQueue = make(chan *Webhook, 10)
  41. go processWebhookQueue()
  42. }
  43. func processWebhookQueue() {
  44. for {
  45. select {
  46. case webhook := <-webhookQueue:
  47. err := sendWebRequestSync(context.Background(), webhook)
  48. if err != nil {
  49. webhookLog.Error("Failed to send webrequest ", "error", err)
  50. }
  51. }
  52. }
  53. }
  54. func sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
  55. webhookLog.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
  56. if webhook.HttpMethod == "" {
  57. webhook.HttpMethod = http.MethodPost
  58. }
  59. request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  60. if err != nil {
  61. return err
  62. }
  63. request.Header.Add("Content-Type", "application/json")
  64. request.Header.Add("User-Agent", "Grafana")
  65. if webhook.User != "" && webhook.Password != "" {
  66. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  67. }
  68. for k, v := range webhook.HttpHeader {
  69. request.Header.Set(k, v)
  70. }
  71. resp, err := ctxhttp.Do(ctx, netClient, request)
  72. if err != nil {
  73. return err
  74. }
  75. if resp.StatusCode/100 == 2 {
  76. return nil
  77. }
  78. defer resp.Body.Close()
  79. body, err := ioutil.ReadAll(resp.Body)
  80. if err != nil {
  81. return err
  82. }
  83. webhookLog.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
  84. return fmt.Errorf("Webhook response status %v", resp.Status)
  85. }