proxy.go 12 KB

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