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"
ac6cb41d
 	"time"
9e37a046
 
fc8097f9
 	"github.com/docker/docker/api/types"
 	"github.com/docker/docker/client"
33968e6c
 	"github.com/docker/docker/integration-cli/checker"
d69d4799
 	"github.com/docker/docker/integration-cli/request"
fc8097f9
 	"github.com/docker/docker/pkg/stdcopy"
dc944ea7
 	"github.com/go-check/check"
d820e00a
 	"golang.org/x/net/websocket"
9e37a046
 )
 
dc944ea7
 func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
f9a3558a
 	testRequires(c, DaemonIsLinux)
5c295460
 	out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat")
9e37a046
 
d69d4799
 	rwc, err := request.SockConn(time.Duration(10*time.Second), daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
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",
 	)
4f6f46a1
 	c.Assert(err, checker.IsNil)
9e37a046
 
 	ws, err := websocket.NewClient(config, rwc)
4f6f46a1
 	c.Assert(err, checker.IsNil)
9e37a046
 	defer ws.Close()
 
 	expected := []byte("hello")
 	actual := make([]byte, len(expected))
c7b2632d
 
 	outChan := make(chan error)
9e37a046
 	go func() {
85354fb7
 		_, err := io.ReadFull(ws, actual)
c7b2632d
 		outChan <- err
 		close(outChan)
9e37a046
 	}()
 
c7b2632d
 	inChan := make(chan error)
9e37a046
 	go func() {
c7b2632d
 		_, err := ws.Write(expected)
 		inChan <- err
 		close(inChan)
 	}()
 
 	select {
 	case err := <-inChan:
4f6f46a1
 		c.Assert(err, checker.IsNil)
c7b2632d
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout writing to ws")
 	}
9e37a046
 
c7b2632d
 	select {
 	case err := <-outChan:
4f6f46a1
 		c.Assert(err, checker.IsNil)
c7b2632d
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout reading from ws")
 	}
9e37a046
 
4f6f46a1
 	c.Assert(actual, checker.DeepEquals, expected, check.Commentf("Websocket didn't return the expected data"))
9e37a046
 }
88d32a61
 
 // regression gh14320
 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) {
f1ade82d
 	client, err := request.NewHTTPClient(daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
d69d4799
 	req, err := request.New(daemonHost(), "/containers/doesnotexist/attach", request.Method(http.MethodPost))
91e5bb95
 	resp, err := client.Do(req)
 	// connection will shutdown, err should be "persistent connection closed"
 	c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound)
4f304e72
 	content, err := request.ReadBody(resp.Body)
d69d4799
 	c.Assert(err, checker.IsNil)
91e5bb95
 	expected := "No such container: doesnotexist\r\n"
d69d4799
 	c.Assert(string(content), checker.Equals, expected)
88d32a61
 }
 
 func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) {
0fd5a654
 	res, body, err := request.Get("/containers/doesnotexist/attach/ws")
 	c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound)
 	c.Assert(err, checker.IsNil)
 	b, err := request.ReadBody(body)
4f6f46a1
 	c.Assert(err, checker.IsNil)
322e2a7d
 	expected := "No such container: doesnotexist"
0fd5a654
 	c.Assert(getErrorMessage(c, b), checker.Contains, expected)
88d32a61
 }
a8715ea2
 
 func (s *DockerSuite) TestPostContainersAttach(c *check.C) {
f9a3558a
 	testRequires(c, DaemonIsLinux)
a8715ea2
 
13364cd4
 	expectSuccess := func(conn net.Conn, br *bufio.Reader, stream string, tty bool) {
 		defer conn.Close()
 		expected := []byte("success")
 		_, err := conn.Write(expected)
4f6f46a1
 		c.Assert(err, checker.IsNil)
a8715ea2
 
13364cd4
 		conn.SetReadDeadline(time.Now().Add(time.Second))
 		lenHeader := 0
 		if !tty {
 			lenHeader = 8
 		}
 		actual := make([]byte, len(expected)+lenHeader)
 		_, err = io.ReadFull(br, actual)
4f6f46a1
 		c.Assert(err, checker.IsNil)
13364cd4
 		if !tty {
 			fdMap := map[string]byte{
 				"stdin":  0,
 				"stdout": 1,
 				"stderr": 2,
 			}
4f6f46a1
 			c.Assert(actual[0], checker.Equals, fdMap[stream])
13364cd4
 		}
4f6f46a1
 		c.Assert(actual[lenHeader:], checker.DeepEquals, expected, check.Commentf("Attach didn't return the expected data from %s", stream))
a8715ea2
 	}
 
13364cd4
 	expectTimeout := func(conn net.Conn, br *bufio.Reader, stream string) {
 		defer conn.Close()
 		_, err := conn.Write([]byte{'t'})
4f6f46a1
 		c.Assert(err, checker.IsNil)
a8715ea2
 
13364cd4
 		conn.SetReadDeadline(time.Now().Add(time.Second))
 		actual := make([]byte, 1)
 		_, err = io.ReadFull(br, actual)
 		opErr, ok := err.(*net.OpError)
4f6f46a1
 		c.Assert(ok, checker.Equals, true, check.Commentf("Error is expected to be *net.OpError, got %v", err))
 		c.Assert(opErr.Timeout(), checker.Equals, true, check.Commentf("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)
 	// Attach to the container's stdout stream.
d69d4799
 	conn, br, err := request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
13364cd4
 	// Check if the data from stdout can be received.
 	expectSuccess(conn, br, "stdout", false)
 	// Attach to the container's stderr stream.
d69d4799
 	conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
13364cd4
 	// Since the container only emits stdout, attaching to stderr should return nothing.
 	expectTimeout(conn, 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)
d69d4799
 	conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
13364cd4
 	expectSuccess(conn, br, "stderr", false)
d69d4799
 	conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
13364cd4
 	expectTimeout(conn, 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.
d69d4799
 	conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
13364cd4
 	expectSuccess(conn, br, "stdout", true)
a8715ea2
 
13364cd4
 	// Attach without stdout stream.
d69d4799
 	conn, br, err = request.SockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost())
4f6f46a1
 	c.Assert(err, checker.IsNil)
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.
 	expectTimeout(conn, br, "stdout")
fc8097f9
 
 	// Test the client API
 	// Make sure we don't see "hello" if Logs is false
 	client, err := client.NewEnvClient()
 	c.Assert(err, checker.IsNil)
0fd5a654
 	defer client.Close()
fc8097f9
 
 	cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat")
 	cid = strings.TrimSpace(cid)
 
 	attachOpts := types.ContainerAttachOptions{
 		Stream: true,
 		Stdin:  true,
 		Stdout: true,
 	}
 
 	resp, err := client.ContainerAttach(context.Background(), cid, attachOpts)
 	c.Assert(err, checker.IsNil)
 	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)
 	c.Assert(err, checker.IsNil)
 
 	defer resp.Conn.Close()
 	resp.Conn.SetReadDeadline(time.Now().Add(time.Second))
 
 	_, err = resp.Conn.Write([]byte("success"))
 	c.Assert(err, checker.IsNil)
 
 	actualStdout := new(bytes.Buffer)
 	actualStderr := new(bytes.Buffer)
 	stdcopy.StdCopy(actualStdout, actualStderr, resp.Reader)
 	c.Assert(actualStdout.Bytes(), checker.DeepEquals, []byte("hello\nsuccess"), check.Commentf("Attach didn't return the expected data from stdout"))
a8715ea2
 }