/
exec.go
198 lines (179 loc) · 4.94 KB
/
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package confort
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"github.com/daichitakahashi/confort/internal/logging"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/lestrrat-go/option"
)
type ContainerExec struct {
c *Container
cmd []string
workingDir string
env []string
cli *client.Client
execID string
Stdout io.Writer
Stderr io.Writer
}
type (
execIdent interface{ exec() }
ExecOption interface {
option.Interface
execIdent
}
identOptionExecWorkingDir struct{}
identOptionExecEnv struct{}
execOption struct {
option.Interface
execIdent
}
)
// WithExecWorkingDir specifies working directory inside the container.
func WithExecWorkingDir(s string) ExecOption {
return execOption{
Interface: option.New(identOptionExecWorkingDir{}, s),
}
}
// WithExecEnv specifies environment variables using in the container.
func WithExecEnv(kv map[string]string) ExecOption {
list := make([]string, 0, len(kv))
for k, v := range kv {
list = append(list, fmt.Sprintf("%s=%s", k, v))
}
return execOption{
Interface: option.New(identOptionExecEnv{}, list),
}
}
// CreateExec creates new ContainerExec that executes the specified command on the container.
func (c *Container) CreateExec(ctx context.Context, cmd []string, opts ...ExecOption) (*ContainerExec, error) {
var (
workingDir string
execEnv []string
)
for _, opt := range opts {
switch opt.Ident() {
case identOptionExecWorkingDir{}:
workingDir = opt.Value().(string)
case identOptionExecEnv{}:
execEnv = opt.Value().([]string)
}
}
if _, err := c.cft.cli.ContainerInspect(ctx, c.id); err != nil {
return nil, err
}
return &ContainerExec{
c: c,
cmd: cmd,
workingDir: workingDir,
env: execEnv,
cli: c.cft.cli,
}, nil
}
// Start executes the command but does not wait for it to complete.
func (e *ContainerExec) Start(ctx context.Context) error {
if e.execID != "" {
return errors.New("confort: exec: already started")
}
logging.Debugf("exec on container %q: %v", e.c.name, e.cmd)
execConfig := types.ExecConfig{
Cmd: e.cmd,
WorkingDir: e.workingDir,
Env: e.env,
AttachStdout: e.Stdout != nil,
AttachStderr: e.Stderr != nil,
}
// When both stdout and stderr haven't attached, ContainerExecCreate behaves like a detached mode.
// So, to wait execution done, make stdout attached.
if !execConfig.AttachStdout && !execConfig.AttachStderr {
execConfig.AttachStdout = true
}
resp, err := e.cli.ContainerExecCreate(ctx, e.c.id, execConfig)
if err != nil {
return err
}
e.execID = resp.ID
return nil
}
type ExitError struct {
ExitCode int
}
func (e *ExitError) Error() string {
return fmt.Sprintf("confort: exec: exit status %d", e.ExitCode)
}
// Wait waits for the specified command to exit and waits for copying from stdout or stderr to complete.
// The command must have been started by Start.
// The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.
// If the command fails to run or doesn't complete successfully, the error is of type *ExitError.
func (e *ContainerExec) Wait(ctx context.Context) error {
if e.execID == "" {
return errors.New("confort: exec: not started")
}
hijackedResp, err := e.cli.ContainerExecAttach(ctx, e.execID, types.ExecStartCheck{})
if err != nil {
return err
}
defer hijackedResp.Close()
var (
stdout = io.Discard
stderr = io.Discard
)
if e.Stdout != nil {
stdout = e.Stdout
}
if e.Stderr != nil {
stderr = e.Stderr
}
_, err = stdcopy.StdCopy(stdout, stderr, hijackedResp.Reader)
if err != nil {
return err
}
info, err := e.cli.ContainerExecInspect(ctx, e.execID)
if err != nil {
return err
}
if info.ExitCode != 0 {
return &ExitError{
ExitCode: info.ExitCode,
}
}
return nil
}
// Run starts the specified command and waits for it to complete.
func (e *ContainerExec) Run(ctx context.Context) error {
err := e.Start(ctx)
if err != nil {
return err
}
return e.Wait(ctx)
}
// Output runs the command and returns its standard output.
func (e *ContainerExec) Output(ctx context.Context) ([]byte, error) {
if e.Stdout != nil {
return nil, errors.New("confort: exec: Stdout already set")
}
buf := bytes.NewBuffer(nil)
e.Stdout = buf
err := e.Run(ctx)
return buf.Bytes(), err
}
// CombinedOutput runs the command and returns its combined standard output and standard error.
// Because the difference of stdout and stderr, an order of the lines of the combined output is not preserved.
func (e *ContainerExec) CombinedOutput(ctx context.Context) ([]byte, error) {
if e.Stdout != nil {
return nil, errors.New("confort: exec: Stdout already set")
}
if e.Stderr != nil {
return nil, errors.New("confort: exec: Stderr already set")
}
buf := bytes.NewBuffer(nil)
e.Stdout = buf
e.Stderr = buf
err := e.Run(ctx)
return buf.Bytes(), err
}