http.go 4.9 KB

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