util.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package notifiers
  15. import (
  16. "bytes"
  17. "context"
  18. "crypto/tls"
  19. "encoding/base64"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "net"
  24. "net/http"
  25. "strings"
  26. "time"
  27. "golang.org/x/net/context/ctxhttp"
  28. "moul.io/http2curl/v2"
  29. "yunion.io/x/log"
  30. "yunion.io/x/onecloud/pkg/apis/monitor"
  31. )
  32. // GetBasicAuthHeader returns a base64 encoded string from user and password.
  33. func GetBasicAuthHeader(user string, password string) string {
  34. var userAndPass = user + ":" + password
  35. return "Basic " + base64.StdEncoding.EncodeToString([]byte(userAndPass))
  36. }
  37. // DecodeBasicAuthHeader decodes user and password from a basic auth header.
  38. func DecodeBasicAuthHeader(header string) (string, string, error) {
  39. var code string
  40. parts := strings.SplitN(header, " ", 2)
  41. if len(parts) == 2 && parts[0] == "Basic" {
  42. code = parts[1]
  43. }
  44. decoded, err := base64.StdEncoding.DecodeString(code)
  45. if err != nil {
  46. return "", "", err
  47. }
  48. userAndPass := strings.SplitN(string(decoded), ":", 2)
  49. if len(userAndPass) != 2 {
  50. return "", "", fmt.Errorf("Invalid basic auth header")
  51. }
  52. return userAndPass[0], userAndPass[1], nil
  53. }
  54. // TODO: use httputils.HttpTransport instead -- qj
  55. // TODO:
  56. var netTransport = &http.Transport{
  57. TLSClientConfig: &tls.Config{
  58. Renegotiation: tls.RenegotiateFreelyAsClient,
  59. },
  60. Proxy: http.ProxyFromEnvironment,
  61. DialContext: (&net.Dialer{
  62. Timeout: 30 * time.Second,
  63. }).DialContext,
  64. TLSHandshakeTimeout: 5 * time.Second,
  65. }
  66. var netClient = &http.Client{
  67. Timeout: time.Second * 30,
  68. Transport: netTransport,
  69. }
  70. func SendWebRequestSync(ctx context.Context, webhook *monitor.SendWebhookSync) error {
  71. if webhook.HttpMethod == "" {
  72. webhook.HttpMethod = http.MethodPost
  73. }
  74. request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  75. if err != nil {
  76. return err
  77. }
  78. if webhook.ContentType == "" {
  79. webhook.ContentType = "application/json"
  80. }
  81. request.Header.Add("Content-Type", webhook.ContentType)
  82. request.Header.Add("User-Agent", "OneCloud Monitor")
  83. if webhook.User != "" && webhook.Password != "" {
  84. request.Header.Add("Authorization", GetBasicAuthHeader(webhook.User, webhook.Password))
  85. }
  86. for k, v := range webhook.HttpHeader {
  87. request.Header.Set(k, v)
  88. }
  89. curlCmd, _ := http2curl.GetCurlCommand(request)
  90. log.Debugf("webhook curl: %s", curlCmd)
  91. resp, err := ctxhttp.Do(ctx, netClient, request)
  92. if err != nil {
  93. return err
  94. }
  95. defer resp.Body.Close()
  96. if resp.StatusCode/100 == 2 {
  97. // flushing the body enables the transport to reuse the same connection
  98. if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
  99. log.Errorf("Failed to copy resp.Body to ioutil.Discard: %v", err)
  100. }
  101. return nil
  102. }
  103. body, err := ioutil.ReadAll(resp.Body)
  104. if err != nil {
  105. return err
  106. }
  107. log.Errorf("Webhook failed statuscode: %s, body: %s", resp.Status, string(body))
  108. return fmt.Errorf("Webhook response status %v", resp.Status)
  109. }