http.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package http
  14. import (
  15. "crypto/tls"
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "net/url"
  20. "time"
  21. utilnet "k8s.io/apimachinery/pkg/util/net"
  22. "k8s.io/component-base/version"
  23. "k8s.io/kubernetes/pkg/probe"
  24. "k8s.io/klog"
  25. utilio "k8s.io/utils/io"
  26. )
  27. const (
  28. maxRespBodyLength = 10 * 1 << 10 // 10KB
  29. )
  30. // New creates Prober that will skip TLS verification while probing.
  31. // followNonLocalRedirects configures whether the prober should follow redirects to a different hostname.
  32. // If disabled, redirects to other hosts will trigger a warning result.
  33. func New(followNonLocalRedirects bool) Prober {
  34. tlsConfig := &tls.Config{InsecureSkipVerify: true}
  35. return NewWithTLSConfig(tlsConfig, followNonLocalRedirects)
  36. }
  37. // NewWithTLSConfig takes tls config as parameter.
  38. // followNonLocalRedirects configures whether the prober should follow redirects to a different hostname.
  39. // If disabled, redirects to other hosts will trigger a warning result.
  40. func NewWithTLSConfig(config *tls.Config, followNonLocalRedirects bool) Prober {
  41. // We do not want the probe use node's local proxy set.
  42. transport := utilnet.SetTransportDefaults(
  43. &http.Transport{
  44. TLSClientConfig: config,
  45. DisableKeepAlives: true,
  46. Proxy: http.ProxyURL(nil),
  47. })
  48. return httpProber{transport, followNonLocalRedirects}
  49. }
  50. // Prober is an interface that defines the Probe function for doing HTTP readiness/liveness checks.
  51. type Prober interface {
  52. Probe(url *url.URL, headers http.Header, timeout time.Duration) (probe.Result, string, error)
  53. }
  54. type httpProber struct {
  55. transport *http.Transport
  56. followNonLocalRedirects bool
  57. }
  58. // Probe returns a ProbeRunner capable of running an HTTP check.
  59. func (pr httpProber) Probe(url *url.URL, headers http.Header, timeout time.Duration) (probe.Result, string, error) {
  60. client := &http.Client{
  61. Timeout: timeout,
  62. Transport: pr.transport,
  63. CheckRedirect: redirectChecker(pr.followNonLocalRedirects),
  64. }
  65. return DoHTTPProbe(url, headers, client)
  66. }
  67. // GetHTTPInterface is an interface for making HTTP requests, that returns a response and error.
  68. type GetHTTPInterface interface {
  69. Do(req *http.Request) (*http.Response, error)
  70. }
  71. // DoHTTPProbe checks if a GET request to the url succeeds.
  72. // If the HTTP response code is successful (i.e. 400 > code >= 200), it returns Success.
  73. // If the HTTP response code is unsuccessful or HTTP communication fails, it returns Failure.
  74. // This is exported because some other packages may want to do direct HTTP probes.
  75. func DoHTTPProbe(url *url.URL, headers http.Header, client GetHTTPInterface) (probe.Result, string, error) {
  76. req, err := http.NewRequest("GET", url.String(), nil)
  77. if err != nil {
  78. // Convert errors into failures to catch timeouts.
  79. return probe.Failure, err.Error(), nil
  80. }
  81. if _, ok := headers["User-Agent"]; !ok {
  82. if headers == nil {
  83. headers = http.Header{}
  84. }
  85. // explicitly set User-Agent so it's not set to default Go value
  86. v := version.Get()
  87. headers.Set("User-Agent", fmt.Sprintf("kube-probe/%s.%s", v.Major, v.Minor))
  88. }
  89. req.Header = headers
  90. if headers.Get("Host") != "" {
  91. req.Host = headers.Get("Host")
  92. }
  93. res, err := client.Do(req)
  94. if err != nil {
  95. // Convert errors into failures to catch timeouts.
  96. return probe.Failure, err.Error(), nil
  97. }
  98. defer res.Body.Close()
  99. b, err := utilio.ReadAtMost(res.Body, maxRespBodyLength)
  100. if err != nil {
  101. if err == utilio.ErrLimitReached {
  102. klog.V(4).Infof("Non fatal body truncation for %s, Response: %v", url.String(), *res)
  103. } else {
  104. return probe.Failure, "", err
  105. }
  106. }
  107. body := string(b)
  108. if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest {
  109. if res.StatusCode >= http.StatusMultipleChoices { // Redirect
  110. klog.V(4).Infof("Probe terminated redirects for %s, Response: %v", url.String(), *res)
  111. return probe.Warning, body, nil
  112. }
  113. klog.V(4).Infof("Probe succeeded for %s, Response: %v", url.String(), *res)
  114. return probe.Success, body, nil
  115. }
  116. klog.V(4).Infof("Probe failed for %s with request headers %v, response body: %v", url.String(), headers, body)
  117. return probe.Failure, fmt.Sprintf("HTTP probe failed with statuscode: %d", res.StatusCode), nil
  118. }
  119. func redirectChecker(followNonLocalRedirects bool) func(*http.Request, []*http.Request) error {
  120. if followNonLocalRedirects {
  121. return nil // Use the default http client checker.
  122. }
  123. return func(req *http.Request, via []*http.Request) error {
  124. if req.URL.Hostname() != via[0].URL.Hostname() {
  125. return http.ErrUseLastResponse
  126. }
  127. // Default behavior: stop after 10 redirects.
  128. if len(via) >= 10 {
  129. return errors.New("stopped after 10 redirects")
  130. }
  131. return nil
  132. }
  133. }