docker_api_attach_test.go 9.1 KB

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