portforward.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 e2e
  14. import (
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "net"
  19. "os/exec"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "syscall"
  24. "time"
  25. "k8s.io/kubernetes/pkg/api"
  26. "k8s.io/kubernetes/pkg/util/wait"
  27. "k8s.io/kubernetes/pkg/version"
  28. "k8s.io/kubernetes/test/e2e/framework"
  29. . "github.com/onsi/ginkgo"
  30. )
  31. const (
  32. podName = "pfpod"
  33. )
  34. // TODO support other ports besides 80
  35. var (
  36. portForwardRegexp = regexp.MustCompile("Forwarding from 127.0.0.1:([0-9]+) -> 80")
  37. portForwardPortToStdOutV = version.MustParse("v1.3.0-alpha.4")
  38. )
  39. func pfPod(expectedClientData, chunks, chunkSize, chunkIntervalMillis string) *api.Pod {
  40. return &api.Pod{
  41. ObjectMeta: api.ObjectMeta{
  42. Name: podName,
  43. Labels: map[string]string{"name": podName},
  44. },
  45. Spec: api.PodSpec{
  46. Containers: []api.Container{
  47. {
  48. Name: "portforwardtester",
  49. Image: "gcr.io/google_containers/portforwardtester:1.0",
  50. Env: []api.EnvVar{
  51. {
  52. Name: "BIND_PORT",
  53. Value: "80",
  54. },
  55. {
  56. Name: "EXPECTED_CLIENT_DATA",
  57. Value: expectedClientData,
  58. },
  59. {
  60. Name: "CHUNKS",
  61. Value: chunks,
  62. },
  63. {
  64. Name: "CHUNK_SIZE",
  65. Value: chunkSize,
  66. },
  67. {
  68. Name: "CHUNK_INTERVAL",
  69. Value: chunkIntervalMillis,
  70. },
  71. },
  72. },
  73. },
  74. RestartPolicy: api.RestartPolicyNever,
  75. },
  76. }
  77. }
  78. type portForwardCommand struct {
  79. cmd *exec.Cmd
  80. port int
  81. }
  82. // Stop attempts to gracefully stop `kubectl port-forward`, only killing it if necessary.
  83. // This helps avoid spdy goroutine leaks in the Kubelet.
  84. func (c *portForwardCommand) Stop() {
  85. // SIGINT signals that kubectl port-forward should gracefully terminate
  86. if err := c.cmd.Process.Signal(syscall.SIGINT); err != nil {
  87. framework.Logf("error sending SIGINT to kubectl port-forward: %v", err)
  88. }
  89. // try to wait for a clean exit
  90. done := make(chan error)
  91. go func() {
  92. done <- c.cmd.Wait()
  93. }()
  94. expired := time.NewTimer(wait.ForeverTestTimeout)
  95. defer expired.Stop()
  96. select {
  97. case err := <-done:
  98. if err == nil {
  99. // success
  100. return
  101. }
  102. framework.Logf("error waiting for kubectl port-forward to exit: %v", err)
  103. case <-expired.C:
  104. framework.Logf("timed out waiting for kubectl port-forward to exit")
  105. }
  106. framework.Logf("trying to forcibly kill kubectl port-forward")
  107. framework.TryKill(c.cmd)
  108. }
  109. func runPortForward(ns, podName string, port int) *portForwardCommand {
  110. cmd := framework.KubectlCmd("port-forward", fmt.Sprintf("--namespace=%v", ns), podName, fmt.Sprintf(":%d", port))
  111. // This is somewhat ugly but is the only way to retrieve the port that was picked
  112. // by the port-forward command. We don't want to hard code the port as we have no
  113. // way of guaranteeing we can pick one that isn't in use, particularly on Jenkins.
  114. framework.Logf("starting port-forward command and streaming output")
  115. stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
  116. if err != nil {
  117. framework.Failf("Failed to start port-forward command: %v", err)
  118. }
  119. buf := make([]byte, 128)
  120. // After v1.3.0-alpha.4 (#17030), kubectl port-forward outputs port
  121. // info to stdout, not stderr, so for version-skewed tests, look there
  122. // instead.
  123. var portOutput io.ReadCloser
  124. if useStdOut, err := framework.KubectlVersionGTE(portForwardPortToStdOutV); err != nil {
  125. framework.Failf("Failed to get kubectl version: %v", err)
  126. } else if useStdOut {
  127. portOutput = stdout
  128. } else {
  129. portOutput = stderr
  130. }
  131. var n int
  132. framework.Logf("reading from `kubectl port-forward` command's stdout")
  133. if n, err = portOutput.Read(buf); err != nil {
  134. framework.Failf("Failed to read from kubectl port-forward stdout: %v", err)
  135. }
  136. portForwardOutput := string(buf[:n])
  137. match := portForwardRegexp.FindStringSubmatch(portForwardOutput)
  138. if len(match) != 2 {
  139. framework.Failf("Failed to parse kubectl port-forward output: %s", portForwardOutput)
  140. }
  141. listenPort, err := strconv.Atoi(match[1])
  142. if err != nil {
  143. framework.Failf("Error converting %s to an int: %v", match[1], err)
  144. }
  145. return &portForwardCommand{
  146. cmd: cmd,
  147. port: listenPort,
  148. }
  149. }
  150. var _ = framework.KubeDescribe("Port forwarding", func() {
  151. f := framework.NewDefaultFramework("port-forwarding")
  152. framework.KubeDescribe("With a server that expects a client request", func() {
  153. It("should support a client that connects, sends no data, and disconnects [Conformance]", func() {
  154. By("creating the target pod")
  155. pod := pfPod("abc", "1", "1", "1")
  156. if _, err := f.Client.Pods(f.Namespace.Name).Create(pod); err != nil {
  157. framework.Failf("Couldn't create pod: %v", err)
  158. }
  159. if err := f.WaitForPodRunning(pod.Name); err != nil {
  160. framework.Failf("Pod did not start running: %v", err)
  161. }
  162. defer func() {
  163. logs, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  164. if err != nil {
  165. framework.Logf("Error getting pod log: %v", err)
  166. } else {
  167. framework.Logf("Pod log:\n%s", logs)
  168. }
  169. }()
  170. By("Running 'kubectl port-forward'")
  171. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  172. defer cmd.Stop()
  173. By("Dialing the local port")
  174. conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  175. if err != nil {
  176. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  177. }
  178. By("Closing the connection to the local port")
  179. conn.Close()
  180. By("Waiting for the target pod to stop running")
  181. if err := f.WaitForPodNoLongerRunning(pod.Name); err != nil {
  182. framework.Failf("Pod did not stop running: %v", err)
  183. }
  184. By("Verifying logs")
  185. logOutput, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  186. if err != nil {
  187. framework.Failf("Error retrieving pod logs: %v", err)
  188. }
  189. verifyLogMessage(logOutput, "Accepted client connection")
  190. verifyLogMessage(logOutput, "Expected to read 3 bytes from client, but got 0 instead")
  191. })
  192. It("should support a client that connects, sends data, and disconnects [Conformance]", func() {
  193. By("creating the target pod")
  194. pod := pfPod("abc", "10", "10", "100")
  195. if _, err := f.Client.Pods(f.Namespace.Name).Create(pod); err != nil {
  196. framework.Failf("Couldn't create pod: %v", err)
  197. }
  198. if err := f.WaitForPodRunning(pod.Name); err != nil {
  199. framework.Failf("Pod did not start running: %v", err)
  200. }
  201. defer func() {
  202. logs, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  203. if err != nil {
  204. framework.Logf("Error getting pod log: %v", err)
  205. } else {
  206. framework.Logf("Pod log:\n%s", logs)
  207. }
  208. }()
  209. By("Running 'kubectl port-forward'")
  210. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  211. defer cmd.Stop()
  212. By("Dialing the local port")
  213. addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  214. if err != nil {
  215. framework.Failf("Error resolving tcp addr: %v", err)
  216. }
  217. conn, err := net.DialTCP("tcp", nil, addr)
  218. if err != nil {
  219. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  220. }
  221. defer func() {
  222. By("Closing the connection to the local port")
  223. conn.Close()
  224. }()
  225. By("Sending the expected data to the local port")
  226. fmt.Fprint(conn, "abc")
  227. By("Closing the write half of the client's connection")
  228. conn.CloseWrite()
  229. By("Reading data from the local port")
  230. fromServer, err := ioutil.ReadAll(conn)
  231. if err != nil {
  232. framework.Failf("Unexpected error reading data from the server: %v", err)
  233. }
  234. if e, a := strings.Repeat("x", 100), string(fromServer); e != a {
  235. framework.Failf("Expected %q from server, got %q", e, a)
  236. }
  237. By("Waiting for the target pod to stop running")
  238. if err := f.WaitForPodNoLongerRunning(pod.Name); err != nil {
  239. framework.Failf("Pod did not stop running: %v", err)
  240. }
  241. By("Verifying logs")
  242. logOutput, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  243. if err != nil {
  244. framework.Failf("Error retrieving pod logs: %v", err)
  245. }
  246. verifyLogMessage(logOutput, "^Accepted client connection$")
  247. verifyLogMessage(logOutput, "^Received expected client data$")
  248. verifyLogMessage(logOutput, "^Done$")
  249. })
  250. })
  251. framework.KubeDescribe("With a server that expects no client request", func() {
  252. It("should support a client that connects, sends no data, and disconnects [Conformance]", func() {
  253. By("creating the target pod")
  254. pod := pfPod("", "10", "10", "100")
  255. if _, err := f.Client.Pods(f.Namespace.Name).Create(pod); err != nil {
  256. framework.Failf("Couldn't create pod: %v", err)
  257. }
  258. if err := f.WaitForPodRunning(pod.Name); err != nil {
  259. framework.Failf("Pod did not start running: %v", err)
  260. }
  261. defer func() {
  262. logs, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  263. if err != nil {
  264. framework.Logf("Error getting pod log: %v", err)
  265. } else {
  266. framework.Logf("Pod log:\n%s", logs)
  267. }
  268. }()
  269. By("Running 'kubectl port-forward'")
  270. cmd := runPortForward(f.Namespace.Name, pod.Name, 80)
  271. defer cmd.Stop()
  272. By("Dialing the local port")
  273. conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", cmd.port))
  274. if err != nil {
  275. framework.Failf("Couldn't connect to port %d: %v", cmd.port, err)
  276. }
  277. defer func() {
  278. By("Closing the connection to the local port")
  279. conn.Close()
  280. }()
  281. By("Reading data from the local port")
  282. fromServer, err := ioutil.ReadAll(conn)
  283. if err != nil {
  284. framework.Failf("Unexpected error reading data from the server: %v", err)
  285. }
  286. if e, a := strings.Repeat("x", 100), string(fromServer); e != a {
  287. framework.Failf("Expected %q from server, got %q", e, a)
  288. }
  289. By("Waiting for the target pod to stop running")
  290. if err := f.WaitForPodNoLongerRunning(pod.Name); err != nil {
  291. framework.Failf("Pod did not stop running: %v", err)
  292. }
  293. By("Verifying logs")
  294. logOutput, err := framework.GetPodLogs(f.Client, f.Namespace.Name, pod.Name, "portforwardtester")
  295. if err != nil {
  296. framework.Failf("Error retrieving pod logs: %v", err)
  297. }
  298. verifyLogMessage(logOutput, "Accepted client connection")
  299. verifyLogMessage(logOutput, "Done")
  300. })
  301. })
  302. })
  303. func verifyLogMessage(log, expected string) {
  304. re := regexp.MustCompile(expected)
  305. lines := strings.Split(log, "\n")
  306. for i := range lines {
  307. if re.MatchString(lines[i]) {
  308. return
  309. }
  310. }
  311. framework.Failf("Missing %q from log: %s", expected, log)
  312. }