docker_api_attach_test.go 9.1 KB

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