docker_api_attach_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "net/http/httputil"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/client"
  16. "github.com/docker/docker/pkg/stdcopy"
  17. "github.com/docker/docker/testutil/request"
  18. "github.com/pkg/errors"
  19. "golang.org/x/net/websocket"
  20. "gotest.tools/assert"
  21. is "gotest.tools/assert/cmp"
  22. )
  23. func (s *DockerSuite) TestGetContainersAttachWebsocket(c *testing.T) {
  24. testRequires(c, DaemonIsLinux)
  25. out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")
  26. rwc, err := request.SockConn(10*time.Second, request.DaemonHost())
  27. assert.NilError(c, err)
  28. cleanedContainerID := strings.TrimSpace(out)
  29. config, err := websocket.NewConfig(
  30. "/containers/"+cleanedContainerID+"/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)
  40. go func() {
  41. _, err := io.ReadFull(ws, actual)
  42. outChan <- err
  43. close(outChan)
  44. }()
  45. inChan := make(chan error)
  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 *DockerSuite) TestPostContainersAttachContainerNotFound(c *testing.T) {
  67. resp, _, err := request.Post("/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 *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *testing.T) {
  77. res, body, err := request.Get("/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 *DockerSuite) TestPostContainersAttach(c *testing.T) {
  86. testRequires(c, DaemonIsLinux)
  87. expectSuccess := func(conn net.Conn, br *bufio.Reader, stream string, tty bool) {
  88. defer conn.Close()
  89. expected := []byte("success")
  90. _, err := conn.Write(expected)
  91. assert.NilError(c, err)
  92. conn.SetReadDeadline(time.Now().Add(time.Second))
  93. lenHeader := 0
  94. if !tty {
  95. lenHeader = 8
  96. }
  97. actual := make([]byte, len(expected)+lenHeader)
  98. _, err = io.ReadFull(br, actual)
  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(conn net.Conn, br *bufio.Reader, stream string) {
  111. defer conn.Close()
  112. _, err := conn.Write([]byte{'t'})
  113. assert.NilError(c, err)
  114. conn.SetReadDeadline(time.Now().Add(time.Second))
  115. actual := make([]byte, 1)
  116. _, err = io.ReadFull(br, actual)
  117. opErr, ok := err.(*net.OpError)
  118. assert.Assert(c, ok, "Error is expected to be *net.OpError, got %v", err)
  119. assert.Assert(c, opErr.Timeout(), "Read from %s is expected to timeout", stream)
  120. }
  121. // Create a container that only emits stdout.
  122. cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat")
  123. cid = strings.TrimSpace(cid)
  124. // Attach to the container's stdout stream.
  125. conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
  126. assert.NilError(c, err)
  127. // Check if the data from stdout can be received.
  128. expectSuccess(conn, br, "stdout", false)
  129. // Attach to the container's stderr stream.
  130. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
  131. assert.NilError(c, err)
  132. // Since the container only emits stdout, attaching to stderr should return nothing.
  133. expectTimeout(conn, br, "stdout")
  134. // Test the similar functions of the stderr stream.
  135. cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2")
  136. cid = strings.TrimSpace(cid)
  137. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
  138. assert.NilError(c, err)
  139. expectSuccess(conn, br, "stderr", false)
  140. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
  141. assert.NilError(c, err)
  142. expectTimeout(conn, br, "stderr")
  143. // Test with tty.
  144. cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2")
  145. cid = strings.TrimSpace(cid)
  146. // Attach to stdout only.
  147. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
  148. assert.NilError(c, err)
  149. expectSuccess(conn, br, "stdout", true)
  150. // Attach without stdout stream.
  151. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
  152. assert.NilError(c, err)
  153. // Nothing should be received because both the stdout and stderr of the container will be
  154. // sent to the client as stdout when tty is enabled.
  155. expectTimeout(conn, br, "stdout")
  156. // Test the client API
  157. client, err := client.NewClientWithOpts(client.FromEnv)
  158. assert.NilError(c, err)
  159. defer client.Close()
  160. cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat")
  161. cid = strings.TrimSpace(cid)
  162. // Make sure we don't see "hello" if Logs is false
  163. attachOpts := types.ContainerAttachOptions{
  164. Stream: true,
  165. Stdin: true,
  166. Stdout: true,
  167. Stderr: true,
  168. Logs: false,
  169. }
  170. resp, err := client.ContainerAttach(context.Background(), cid, attachOpts)
  171. assert.NilError(c, err)
  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 = client.ContainerAttach(context.Background(), 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. _, err = stdcopy.StdCopy(&outBuf, &errBuf, resp.Reader)
  183. if err != nil && errors.Cause(err).(net.Error).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. // SockRequestHijack creates a connection to specified host (with method, contenttype, …) and returns a hijacked connection
  192. // and the output as a `bufio.Reader`
  193. func sockRequestHijack(method, endpoint string, data io.Reader, ct string, daemon string, modifiers ...func(*http.Request)) (net.Conn, *bufio.Reader, error) {
  194. req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. client.Do(req)
  199. conn, br := client.Hijack()
  200. return conn, br, nil
  201. }
  202. // FIXME(vdemeester) httputil.ClientConn is deprecated, use http.Client instead (closer to actual client)
  203. // Deprecated: Use New instead of NewRequestClient
  204. // Deprecated: use request.Do (or Get, Delete, Post) instead
  205. func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) {
  206. c, err := request.SockConn(10*time.Second, daemon)
  207. if err != nil {
  208. return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  209. }
  210. client := httputil.NewClientConn(c, nil)
  211. req, err := http.NewRequest(method, endpoint, data)
  212. if err != nil {
  213. client.Close()
  214. return nil, nil, fmt.Errorf("could not create new request: %v", err)
  215. }
  216. for _, opt := range modifiers {
  217. opt(req)
  218. }
  219. if ct != "" {
  220. req.Header.Set("Content-Type", ct)
  221. }
  222. return req, client, nil
  223. }