proxy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. Copyright 2014 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. // OWNER = sig/network
  14. package network
  15. import (
  16. "context"
  17. "fmt"
  18. "math"
  19. "net/http"
  20. "strings"
  21. "sync"
  22. "time"
  23. v1 "k8s.io/api/core/v1"
  24. apierrors "k8s.io/apimachinery/pkg/api/errors"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/util/intstr"
  27. "k8s.io/apimachinery/pkg/util/net"
  28. clientset "k8s.io/client-go/kubernetes"
  29. "k8s.io/kubernetes/test/e2e/framework"
  30. e2enode "k8s.io/kubernetes/test/e2e/framework/node"
  31. e2erc "k8s.io/kubernetes/test/e2e/framework/rc"
  32. testutils "k8s.io/kubernetes/test/utils"
  33. imageutils "k8s.io/kubernetes/test/utils/image"
  34. "github.com/onsi/ginkgo"
  35. "github.com/onsi/gomega"
  36. )
  37. const (
  38. // Try all the proxy tests this many times (to catch even rare flakes).
  39. proxyAttempts = 20
  40. // Only print this many characters of the response (to keep the logs
  41. // legible).
  42. maxDisplayBodyLen = 100
  43. // We have seen one of these calls take just over 15 seconds, so putting this at 30.
  44. proxyHTTPCallTimeout = 30 * time.Second
  45. )
  46. var _ = SIGDescribe("Proxy", func() {
  47. version := "v1"
  48. ginkgo.Context("version "+version, func() {
  49. options := framework.Options{
  50. ClientQPS: -1.0,
  51. }
  52. f := framework.NewFramework("proxy", options, nil)
  53. prefix := "/api/" + version
  54. /*
  55. Release : v1.9
  56. Testname: Proxy, logs port endpoint
  57. Description: Select any node in the cluster to invoke /proxy/nodes/<nodeip>:10250/logs endpoint. This endpoint MUST be reachable.
  58. */
  59. framework.ConformanceIt("should proxy logs on node with explicit kubelet port using proxy subresource ", func() { nodeProxyTest(f, prefix+"/nodes/", ":10250/proxy/logs/") })
  60. /*
  61. Release : v1.9
  62. Testname: Proxy, logs endpoint
  63. Description: Select any node in the cluster to invoke /proxy/nodes/<nodeip>//logs endpoint. This endpoint MUST be reachable.
  64. */
  65. framework.ConformanceIt("should proxy logs on node using proxy subresource ", func() { nodeProxyTest(f, prefix+"/nodes/", "/proxy/logs/") })
  66. // using the porter image to serve content, access the content
  67. // (of multiple pods?) from multiple (endpoints/services?)
  68. /*
  69. Release : v1.9
  70. Testname: Proxy, logs service endpoint
  71. Description: Select any node in the cluster to invoke /logs endpoint using the /nodes/proxy subresource from the kubelet port. This endpoint MUST be reachable.
  72. */
  73. framework.ConformanceIt("should proxy through a service and a pod ", func() {
  74. start := time.Now()
  75. labels := map[string]string{"proxy-service-target": "true"}
  76. service, err := f.ClientSet.CoreV1().Services(f.Namespace.Name).Create(context.TODO(), &v1.Service{
  77. ObjectMeta: metav1.ObjectMeta{
  78. GenerateName: "proxy-service-",
  79. },
  80. Spec: v1.ServiceSpec{
  81. Selector: labels,
  82. Ports: []v1.ServicePort{
  83. {
  84. Name: "portname1",
  85. Port: 80,
  86. TargetPort: intstr.FromString("dest1"),
  87. },
  88. {
  89. Name: "portname2",
  90. Port: 81,
  91. TargetPort: intstr.FromInt(162),
  92. },
  93. {
  94. Name: "tlsportname1",
  95. Port: 443,
  96. TargetPort: intstr.FromString("tlsdest1"),
  97. },
  98. {
  99. Name: "tlsportname2",
  100. Port: 444,
  101. TargetPort: intstr.FromInt(462),
  102. },
  103. },
  104. },
  105. }, metav1.CreateOptions{})
  106. framework.ExpectNoError(err)
  107. // Make an RC with a single pod. The 'porter' image is
  108. // a simple server which serves the values of the
  109. // environmental variables below.
  110. ginkgo.By("starting an echo server on multiple ports")
  111. pods := []*v1.Pod{}
  112. cfg := testutils.RCConfig{
  113. Client: f.ClientSet,
  114. Image: imageutils.GetE2EImage(imageutils.Agnhost),
  115. Command: []string{"/agnhost", "porter"},
  116. Name: service.Name,
  117. Namespace: f.Namespace.Name,
  118. Replicas: 1,
  119. PollInterval: time.Second,
  120. Env: map[string]string{
  121. "SERVE_PORT_80": `<a href="/rewriteme">test</a>`,
  122. "SERVE_PORT_1080": `<a href="/rewriteme">test</a>`,
  123. "SERVE_PORT_160": "foo",
  124. "SERVE_PORT_162": "bar",
  125. "SERVE_TLS_PORT_443": `<a href="/tlsrewriteme">test</a>`,
  126. "SERVE_TLS_PORT_460": `tls baz`,
  127. "SERVE_TLS_PORT_462": `tls qux`,
  128. },
  129. Ports: map[string]int{
  130. "dest1": 160,
  131. "dest2": 162,
  132. "tlsdest1": 460,
  133. "tlsdest2": 462,
  134. },
  135. ReadinessProbe: &v1.Probe{
  136. Handler: v1.Handler{
  137. HTTPGet: &v1.HTTPGetAction{
  138. Port: intstr.FromInt(80),
  139. },
  140. },
  141. InitialDelaySeconds: 1,
  142. TimeoutSeconds: 5,
  143. PeriodSeconds: 10,
  144. },
  145. Labels: labels,
  146. CreatedPods: &pods,
  147. }
  148. err = e2erc.RunRC(cfg)
  149. framework.ExpectNoError(err)
  150. defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, cfg.Name)
  151. err = waitForEndpoint(f.ClientSet, f.Namespace.Name, service.Name)
  152. framework.ExpectNoError(err)
  153. // table constructors
  154. // Try proxying through the service and directly to through the pod.
  155. subresourceServiceProxyURL := func(scheme, port string) string {
  156. return prefix + "/namespaces/" + f.Namespace.Name + "/services/" + net.JoinSchemeNamePort(scheme, service.Name, port) + "/proxy"
  157. }
  158. subresourcePodProxyURL := func(scheme, port string) string {
  159. return prefix + "/namespaces/" + f.Namespace.Name + "/pods/" + net.JoinSchemeNamePort(scheme, pods[0].Name, port) + "/proxy"
  160. }
  161. // construct the table
  162. expectations := map[string]string{
  163. subresourceServiceProxyURL("", "portname1") + "/": "foo",
  164. subresourceServiceProxyURL("http", "portname1") + "/": "foo",
  165. subresourceServiceProxyURL("", "portname2") + "/": "bar",
  166. subresourceServiceProxyURL("http", "portname2") + "/": "bar",
  167. subresourceServiceProxyURL("https", "tlsportname1") + "/": "tls baz",
  168. subresourceServiceProxyURL("https", "tlsportname2") + "/": "tls qux",
  169. subresourcePodProxyURL("", "") + "/": `<a href="` + subresourcePodProxyURL("", "") + `/rewriteme">test</a>`,
  170. subresourcePodProxyURL("", "1080") + "/": `<a href="` + subresourcePodProxyURL("", "1080") + `/rewriteme">test</a>`,
  171. subresourcePodProxyURL("http", "1080") + "/": `<a href="` + subresourcePodProxyURL("http", "1080") + `/rewriteme">test</a>`,
  172. subresourcePodProxyURL("", "160") + "/": "foo",
  173. subresourcePodProxyURL("http", "160") + "/": "foo",
  174. subresourcePodProxyURL("", "162") + "/": "bar",
  175. subresourcePodProxyURL("http", "162") + "/": "bar",
  176. subresourcePodProxyURL("https", "443") + "/": `<a href="` + subresourcePodProxyURL("https", "443") + `/tlsrewriteme">test</a>`,
  177. subresourcePodProxyURL("https", "460") + "/": "tls baz",
  178. subresourcePodProxyURL("https", "462") + "/": "tls qux",
  179. // TODO: below entries don't work, but I believe we should make them work.
  180. // podPrefix + ":dest1": "foo",
  181. // podPrefix + ":dest2": "bar",
  182. }
  183. wg := sync.WaitGroup{}
  184. errs := []string{}
  185. errLock := sync.Mutex{}
  186. recordError := func(s string) {
  187. errLock.Lock()
  188. defer errLock.Unlock()
  189. errs = append(errs, s)
  190. }
  191. d := time.Since(start)
  192. framework.Logf("setup took %v, starting test cases", d)
  193. numberTestCases := len(expectations)
  194. totalAttempts := numberTestCases * proxyAttempts
  195. ginkgo.By(fmt.Sprintf("running %v cases, %v attempts per case, %v total attempts", numberTestCases, proxyAttempts, totalAttempts))
  196. for i := 0; i < proxyAttempts; i++ {
  197. wg.Add(numberTestCases)
  198. for path, val := range expectations {
  199. go func(i int, path, val string) {
  200. defer wg.Done()
  201. // this runs the test case
  202. body, status, d, err := doProxy(f, path, i)
  203. if err != nil {
  204. if serr, ok := err.(*apierrors.StatusError); ok {
  205. recordError(fmt.Sprintf("%v (%v; %v): path %v gave status error: %+v",
  206. i, status, d, path, serr.Status()))
  207. } else {
  208. recordError(fmt.Sprintf("%v: path %v gave error: %v", i, path, err))
  209. }
  210. return
  211. }
  212. if status != http.StatusOK {
  213. recordError(fmt.Sprintf("%v: path %v gave status: %v", i, path, status))
  214. }
  215. if e, a := val, string(body); e != a {
  216. recordError(fmt.Sprintf("%v: path %v: wanted %v, got %v", i, path, e, a))
  217. }
  218. if d > proxyHTTPCallTimeout {
  219. recordError(fmt.Sprintf("%v: path %v took %v > %v", i, path, d, proxyHTTPCallTimeout))
  220. }
  221. }(i, path, val)
  222. }
  223. wg.Wait()
  224. }
  225. if len(errs) != 0 {
  226. body, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).GetLogs(pods[0].Name, &v1.PodLogOptions{}).Do(context.TODO()).Raw()
  227. if err != nil {
  228. framework.Logf("Error getting logs for pod %s: %v", pods[0].Name, err)
  229. } else {
  230. framework.Logf("Pod %s has the following error logs: %s", pods[0].Name, body)
  231. }
  232. framework.Failf(strings.Join(errs, "\n"))
  233. }
  234. })
  235. })
  236. })
  237. func doProxy(f *framework.Framework, path string, i int) (body []byte, statusCode int, d time.Duration, err error) {
  238. // About all of the proxy accesses in this file:
  239. // * AbsPath is used because it preserves the trailing '/'.
  240. // * Do().Raw() is used (instead of DoRaw()) because it will turn an
  241. // error from apiserver proxy into an actual error, and there is no
  242. // chance of the things we are talking to being confused for an error
  243. // that apiserver would have emitted.
  244. start := time.Now()
  245. body, err = f.ClientSet.CoreV1().RESTClient().Get().AbsPath(path).Do(context.TODO()).StatusCode(&statusCode).Raw()
  246. d = time.Since(start)
  247. if len(body) > 0 {
  248. framework.Logf("(%v) %v: %s (%v; %v)", i, path, truncate(body, maxDisplayBodyLen), statusCode, d)
  249. } else {
  250. framework.Logf("%v: %s (%v; %v)", path, "no body", statusCode, d)
  251. }
  252. return
  253. }
  254. func truncate(b []byte, maxLen int) []byte {
  255. if len(b) <= maxLen-3 {
  256. return b
  257. }
  258. b2 := append([]byte(nil), b[:maxLen-3]...)
  259. b2 = append(b2, '.', '.', '.')
  260. return b2
  261. }
  262. func nodeProxyTest(f *framework.Framework, prefix, nodeDest string) {
  263. // TODO: investigate why it doesn't work on master Node.
  264. node, err := e2enode.GetRandomReadySchedulableNode(f.ClientSet)
  265. framework.ExpectNoError(err)
  266. // TODO: Change it to test whether all requests succeeded when requests
  267. // not reaching Kubelet issue is debugged.
  268. serviceUnavailableErrors := 0
  269. for i := 0; i < proxyAttempts; i++ {
  270. _, status, d, err := doProxy(f, prefix+node.Name+nodeDest, i)
  271. if status == http.StatusServiceUnavailable {
  272. framework.Logf("ginkgo.Failed proxying node logs due to service unavailable: %v", err)
  273. time.Sleep(time.Second)
  274. serviceUnavailableErrors++
  275. } else {
  276. framework.ExpectNoError(err)
  277. framework.ExpectEqual(status, http.StatusOK)
  278. gomega.Expect(d).To(gomega.BeNumerically("<", proxyHTTPCallTimeout))
  279. }
  280. }
  281. if serviceUnavailableErrors > 0 {
  282. framework.Logf("error: %d requests to proxy node logs failed", serviceUnavailableErrors)
  283. }
  284. maxFailures := int(math.Floor(0.1 * float64(proxyAttempts)))
  285. gomega.Expect(serviceUnavailableErrors).To(gomega.BeNumerically("<", maxFailures))
  286. }
  287. // waitForEndpoint waits for the specified endpoint to be ready.
  288. func waitForEndpoint(c clientset.Interface, ns, name string) error {
  289. // registerTimeout is how long to wait for an endpoint to be registered.
  290. registerTimeout := time.Minute
  291. for t := time.Now(); time.Since(t) < registerTimeout; time.Sleep(framework.Poll) {
  292. endpoint, err := c.CoreV1().Endpoints(ns).Get(context.TODO(), name, metav1.GetOptions{})
  293. if apierrors.IsNotFound(err) {
  294. framework.Logf("Endpoint %s/%s is not ready yet", ns, name)
  295. continue
  296. }
  297. framework.ExpectNoError(err, "Failed to get endpoints for %s/%s", ns, name)
  298. if len(endpoint.Subsets) == 0 || len(endpoint.Subsets[0].Addresses) == 0 {
  299. framework.Logf("Endpoint %s/%s is not ready yet", ns, name)
  300. continue
  301. }
  302. return nil
  303. }
  304. return fmt.Errorf("failed to get endpoints for %s/%s", ns, name)
  305. }