webhook.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  19. var webhookQueue chan *Webhook
  20. var webhookLog log.Logger
  21. func initWebhookQueue() {
  22. webhookLog = log.New("notifications.webhook")
  23. webhookQueue = make(chan *Webhook, 10)
  24. go processWebhookQueue()
  25. }
  26. func processWebhookQueue() {
  27. for {
  28. select {
  29. case webhook := <-webhookQueue:
  30. err := sendWebRequestSync(context.TODO(), webhook)
  31. if err != nil {
  32. webhookLog.Error("Failed to send webrequest ", "error", err)
  33. }
  34. }
  35. }
  36. }
  37. func sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
  38. webhookLog.Debug("Sending webhook", "url", webhook.Url)
  39. client := &http.Client{
  40. Timeout: time.Duration(10 * time.Second),
  41. }
  42. request, err := http.NewRequest(http.MethodPost, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  43. if webhook.User != "" && webhook.Password != "" {
  44. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  45. }
  46. if err != nil {
  47. return err
  48. }
  49. resp, err := ctxhttp.Do(ctx, client, request)
  50. if err != nil {
  51. return err
  52. }
  53. if resp.StatusCode/100 == 2 {
  54. return nil
  55. }
  56. body, err := ioutil.ReadAll(resp.Body)
  57. if err != nil {
  58. return err
  59. }
  60. defer resp.Body.Close()
  61. webhookLog.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
  62. return fmt.Errorf("Webhook response status %v", resp.Status)
  63. }
  64. var addToWebhookQueue = func(msg *Webhook) {
  65. webhookQueue <- msg
  66. }