github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/integration-cli/docker_api_attach_test.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "context" 7 "io" 8 "net" 9 "net/http" 10 "strings" 11 "testing" 12 "time" 13 14 "github.com/docker/docker/api/types" 15 "github.com/docker/docker/client" 16 "github.com/docker/docker/pkg/stdcopy" 17 "github.com/docker/docker/testutil/request" 18 "github.com/docker/go-connections/sockets" 19 "github.com/pkg/errors" 20 "golang.org/x/net/websocket" 21 "gotest.tools/v3/assert" 22 is "gotest.tools/v3/assert/cmp" 23 ) 24 25 func (s *DockerSuite) TestGetContainersAttachWebsocket(c *testing.T) { 26 testRequires(c, DaemonIsLinux) 27 out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") 28 29 rwc, err := request.SockConn(10*time.Second, request.DaemonHost()) 30 assert.NilError(c, err) 31 32 cleanedContainerID := strings.TrimSpace(out) 33 config, err := websocket.NewConfig( 34 "/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1", 35 "http://localhost", 36 ) 37 assert.NilError(c, err) 38 39 ws, err := websocket.NewClient(config, rwc) 40 assert.NilError(c, err) 41 defer ws.Close() 42 43 expected := []byte("hello") 44 actual := make([]byte, len(expected)) 45 46 outChan := make(chan error, 1) 47 go func() { 48 _, err := io.ReadFull(ws, actual) 49 outChan <- err 50 close(outChan) 51 }() 52 53 inChan := make(chan error, 1) 54 go func() { 55 _, err := ws.Write(expected) 56 inChan <- err 57 close(inChan) 58 }() 59 60 select { 61 case err := <-inChan: 62 assert.NilError(c, err) 63 case <-time.After(5 * time.Second): 64 c.Fatal("Timeout writing to ws") 65 } 66 67 select { 68 case err := <-outChan: 69 assert.NilError(c, err) 70 case <-time.After(5 * time.Second): 71 c.Fatal("Timeout reading from ws") 72 } 73 74 assert.Assert(c, is.DeepEqual(actual, expected), "Websocket didn't return the expected data") 75 } 76 77 // regression gh14320 78 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *testing.T) { 79 resp, _, err := request.Post("/containers/doesnotexist/attach") 80 assert.NilError(c, err) 81 // connection will shutdown, err should be "persistent connection closed" 82 assert.Equal(c, resp.StatusCode, http.StatusNotFound) 83 content, err := request.ReadBody(resp.Body) 84 assert.NilError(c, err) 85 expected := "No such container: doesnotexist\r\n" 86 assert.Equal(c, string(content), expected) 87 } 88 89 func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *testing.T) { 90 res, body, err := request.Get("/containers/doesnotexist/attach/ws") 91 assert.Equal(c, res.StatusCode, http.StatusNotFound) 92 assert.NilError(c, err) 93 b, err := request.ReadBody(body) 94 assert.NilError(c, err) 95 expected := "No such container: doesnotexist" 96 assert.Assert(c, strings.Contains(getErrorMessage(c, b), expected)) 97 } 98 99 func (s *DockerSuite) TestPostContainersAttach(c *testing.T) { 100 testRequires(c, DaemonIsLinux) 101 102 expectSuccess := func(wc io.WriteCloser, br *bufio.Reader, stream string, tty bool) { 103 defer wc.Close() 104 expected := []byte("success") 105 _, err := wc.Write(expected) 106 assert.NilError(c, err) 107 108 lenHeader := 0 109 if !tty { 110 lenHeader = 8 111 } 112 actual := make([]byte, len(expected)+lenHeader) 113 _, err = readTimeout(br, actual, time.Second) 114 assert.NilError(c, err) 115 if !tty { 116 fdMap := map[string]byte{ 117 "stdin": 0, 118 "stdout": 1, 119 "stderr": 2, 120 } 121 assert.Equal(c, actual[0], fdMap[stream]) 122 } 123 assert.Assert(c, is.DeepEqual(actual[lenHeader:], expected), "Attach didn't return the expected data from %s", stream) 124 } 125 126 expectTimeout := func(wc io.WriteCloser, br *bufio.Reader, stream string) { 127 defer wc.Close() 128 _, err := wc.Write([]byte{'t'}) 129 assert.NilError(c, err) 130 131 actual := make([]byte, 1) 132 _, err = readTimeout(br, actual, time.Second) 133 assert.Assert(c, err.Error() == "Timeout", "Read from %s is expected to timeout", stream) 134 } 135 136 // Create a container that only emits stdout. 137 cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat") 138 cid = strings.TrimSpace(cid) 139 140 // Attach to the container's stdout stream. 141 wc, br, err := requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) 142 assert.NilError(c, err) 143 // Check if the data from stdout can be received. 144 expectSuccess(wc, br, "stdout", false) 145 146 // Attach to the container's stderr stream. 147 wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) 148 assert.NilError(c, err) 149 // Since the container only emits stdout, attaching to stderr should return nothing. 150 expectTimeout(wc, br, "stdout") 151 152 // Test the similar functions of the stderr stream. 153 cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2") 154 cid = strings.TrimSpace(cid) 155 wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) 156 assert.NilError(c, err) 157 expectSuccess(wc, br, "stderr", false) 158 wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) 159 assert.NilError(c, err) 160 expectTimeout(wc, br, "stderr") 161 162 // Test with tty. 163 cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2") 164 cid = strings.TrimSpace(cid) 165 // Attach to stdout only. 166 wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) 167 assert.NilError(c, err) 168 expectSuccess(wc, br, "stdout", true) 169 170 // Attach without stdout stream. 171 wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) 172 assert.NilError(c, err) 173 // Nothing should be received because both the stdout and stderr of the container will be 174 // sent to the client as stdout when tty is enabled. 175 expectTimeout(wc, br, "stdout") 176 177 // Test the client API 178 client, err := client.NewClientWithOpts(client.FromEnv) 179 assert.NilError(c, err) 180 defer client.Close() 181 182 cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat") 183 cid = strings.TrimSpace(cid) 184 185 // Make sure we don't see "hello" if Logs is false 186 attachOpts := types.ContainerAttachOptions{ 187 Stream: true, 188 Stdin: true, 189 Stdout: true, 190 Stderr: true, 191 Logs: false, 192 } 193 194 resp, err := client.ContainerAttach(context.Background(), cid, attachOpts) 195 assert.NilError(c, err) 196 expectSuccess(resp.Conn, resp.Reader, "stdout", false) 197 198 // Make sure we do see "hello" if Logs is true 199 attachOpts.Logs = true 200 resp, err = client.ContainerAttach(context.Background(), cid, attachOpts) 201 assert.NilError(c, err) 202 203 defer resp.Conn.Close() 204 resp.Conn.SetReadDeadline(time.Now().Add(time.Second)) 205 206 _, err = resp.Conn.Write([]byte("success")) 207 assert.NilError(c, err) 208 209 var outBuf, errBuf bytes.Buffer 210 var nErr net.Error 211 _, err = stdcopy.StdCopy(&outBuf, &errBuf, resp.Reader) 212 if errors.As(err, &nErr) && nErr.Timeout() { 213 // ignore the timeout error as it is expected 214 err = nil 215 } 216 assert.NilError(c, err) 217 assert.Equal(c, errBuf.String(), "") 218 assert.Equal(c, outBuf.String(), "hello\nsuccess") 219 } 220 221 // requestHijack create a http requst to specified host with `Upgrade` header (with method 222 // , contenttype, …), if receive a successful "101 Switching Protocols" response return 223 // a `io.WriteCloser` and `bufio.Reader` 224 func requestHijack(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (io.WriteCloser, *bufio.Reader, error) { 225 226 hostURL, err := client.ParseHostURL(daemon) 227 if err != nil { 228 return nil, nil, errors.Wrap(err, "parse daemon host error") 229 } 230 231 req, err := http.NewRequest(method, endpoint, data) 232 if err != nil { 233 return nil, nil, errors.Wrap(err, "could not create new request") 234 } 235 req.URL.Scheme = "http" 236 req.URL.Host = hostURL.Host 237 238 for _, opt := range modifiers { 239 opt(req) 240 } 241 242 if ct != "" { 243 req.Header.Set("Content-Type", ct) 244 } 245 246 // must have Upgrade header 247 // server api return 101 Switching Protocols 248 req.Header.Set("Upgrade", "tcp") 249 250 // new client 251 // FIXME use testutil/request newHTTPClient 252 transport := &http.Transport{} 253 err = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) 254 if err != nil { 255 return nil, nil, errors.Wrap(err, "configure Transport error") 256 } 257 258 client := http.Client{ 259 Transport: transport, 260 } 261 262 resp, err := client.Do(req) 263 if err != nil { 264 return nil, nil, errors.Wrap(err, "client.Do") 265 } 266 267 if !bodyIsWritable(resp) { 268 return nil, nil, errors.New("response.Body not writable") 269 } 270 271 return resp.Body.(io.WriteCloser), bufio.NewReader(resp.Body), nil 272 } 273 274 // bodyIsWritable check Response.Body is writable 275 func bodyIsWritable(r *http.Response) bool { 276 _, ok := r.Body.(io.Writer) 277 return ok 278 } 279 280 // readTimeout read from io.Reader with timeout 281 func readTimeout(r io.Reader, buf []byte, timeout time.Duration) (n int, err error) { 282 ch := make(chan bool, 1) 283 go func() { 284 n, err = io.ReadFull(r, buf) 285 ch <- true 286 }() 287 select { 288 case <-ch: 289 return 290 case <-time.After(timeout): 291 return 0, errors.New("Timeout") 292 } 293 }