docker_api_attach_test.go 9.0 KB

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