docker_api_attach_test.go 8.7 KB

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