attach_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 cmd
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "net/url"
  20. "strings"
  21. "testing"
  22. "github.com/spf13/cobra"
  23. "k8s.io/kubernetes/pkg/api"
  24. "k8s.io/kubernetes/pkg/api/testapi"
  25. "k8s.io/kubernetes/pkg/api/unversioned"
  26. "k8s.io/kubernetes/pkg/client/restclient"
  27. "k8s.io/kubernetes/pkg/client/unversioned/fake"
  28. "k8s.io/kubernetes/pkg/util/term"
  29. )
  30. type fakeRemoteAttach struct {
  31. method string
  32. url *url.URL
  33. err error
  34. }
  35. func (f *fakeRemoteAttach) Attach(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue term.TerminalSizeQueue) error {
  36. f.method = method
  37. f.url = url
  38. return f.err
  39. }
  40. func TestPodAndContainerAttach(t *testing.T) {
  41. tests := []struct {
  42. args []string
  43. p *AttachOptions
  44. name string
  45. expectError bool
  46. expectedPod string
  47. expectedContainer string
  48. }{
  49. {
  50. p: &AttachOptions{},
  51. expectError: true,
  52. name: "empty",
  53. },
  54. {
  55. p: &AttachOptions{},
  56. args: []string{"foo", "bar"},
  57. expectError: true,
  58. name: "too many args",
  59. },
  60. {
  61. p: &AttachOptions{},
  62. args: []string{"foo"},
  63. expectedPod: "foo",
  64. name: "no container, no flags",
  65. },
  66. {
  67. p: &AttachOptions{StreamOptions: StreamOptions{ContainerName: "bar"}},
  68. args: []string{"foo"},
  69. expectedPod: "foo",
  70. expectedContainer: "bar",
  71. name: "container in flag",
  72. },
  73. {
  74. p: &AttachOptions{StreamOptions: StreamOptions{ContainerName: "initfoo"}},
  75. args: []string{"foo"},
  76. expectedPod: "foo",
  77. expectedContainer: "initfoo",
  78. name: "init container in flag",
  79. },
  80. {
  81. p: &AttachOptions{StreamOptions: StreamOptions{ContainerName: "bar"}},
  82. args: []string{"foo", "-c", "wrong"},
  83. expectError: true,
  84. name: "non-existing container in flag",
  85. },
  86. }
  87. for _, test := range tests {
  88. f, tf, _, ns := NewAPIFactory()
  89. tf.Client = &fake.RESTClient{
  90. NegotiatedSerializer: ns,
  91. Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { return nil, nil }),
  92. }
  93. tf.Namespace = "test"
  94. tf.ClientConfig = &restclient.Config{}
  95. cmd := &cobra.Command{}
  96. options := test.p
  97. err := options.Complete(f, cmd, test.args)
  98. if test.expectError && err == nil {
  99. t.Errorf("unexpected non-error (%s)", test.name)
  100. }
  101. if !test.expectError && err != nil {
  102. t.Errorf("unexpected error: %v (%s)", err, test.name)
  103. }
  104. if err != nil {
  105. continue
  106. }
  107. if options.PodName != test.expectedPod {
  108. t.Errorf("expected: %s, got: %s (%s)", test.expectedPod, options.PodName, test.name)
  109. }
  110. if options.ContainerName != test.expectedContainer {
  111. t.Errorf("expected: %s, got: %s (%s)", test.expectedContainer, options.ContainerName, test.name)
  112. }
  113. }
  114. }
  115. func TestAttach(t *testing.T) {
  116. version := testapi.Default.GroupVersion().Version
  117. tests := []struct {
  118. name, version, podPath, attachPath, container string
  119. pod *api.Pod
  120. remoteAttachErr bool
  121. exepctedErr string
  122. }{
  123. {
  124. name: "pod attach",
  125. version: version,
  126. podPath: "/api/" + version + "/namespaces/test/pods/foo",
  127. attachPath: "/api/" + version + "/namespaces/test/pods/foo/attach",
  128. pod: attachPod(),
  129. container: "bar",
  130. },
  131. {
  132. name: "pod attach error",
  133. version: version,
  134. podPath: "/api/" + version + "/namespaces/test/pods/foo",
  135. attachPath: "/api/" + version + "/namespaces/test/pods/foo/attach",
  136. pod: attachPod(),
  137. remoteAttachErr: true,
  138. container: "bar",
  139. exepctedErr: "attach error",
  140. },
  141. {
  142. name: "container not found error",
  143. version: version,
  144. podPath: "/api/" + version + "/namespaces/test/pods/foo",
  145. attachPath: "/api/" + version + "/namespaces/test/pods/foo/attach",
  146. pod: attachPod(),
  147. container: "foo",
  148. exepctedErr: "cannot attach to the container: container not found (foo)",
  149. },
  150. }
  151. for _, test := range tests {
  152. f, tf, codec, ns := NewAPIFactory()
  153. tf.Client = &fake.RESTClient{
  154. NegotiatedSerializer: ns,
  155. Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
  156. switch p, m := req.URL.Path, req.Method; {
  157. case p == test.podPath && m == "GET":
  158. body := objBody(codec, test.pod)
  159. return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: body}, nil
  160. default:
  161. // Ensures no GET is performed when deleting by name
  162. t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req)
  163. return nil, fmt.Errorf("unexpected request")
  164. }
  165. }),
  166. }
  167. tf.Namespace = "test"
  168. tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}}
  169. bufOut := bytes.NewBuffer([]byte{})
  170. bufErr := bytes.NewBuffer([]byte{})
  171. bufIn := bytes.NewBuffer([]byte{})
  172. remoteAttach := &fakeRemoteAttach{}
  173. if test.remoteAttachErr {
  174. remoteAttach.err = fmt.Errorf("attach error")
  175. }
  176. params := &AttachOptions{
  177. StreamOptions: StreamOptions{
  178. ContainerName: test.container,
  179. In: bufIn,
  180. Out: bufOut,
  181. Err: bufErr,
  182. },
  183. Attach: remoteAttach,
  184. }
  185. cmd := &cobra.Command{}
  186. if err := params.Complete(f, cmd, []string{"foo"}); err != nil {
  187. t.Fatal(err)
  188. }
  189. err := params.Run()
  190. if test.exepctedErr != "" && err.Error() != test.exepctedErr {
  191. t.Errorf("%s: Unexpected exec error: %v", test.name, err)
  192. continue
  193. }
  194. if test.exepctedErr == "" && err != nil {
  195. t.Errorf("%s: Unexpected error: %v", test.name, err)
  196. continue
  197. }
  198. if test.exepctedErr != "" {
  199. continue
  200. }
  201. if remoteAttach.url.Path != test.attachPath {
  202. t.Errorf("%s: Did not get expected path for exec request", test.name)
  203. continue
  204. }
  205. if remoteAttach.method != "POST" {
  206. t.Errorf("%s: Did not get method for attach request: %s", test.name, remoteAttach.method)
  207. }
  208. if remoteAttach.url.Query().Get("container") != "bar" {
  209. t.Errorf("%s: Did not have query parameters: %s", test.name, remoteAttach.url.Query())
  210. }
  211. }
  212. }
  213. func TestAttachWarnings(t *testing.T) {
  214. version := testapi.Default.GroupVersion().Version
  215. tests := []struct {
  216. name, container, version, podPath, expectedErr, expectedOut string
  217. pod *api.Pod
  218. stdin, tty bool
  219. }{
  220. {
  221. name: "fallback tty if not supported",
  222. version: version,
  223. podPath: "/api/" + version + "/namespaces/test/pods/foo",
  224. pod: attachPod(),
  225. stdin: true,
  226. tty: true,
  227. expectedErr: "Unable to use a TTY - container bar did not allocate one",
  228. },
  229. }
  230. for _, test := range tests {
  231. f, tf, codec, ns := NewAPIFactory()
  232. tf.Client = &fake.RESTClient{
  233. NegotiatedSerializer: ns,
  234. Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
  235. switch p, m := req.URL.Path, req.Method; {
  236. case p == test.podPath && m == "GET":
  237. body := objBody(codec, test.pod)
  238. return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: body}, nil
  239. default:
  240. t.Errorf("%s: unexpected request: %s %#v\n%#v", test.name, req.Method, req.URL, req)
  241. return nil, fmt.Errorf("unexpected request")
  242. }
  243. }),
  244. }
  245. tf.Namespace = "test"
  246. tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: &unversioned.GroupVersion{Version: test.version}}}
  247. bufOut := bytes.NewBuffer([]byte{})
  248. bufErr := bytes.NewBuffer([]byte{})
  249. bufIn := bytes.NewBuffer([]byte{})
  250. ex := &fakeRemoteAttach{}
  251. params := &AttachOptions{
  252. StreamOptions: StreamOptions{
  253. ContainerName: test.container,
  254. In: bufIn,
  255. Out: bufOut,
  256. Err: bufErr,
  257. Stdin: test.stdin,
  258. TTY: test.tty,
  259. },
  260. Attach: ex,
  261. }
  262. cmd := &cobra.Command{}
  263. if err := params.Complete(f, cmd, []string{"foo"}); err != nil {
  264. t.Fatal(err)
  265. }
  266. if err := params.Run(); err != nil {
  267. t.Fatal(err)
  268. }
  269. if test.stdin && test.tty {
  270. if !test.pod.Spec.Containers[0].TTY {
  271. if !strings.Contains(bufErr.String(), test.expectedErr) {
  272. t.Errorf("%s: Expected TTY fallback warning for attach request: %s", test.name, bufErr.String())
  273. continue
  274. }
  275. }
  276. }
  277. }
  278. }
  279. func attachPod() *api.Pod {
  280. return &api.Pod{
  281. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "test", ResourceVersion: "10"},
  282. Spec: api.PodSpec{
  283. RestartPolicy: api.RestartPolicyAlways,
  284. DNSPolicy: api.DNSClusterFirst,
  285. Containers: []api.Container{
  286. {
  287. Name: "bar",
  288. },
  289. },
  290. InitContainers: []api.Container{
  291. {
  292. Name: "initfoo",
  293. },
  294. },
  295. },
  296. Status: api.PodStatus{
  297. Phase: api.PodRunning,
  298. },
  299. }
  300. }