proxy.go 11 KB

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