/
docker_exec.go
82 lines (71 loc) · 1.78 KB
/
docker_exec.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package watcher
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
)
type statusError struct {
StatusCode int
}
func (e statusError) Error() string {
return fmt.Sprintf("Code: %d", e.StatusCode)
}
// dockerExec is simplified version of docker exec without -it option.
func dockerExec(ctx context.Context, cli *client.Client, containerID string, cmd []string, stdout, stderr io.Writer) error {
if _, err := cli.ContainerInspect(ctx, containerID); err != nil {
return err
}
execConfig := types.ExecConfig{
Cmd: cmd,
AttachStderr: true,
AttachStdout: true,
}
respCreate, err := cli.ContainerExecCreate(ctx, containerID, execConfig)
if err != nil {
return err
}
execID := respCreate.ID
if execID == "" {
return errors.New("exec ID empty")
}
execStartCheck := types.ExecStartCheck{}
resp, err := cli.ContainerExecAttach(ctx, execID, execStartCheck)
if err != nil {
return err
}
defer resp.Close()
errC := make(chan error, 1)
go func() {
_, err := stdcopy.StdCopy(stdout, stderr, resp.Reader)
errC <- err
}()
select {
case err := <-errC:
if err != nil {
fmt.Fprintf(os.Stderr, "failed to docker exec, err=%v\n", err)
}
case <-ctx.Done():
fmt.Fprintf(os.Stderr, "docker exec canceled\n")
}
return getExecExitStatus(ctx, cli, execID)
}
func getExecExitStatus(ctx context.Context, cli *client.Client, execID string) error {
resp, err := cli.ContainerExecInspect(ctx, execID)
if err != nil {
// If we can't connect, then the daemon probably died.
if !client.IsErrConnectionFailed(err) {
return err
}
return statusError{StatusCode: -1}
}
status := resp.ExitCode
if status != 0 {
return statusError{StatusCode: status}
}
return nil
}