portforward.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. // OWNER = sig/cli
  14. package kubectl
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "os/exec"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. "syscall"
  26. "time"
  27. "golang.org/x/net/websocket"
  28. v1 "k8s.io/api/core/v1"
  29. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  30. "k8s.io/apimachinery/pkg/util/wait"
  31. "k8s.io/kubernetes/test/e2e/framework"
  32. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  33. testutils "k8s.io/kubernetes/test/utils"
  34. imageutils "k8s.io/kubernetes/test/utils/image"
  35. "github.com/onsi/ginkgo"
  36. "github.com/onsi/gomega"
  37. )
  38. const (
  39. podName = "pfpod"
  40. )
  41. const (
  42. podCheckInterval = 1 * time.Second
  43. postStartWaitTimeout = 2 * time.Minute
  44. )
  45. // TODO support other ports besides 80
  46. var (
  47. portForwardRegexp = regexp.MustCompile("Forwarding from (127.0.0.1|\\[::1\\]):([0-9]+) -> 80")
  48. )
  49. func pfPod(expectedClientData, chunks, chunkSize, chunkIntervalMillis string, bindAddress string) *v1.Pod {
  50. return &v1.Pod{
  51. ObjectMeta: metav1.ObjectMeta{
  52. Name: podName,
  53. Labels: map[string]string{"name": podName},
  54. },
  55. Spec: v1.PodSpec{
  56. Containers: []v1.Container{
  57. {
  58. Name: "readiness",
  59. Image: imageutils.GetE2EImage(imageutils.Netexec),
  60. ReadinessProbe: &v1.Probe{
  61. Handler: v1.Handler{
  62. Exec: &v1.ExecAction{
  63. Command: []string{
  64. "sh", "-c", "netstat -na | grep LISTEN | grep -v 8080 | grep 80",
  65. }},
  66. },
  67. InitialDelaySeconds: 5,
  68. TimeoutSeconds: 60,
  69. PeriodSeconds: 1,
  70. },
  71. },
  72. {
  73. Name: "portforwardtester",
  74. Image: imageutils.GetE2EImage(imageutils.PortForwardTester),
  75. Env: []v1.EnvVar{
  76. {
  77. Name: "BIND_PORT",
  78. Value: "80",
  79. },
  80. {
  81. Name: "EXPECTED_CLIENT_DATA",
  82. Value: expectedClientData,
  83. },
  84. {
  85. Name: "CHUNKS",
  86. Value: chunks,
  87. },
  88. {
  89. Name: "CHUNK_SIZE",
  90. Value: chunkSize,
  91. },
  92. {
  93. Name: "CHUNK_INTERVAL",
  94. Value: chunkIntervalMillis,
  95. },
  96. {
  97. Name: "BIND_ADDRESS",
  98. Value: bindAddress,
  99. },
  100. },
  101. },
  102. },
  103. RestartPolicy: v1.RestartPolicyNever,
  104. },
  105. }
  106. }
  107. // WaitForTerminatedContainer wait till a given container be terminated for a given pod.
  108. func WaitForTerminatedContainer(f *framework.Framework, pod *v1.Pod, containerName string) error {
  109. return framework.WaitForPodCondition(f.ClientSet, f.Namespace.Name, pod.Name, "container terminated", framework.PodStartTimeout, func(pod *v1.Pod) (bool, error) {
  110. if len(testutils.TerminatedContainers(pod)[containerName]) > 0 {
  111. return true, nil
  112. }
  113. return false, nil
  114. })
  115. }
  116. type portForwardCommand struct {
  117. cmd *exec.Cmd
  118. port int
  119. }
  120. // Stop attempts to gracefully stop `kubectl port-forward`, only killing it if necessary.
  121. // This helps avoid spdy goroutine leaks in the Kubelet.
  122. func (c *portForwardCommand) Stop() {
  123. // SIGINT signals that kubectl port-forward should gracefully terminate
  124. if err := c.cmd.Process.Signal(syscall.SIGINT); err != nil {
  125. e2elog.Logf("error sending SIGINT to kubectl port-forward: %v", err)
  126. }
  127. // try to wait for a clean exit
  128. done := make(chan error)
  129. go func() {
  130. done <- c.cmd.Wait()
  131. }()
  132. expired := time.NewTimer(wait.ForeverTestTimeout)
  133. defer expired.Stop()
  134. select {
  135. case err := <-done:
  136. if err == nil {
  137. // success
  138. return
  139. }
  140. e2elog.Logf("error waiting for kubectl port-forward to exit: %v", err)
  141. case <-expired.C:
  142. e2elog.Logf("timed out waiting for kubectl port-forward to exit")
  143. }
  144. e2elog.Logf("trying to forcibly kill kubectl port-forward")
  145. framework.TryKill(c.cmd)
  146. }
  147. // runPortForward runs port-forward, warning, this may need root functionality on some systems.
  148. func runPortForward(ns, podName string, port int) *portForwardCommand {
  149. cmd := framework.KubectlCmd("port-forward", fmt.Sprintf("--namespace=%v", ns), podName, fmt.Sprintf(":%d", port))
  150. // This is somewhat ugly but is the only way to retrieve the port that was picked
  151. // by the port-forward command. We don't want to hard code the port as we have no
  152. // way of guaranteeing we can pick one that isn't in use, particularly on Jenkins.
  153. e2elog.Logf("starting port-forward command and streaming output")
  154. portOutput, _, err := framework.StartCmdAndStreamOutput(cmd)
  155. if err != nil {
  156. framework.Failf("Failed to start port-forward command: %v", err)
  157. }
  158. buf := make([]byte, 128)
  159. var n int
  160. e2elog.Logf("reading from `kubectl port-forward` command's stdout")
  161. if n, err = portOutput.Read(buf); err != nil {
  162. framework.Failf("Failed to read from kubectl port-forward stdout: %v", err)
  163. }
  164. portForwardOutput := string(buf[:n])
  165. match := portForwardRegexp.FindStringSubmatch(portForwardOutput)
  166. if len(match) != 3 {
  167. framework.Failf("Failed to parse kubectl port-forward output: %s", portForwardOutput)
  168. }
  169. listenPort, err := strconv.Atoi(match[2])
  170. if err != nil {
  171. framework.Failf("Error converting %s to an int: %v", match[2], err)
  172. }
  173. return &portForwardCommand{
  174. cmd: cmd,
  175. port: listenPort,
  176. }
  177. }
  178. func doTestConnectSendDisconnect(bindAddress string, f *framework.Framework) {
  179. ginkgo.By("Creating the target pod")
  180. pod := pfPod("", "10", "10", "100", fmt.Sprintf("%s", bindAddress))
  181. if _, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod); err != nil {
  182. framework.Failf("Couldn't create pod: %v", err)
  183. }
  184. if err := f.WaitForPodReady(pod.Name); err != nil {
  185. framework.Failf("Pod did not start running: %v", err)
  186. }
  187. ginkgo.By("Running 'kubectl port-forward'")
  188. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  189. defer cmd.Stop()
  190. ginkgo.By("Dialing the local port")
  191. conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  192. if err != nil {
  193. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  194. }
  195. defer func() {
  196. ginkgo.By("Closing the connection to the local port")
  197. conn.Close()
  198. }()
  199. ginkgo.By("Reading data from the local port")
  200. fromServer, err := ioutil.ReadAll(conn)
  201. if err != nil {
  202. framework.Failf("Unexpected error reading data from the server: %v", err)
  203. }
  204. if e, a := strings.Repeat("x", 100), string(fromServer); e != a {
  205. framework.Failf("Expected %q from server, got %q", e, a)
  206. }
  207. ginkgo.By("Waiting for the target pod to stop running")
  208. if err := WaitForTerminatedContainer(f, pod, "portforwardtester"); err != nil {
  209. framework.Failf("Container did not terminate: %v", err)
  210. }
  211. ginkgo.By("Verifying logs")
  212. gomega.Eventually(func() (string, error) {
  213. return framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, "portforwardtester")
  214. }, postStartWaitTimeout, podCheckInterval).Should(gomega.SatisfyAll(
  215. gomega.ContainSubstring("Accepted client connection"),
  216. gomega.ContainSubstring("Done"),
  217. ))
  218. }
  219. func doTestMustConnectSendNothing(bindAddress string, f *framework.Framework) {
  220. ginkgo.By("Creating the target pod")
  221. pod := pfPod("abc", "1", "1", "1", fmt.Sprintf("%s", bindAddress))
  222. if _, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod); err != nil {
  223. framework.Failf("Couldn't create pod: %v", err)
  224. }
  225. if err := f.WaitForPodReady(pod.Name); err != nil {
  226. framework.Failf("Pod did not start running: %v", err)
  227. }
  228. ginkgo.By("Running 'kubectl port-forward'")
  229. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  230. defer cmd.Stop()
  231. ginkgo.By("Dialing the local port")
  232. conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  233. if err != nil {
  234. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  235. }
  236. ginkgo.By("Closing the connection to the local port")
  237. conn.Close()
  238. ginkgo.By("Waiting for the target pod to stop running")
  239. if err := WaitForTerminatedContainer(f, pod, "portforwardtester"); err != nil {
  240. framework.Failf("Container did not terminate: %v", err)
  241. }
  242. ginkgo.By("Verifying logs")
  243. gomega.Eventually(func() (string, error) {
  244. return framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, "portforwardtester")
  245. }, postStartWaitTimeout, podCheckInterval).Should(gomega.SatisfyAll(
  246. gomega.ContainSubstring("Accepted client connection"),
  247. gomega.ContainSubstring("Expected to read 3 bytes from client, but got 0 instead"),
  248. ))
  249. }
  250. func doTestMustConnectSendDisconnect(bindAddress string, f *framework.Framework) {
  251. ginkgo.By("Creating the target pod")
  252. pod := pfPod("abc", "10", "10", "100", fmt.Sprintf("%s", bindAddress))
  253. if _, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod); err != nil {
  254. framework.Failf("Couldn't create pod: %v", err)
  255. }
  256. if err := f.WaitForPodReady(pod.Name); err != nil {
  257. framework.Failf("Pod did not start running: %v", err)
  258. }
  259. ginkgo.By("Running 'kubectl port-forward'")
  260. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  261. defer cmd.Stop()
  262. ginkgo.By("Dialing the local port")
  263. addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  264. if err != nil {
  265. framework.Failf("Error resolving tcp addr: %v", err)
  266. }
  267. conn, err := net.DialTCP("tcp", nil, addr)
  268. if err != nil {
  269. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  270. }
  271. defer func() {
  272. ginkgo.By("Closing the connection to the local port")
  273. conn.Close()
  274. }()
  275. ginkgo.By("Sending the expected data to the local port")
  276. fmt.Fprint(conn, "abc")
  277. ginkgo.By("Closing the write half of the client's connection")
  278. conn.CloseWrite()
  279. ginkgo.By("Reading data from the local port")
  280. fromServer, err := ioutil.ReadAll(conn)
  281. if err != nil {
  282. framework.Failf("Unexpected error reading data from the server: %v", err)
  283. }
  284. if e, a := strings.Repeat("x", 100), string(fromServer); e != a {
  285. framework.Failf("Expected %q from server, got %q", e, a)
  286. }
  287. ginkgo.By("Waiting for the target pod to stop running")
  288. if err := WaitForTerminatedContainer(f, pod, "portforwardtester"); err != nil {
  289. framework.Failf("Container did not terminate: %v", err)
  290. }
  291. ginkgo.By("Verifying logs")
  292. gomega.Eventually(func() (string, error) {
  293. return framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, "portforwardtester")
  294. }, postStartWaitTimeout, podCheckInterval).Should(gomega.SatisfyAll(
  295. gomega.ContainSubstring("Accepted client connection"),
  296. gomega.ContainSubstring("Received expected client data"),
  297. gomega.ContainSubstring("Done"),
  298. ))
  299. }
  300. func doTestOverWebSockets(bindAddress string, f *framework.Framework) {
  301. config, err := framework.LoadConfig()
  302. framework.ExpectNoError(err, "unable to get base config")
  303. ginkgo.By("Creating the pod")
  304. pod := pfPod("def", "10", "10", "100", fmt.Sprintf("%s", bindAddress))
  305. if _, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod); err != nil {
  306. framework.Failf("Couldn't create pod: %v", err)
  307. }
  308. if err := f.WaitForPodReady(pod.Name); err != nil {
  309. framework.Failf("Pod did not start running: %v", err)
  310. }
  311. req := f.ClientSet.CoreV1().RESTClient().Get().
  312. Namespace(f.Namespace.Name).
  313. Resource("pods").
  314. Name(pod.Name).
  315. Suffix("portforward").
  316. Param("ports", "80")
  317. url := req.URL()
  318. ws, err := framework.OpenWebSocketForURL(url, config, []string{"v4.channel.k8s.io"})
  319. if err != nil {
  320. framework.Failf("Failed to open websocket to %s: %v", url.String(), err)
  321. }
  322. defer ws.Close()
  323. gomega.Eventually(func() error {
  324. channel, msg, err := wsRead(ws)
  325. if err != nil {
  326. return fmt.Errorf("Failed to read completely from websocket %s: %v", url.String(), err)
  327. }
  328. if channel != 0 {
  329. return fmt.Errorf("Got message from server that didn't start with channel 0 (data): %v", msg)
  330. }
  331. if p := binary.LittleEndian.Uint16(msg); p != 80 {
  332. return fmt.Errorf("Received the wrong port: %d", p)
  333. }
  334. return nil
  335. }, time.Minute, 10*time.Second).Should(gomega.BeNil())
  336. gomega.Eventually(func() error {
  337. channel, msg, err := wsRead(ws)
  338. if err != nil {
  339. return fmt.Errorf("Failed to read completely from websocket %s: %v", url.String(), err)
  340. }
  341. if channel != 1 {
  342. return fmt.Errorf("Got message from server that didn't start with channel 1 (error): %v", msg)
  343. }
  344. if p := binary.LittleEndian.Uint16(msg); p != 80 {
  345. return fmt.Errorf("Received the wrong port: %d", p)
  346. }
  347. return nil
  348. }, time.Minute, 10*time.Second).Should(gomega.BeNil())
  349. ginkgo.By("Sending the expected data to the local port")
  350. err = wsWrite(ws, 0, []byte("def"))
  351. if err != nil {
  352. framework.Failf("Failed to write to websocket %s: %v", url.String(), err)
  353. }
  354. ginkgo.By("Reading data from the local port")
  355. buf := bytes.Buffer{}
  356. expectedData := bytes.Repeat([]byte("x"), 100)
  357. gomega.Eventually(func() error {
  358. channel, msg, err := wsRead(ws)
  359. if err != nil {
  360. return fmt.Errorf("Failed to read completely from websocket %s: %v", url.String(), err)
  361. }
  362. if channel != 0 {
  363. return fmt.Errorf("Got message from server that didn't start with channel 0 (data): %v", msg)
  364. }
  365. buf.Write(msg)
  366. if bytes.Equal(expectedData, buf.Bytes()) {
  367. return fmt.Errorf("Expected %q from server, got %q", expectedData, buf.Bytes())
  368. }
  369. return nil
  370. }, time.Minute, 10*time.Second).Should(gomega.BeNil())
  371. ginkgo.By("Verifying logs")
  372. gomega.Eventually(func() (string, error) {
  373. return framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, "portforwardtester")
  374. }, postStartWaitTimeout, podCheckInterval).Should(gomega.SatisfyAll(
  375. gomega.ContainSubstring("Accepted client connection"),
  376. gomega.ContainSubstring("Received expected client data"),
  377. ))
  378. }
  379. var _ = SIGDescribe("Kubectl Port forwarding", func() {
  380. f := framework.NewDefaultFramework("port-forwarding")
  381. framework.KubeDescribe("With a server listening on 0.0.0.0", func() {
  382. framework.KubeDescribe("that expects a client request", func() {
  383. ginkgo.It("should support a client that connects, sends NO DATA, and disconnects", func() {
  384. doTestMustConnectSendNothing("0.0.0.0", f)
  385. })
  386. ginkgo.It("should support a client that connects, sends DATA, and disconnects", func() {
  387. doTestMustConnectSendDisconnect("0.0.0.0", f)
  388. })
  389. })
  390. framework.KubeDescribe("that expects NO client request", func() {
  391. ginkgo.It("should support a client that connects, sends DATA, and disconnects", func() {
  392. doTestConnectSendDisconnect("0.0.0.0", f)
  393. })
  394. })
  395. ginkgo.It("should support forwarding over websockets", func() {
  396. doTestOverWebSockets("0.0.0.0", f)
  397. })
  398. })
  399. // kubectl port-forward may need elevated privileges to do its job.
  400. framework.KubeDescribe("With a server listening on localhost", func() {
  401. framework.KubeDescribe("that expects a client request", func() {
  402. ginkgo.It("should support a client that connects, sends NO DATA, and disconnects", func() {
  403. doTestMustConnectSendNothing("localhost", f)
  404. })
  405. ginkgo.It("should support a client that connects, sends DATA, and disconnects", func() {
  406. doTestMustConnectSendDisconnect("localhost", f)
  407. })
  408. })
  409. framework.KubeDescribe("that expects NO client request", func() {
  410. ginkgo.It("should support a client that connects, sends DATA, and disconnects", func() {
  411. doTestConnectSendDisconnect("localhost", f)
  412. })
  413. })
  414. ginkgo.It("should support forwarding over websockets", func() {
  415. doTestOverWebSockets("localhost", f)
  416. })
  417. })
  418. })
  419. func wsRead(conn *websocket.Conn) (byte, []byte, error) {
  420. for {
  421. var data []byte
  422. err := websocket.Message.Receive(conn, &data)
  423. if err != nil {
  424. return 0, nil, err
  425. }
  426. if len(data) == 0 {
  427. continue
  428. }
  429. channel := data[0]
  430. data = data[1:]
  431. return channel, data, err
  432. }
  433. }
  434. func wsWrite(conn *websocket.Conn, channel byte, data []byte) error {
  435. frame := make([]byte, len(data)+1)
  436. frame[0] = channel
  437. copy(frame[1:], data)
  438. err := websocket.Message.Send(conn, frame)
  439. return err
  440. }