-
Notifications
You must be signed in to change notification settings - Fork 1
/
container.go
62 lines (55 loc) · 1.24 KB
/
container.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package execcmd
import (
"context"
"io"
"github.com/docker/docker/api/types"
dockerclient "github.com/docker/docker/client"
)
// ExecCmdContainer executes a command in a Docker container.
func ExecCmdContainer(
ctx context.Context,
dockerClient *dockerclient.Client,
containerID, userID string,
stdIn io.Reader, stdOut, stdErr io.Writer,
cmd string, args ...string,
) error {
in := NewInStream(stdIn, false)
out := NewOutStream(stdOut)
errOut := NewOutStream(stdErr)
inStrm, _ := in.(*InStream)
useTty := inStrm != nil && inStrm.IsTty()
cmds := append([]string{cmd}, args...)
execCreate, err := dockerClient.ContainerExecCreate(ctx, containerID, types.ExecConfig{
Tty: useTty,
User: userID,
Cmd: cmds,
// Env: ...,
AttachStdin: stdIn != nil,
AttachStdout: stdOut != nil,
AttachStderr: stdErr != nil,
})
if err != nil {
return err
}
conn, err := dockerClient.ContainerExecAttach(ctx, execCreate.ID, types.ExecStartCheck{
Tty: useTty,
})
if err != nil {
return err
}
defer conn.Close()
strm := &HijackedIOStreamer{
Resp: conn,
Tty: useTty,
}
if in != nil {
strm.InputStream = in
}
if out != nil {
strm.OutputStream = out
}
if errOut != nil {
strm.ErrorStream = errOut
}
return strm.Stream(ctx)
}