integration-cli/docker_api_attach_test.go
9e37a046
 package main
 
 import (
13364cd4
 	"bufio"
fc8097f9
 	"bytes"
 	"context"
a8715ea2
 	"io"
13364cd4
 	"net"
88d32a61
 	"net/http"
475c6531
 	"strings"
59e55dcd
 	"testing"
ac6cb41d
 	"time"
9e37a046
 
fc8097f9
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/client"
 	"github.com/docker/docker/pkg/stdcopy"
b37c214e
 	"github.com/docker/docker/testutil/request"
203ba72f
 	"github.com/docker/go-connections/sockets"
ecc54889
 	"github.com/pkg/errors"
d820e00a
 	"golang.org/x/net/websocket"
9f0b3f56
 	"gotest.tools/v3/assert"
 	is "gotest.tools/v3/assert/cmp"
9e37a046
 )
 
1d92789b
 func (s *DockerSuite) TestGetContainersAttachWebsocket(c *testing.T) {
f9a3558a
 	testRequires(c, DaemonIsLinux)
5c295460
 	out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")
9e37a046
 
7c40c0a9
 	rwc, err := request.SockConn(10*time.Second, request.DaemonHost())
6345208b
 	assert.NilError(c, err)
9e37a046
 
475c6531
 	cleanedContainerID := strings.TrimSpace(out)
9e37a046
 	config, err := websocket.NewConfig(
 		"/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1",
 		"http://localhost",
 	)
6345208b
 	assert.NilError(c, err)
9e37a046
 
 	ws, err := websocket.NewClient(config, rwc)
6345208b
 	assert.NilError(c, err)
9e37a046
 	defer ws.Close()
 
 	expected := []byte("hello")
 	actual := make([]byte, len(expected))
c7b2632d
 
c322af80
 	outChan := make(chan error, 1)
9e37a046
 	go func() {
85354fb7
 		_, err := io.ReadFull(ws, actual)
c7b2632d
 		outChan <- err
 		close(outChan)
9e37a046
 	}()
 
c322af80
 	inChan := make(chan error, 1)
9e37a046
 	go func() {
c7b2632d
 		_, err := ws.Write(expected)
 		inChan <- err
 		close(inChan)
 	}()
 
 	select {
 	case err := <-inChan:
6345208b
 		assert.NilError(c, err)
c7b2632d
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout writing to ws")
 	}
9e37a046
 
c7b2632d
 	select {
 	case err := <-outChan:
6345208b
 		assert.NilError(c, err)
c7b2632d
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout reading from ws")
 	}
9e37a046
 
6345208b
 	assert.Assert(c, is.DeepEqual(actual, expected), "Websocket didn't return the expected data")
9e37a046
 }
88d32a61
 
 // regression gh14320
1d92789b
 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *testing.T) {
0a91ba2d
 	resp, _, err := request.Post("/containers/doesnotexist/attach")
6345208b
 	assert.NilError(c, err)
91e5bb95
 	// connection will shutdown, err should be "persistent connection closed"
6345208b
 	assert.Equal(c, resp.StatusCode, http.StatusNotFound)
4f304e72
 	content, err := request.ReadBody(resp.Body)
6345208b
 	assert.NilError(c, err)
91e5bb95
 	expected := "No such container: doesnotexist\r\n"
6345208b
 	assert.Equal(c, string(content), expected)
88d32a61
 }
 
1d92789b
 func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *testing.T) {
0fd5a654
 	res, body, err := request.Get("/containers/doesnotexist/attach/ws")
6345208b
 	assert.Equal(c, res.StatusCode, http.StatusNotFound)
 	assert.NilError(c, err)
0fd5a654
 	b, err := request.ReadBody(body)
6345208b
 	assert.NilError(c, err)
322e2a7d
 	expected := "No such container: doesnotexist"
6345208b
 	assert.Assert(c, strings.Contains(getErrorMessage(c, b), expected))
88d32a61
 }
a8715ea2
 
1d92789b
 func (s *DockerSuite) TestPostContainersAttach(c *testing.T) {
f9a3558a
 	testRequires(c, DaemonIsLinux)
a8715ea2
 
203ba72f
 	expectSuccess := func(wc io.WriteCloser, br *bufio.Reader, stream string, tty bool) {
 		defer wc.Close()
13364cd4
 		expected := []byte("success")
203ba72f
 		_, err := wc.Write(expected)
6345208b
 		assert.NilError(c, err)
a8715ea2
 
13364cd4
 		lenHeader := 0
 		if !tty {
 			lenHeader = 8
 		}
 		actual := make([]byte, len(expected)+lenHeader)
203ba72f
 		_, err = readTimeout(br, actual, time.Second)
6345208b
 		assert.NilError(c, err)
13364cd4
 		if !tty {
 			fdMap := map[string]byte{
 				"stdin":  0,
 				"stdout": 1,
 				"stderr": 2,
 			}
6345208b
 			assert.Equal(c, actual[0], fdMap[stream])
13364cd4
 		}
6345208b
 		assert.Assert(c, is.DeepEqual(actual[lenHeader:], expected), "Attach didn't return the expected data from %s", stream)
a8715ea2
 	}
 
203ba72f
 	expectTimeout := func(wc io.WriteCloser, br *bufio.Reader, stream string) {
 		defer wc.Close()
 		_, err := wc.Write([]byte{'t'})
6345208b
 		assert.NilError(c, err)
a8715ea2
 
13364cd4
 		actual := make([]byte, 1)
203ba72f
 		_, err = readTimeout(br, actual, time.Second)
 		assert.Assert(c, err.Error() == "Timeout", "Read from %s is expected to timeout", stream)
a8715ea2
 	}
 
13364cd4
 	// Create a container that only emits stdout.
 	cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat")
 	cid = strings.TrimSpace(cid)
203ba72f
 
13364cd4
 	// Attach to the container's stdout stream.
203ba72f
 	wc, br, err := requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
13364cd4
 	// Check if the data from stdout can be received.
203ba72f
 	expectSuccess(wc, br, "stdout", false)
 
13364cd4
 	// Attach to the container's stderr stream.
203ba72f
 	wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
13364cd4
 	// Since the container only emits stdout, attaching to stderr should return nothing.
203ba72f
 	expectTimeout(wc, br, "stdout")
a8715ea2
 
927b334e
 	// Test the similar functions of the stderr stream.
13364cd4
 	cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2")
 	cid = strings.TrimSpace(cid)
203ba72f
 	wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
203ba72f
 	expectSuccess(wc, br, "stderr", false)
 	wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
203ba72f
 	expectTimeout(wc, br, "stderr")
a8715ea2
 
13364cd4
 	// Test with tty.
 	cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2")
 	cid = strings.TrimSpace(cid)
 	// Attach to stdout only.
203ba72f
 	wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
203ba72f
 	expectSuccess(wc, br, "stdout", true)
a8715ea2
 
13364cd4
 	// Attach without stdout stream.
203ba72f
 	wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost())
6345208b
 	assert.NilError(c, err)
13364cd4
 	// Nothing should be received because both the stdout and stderr of the container will be
 	// sent to the client as stdout when tty is enabled.
203ba72f
 	expectTimeout(wc, br, "stdout")
fc8097f9
 
 	// Test the client API
c8ff5ecc
 	client, err := client.NewClientWithOpts(client.FromEnv)
6345208b
 	assert.NilError(c, err)
0fd5a654
 	defer client.Close()
fc8097f9
 
 	cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat")
 	cid = strings.TrimSpace(cid)
 
ecc54889
 	// Make sure we don't see "hello" if Logs is false
fc8097f9
 	attachOpts := types.ContainerAttachOptions{
 		Stream: true,
 		Stdin:  true,
 		Stdout: true,
ecc54889
 		Stderr: true,
 		Logs:   false,
fc8097f9
 	}
 
 	resp, err := client.ContainerAttach(context.Background(), cid, attachOpts)
6345208b
 	assert.NilError(c, err)
fc8097f9
 	expectSuccess(resp.Conn, resp.Reader, "stdout", false)
 
 	// Make sure we do see "hello" if Logs is true
 	attachOpts.Logs = true
 	resp, err = client.ContainerAttach(context.Background(), cid, attachOpts)
6345208b
 	assert.NilError(c, err)
fc8097f9
 
 	defer resp.Conn.Close()
 	resp.Conn.SetReadDeadline(time.Now().Add(time.Second))
 
 	_, err = resp.Conn.Write([]byte("success"))
6345208b
 	assert.NilError(c, err)
fc8097f9
 
ecc54889
 	var outBuf, errBuf bytes.Buffer
07d60bc2
 	var nErr net.Error
ecc54889
 	_, err = stdcopy.StdCopy(&outBuf, &errBuf, resp.Reader)
07d60bc2
 	if errors.As(err, &nErr) && nErr.Timeout() {
ecc54889
 		// ignore the timeout error as it is expected
 		err = nil
 	}
6345208b
 	assert.NilError(c, err)
 	assert.Equal(c, errBuf.String(), "")
 	assert.Equal(c, outBuf.String(), "hello\nsuccess")
a8715ea2
 }
0a91ba2d
 
203ba72f
 // requestHijack create a http requst to specified host with `Upgrade` header (with method
 // , contenttype, …), if receive a successful "101 Switching Protocols" response return
 // a `io.WriteCloser` and `bufio.Reader`
 func requestHijack(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (io.WriteCloser, *bufio.Reader, error) {
0a91ba2d
 
203ba72f
 	hostURL, err := client.ParseHostURL(daemon)
0a91ba2d
 	if err != nil {
203ba72f
 		return nil, nil, errors.Wrap(err, "parse daemon host error")
0a91ba2d
 	}
 
 	req, err := http.NewRequest(method, endpoint, data)
 	if err != nil {
203ba72f
 		return nil, nil, errors.Wrap(err, "could not create new request")
0a91ba2d
 	}
203ba72f
 	req.URL.Scheme = "http"
 	req.URL.Host = hostURL.Host
0a91ba2d
 
 	for _, opt := range modifiers {
 		opt(req)
 	}
 
 	if ct != "" {
 		req.Header.Set("Content-Type", ct)
 	}
203ba72f
 
 	// must have Upgrade header
 	// server api return 101 Switching Protocols
 	req.Header.Set("Upgrade", "tcp")
 
 	// new client
 	// FIXME use testutil/request newHTTPClient
 	transport := &http.Transport{}
 	err = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host)
 	if err != nil {
 		return nil, nil, errors.Wrap(err, "configure Transport error")
 	}
 
 	client := http.Client{
 		Transport: transport,
 	}
 
 	resp, err := client.Do(req)
 	if err != nil {
 		return nil, nil, errors.Wrap(err, "client.Do")
 	}
 
 	if !bodyIsWritable(resp) {
 		return nil, nil, errors.New("response.Body not writable")
 	}
 
 	return resp.Body.(io.WriteCloser), bufio.NewReader(resp.Body), nil
 }
 
 // bodyIsWritable check Response.Body is writable
 func bodyIsWritable(r *http.Response) bool {
 	_, ok := r.Body.(io.Writer)
 	return ok
 }
 
 // readTimeout read from io.Reader with timeout
 func readTimeout(r io.Reader, buf []byte, timeout time.Duration) (n int, err error) {
c322af80
 	ch := make(chan bool, 1)
203ba72f
 	go func() {
 		n, err = io.ReadFull(r, buf)
 		ch <- true
 	}()
 	select {
 	case <-ch:
 		return
 	case <-time.After(timeout):
 		return 0, errors.New("Timeout")
 	}
0a91ba2d
 }