webhook.go 1.8 KB

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