docker_api_attach_test.go 8.8 KB

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