This repository has been archived by the owner on May 19, 2023. It is now read-only.
/
container.go
351 lines (292 loc) · 8 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
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package docker
import (
"errors"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/pkg/term"
"io"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
const (
// ContainerStopTimeout constant represents how long Docker Engine
// will wait for container before stopping it
ContainerStopTimeout = time.Millisecond * 10
// ContainerStateRunning constants defines that container is running
ContainerStateRunning = "running"
// ContainerStateCreated constants defines that container is created
ContainerStateCreated = "created"
// ContainerStateExited constants defines that container has exited
ContainerStateExited = "exited"
// ContainerStateRestarting constants defines that container is restarting
ContainerStateRestarting = "restarting"
// ContainerStatePaused constants defines that container is paused
ContainerStatePaused = "paused"
// ContainerStateDead constants defines that container is dead
ContainerStateDead = "dead"
)
// ContainerCreateArgs struct represents arguments
// passed to ContainerCreate().
type ContainerCreateArgs struct {
Mounts []mount.Mount
Image string
Name string
User string
}
// ContainerExecArgs struct represents arguments
// passed to ContainerExec().
type ContainerExecArgs struct {
Interactive bool
Name string
Cmd string
WorkDir string
AsRoot bool
Skip bool
Network bool
}
// IsContainerCreated function checks if container is created
// or simply just exists.
func (docker *Docker) IsContainerCreated(name string) (bool, error) {
list, err := docker.cli.ContainerList(docker.ctx, types.ContainerListOptions{All: true})
if err != nil {
return false, err
}
for i := range list {
for j := range list[i].Names {
if list[i].Names[j] == "/"+name {
return true, nil
}
}
}
return false, nil
}
// IsContainerStarted function checks
// if container's state == ContainerStateRunning.
func (docker *Docker) IsContainerStarted(name string) (bool, error) {
list, err := docker.cli.ContainerList(docker.ctx, types.ContainerListOptions{All: true})
if err != nil {
return false, err
}
for i := range list {
for j := range list[i].Names {
if list[i].Names[j] == "/"+name {
if list[i].State == ContainerStateRunning {
return true, nil
}
}
}
}
return false, nil
}
// IsContainerStopped function checks
// if container's state != ContainerStateRunning.
func (docker *Docker) IsContainerStopped(name string) (bool, error) {
list, err := docker.cli.ContainerList(docker.ctx, types.ContainerListOptions{All: true})
if err != nil {
return false, err
}
for i := range list {
for j := range list[i].Names {
if list[i].Names[j] == "/"+name {
if list[i].State == ContainerStateRunning {
return false, nil
}
}
}
}
return true, nil
}
// ContainerCreate function creates container.
//
// It's up to the caller to make to-be-mounted directories on host.
func (docker *Docker) ContainerCreate(args ContainerCreateArgs) error {
hostConfig := &container.HostConfig{
Mounts: args.Mounts,
}
config := &container.Config{
Image: args.Image,
User: args.User,
}
_, err := docker.cli.ContainerCreate(docker.ctx, config, hostConfig, nil, args.Name)
if err != nil {
return err
}
return nil
}
// ContainerStart function starts container, just that.
func (docker *Docker) ContainerStart(name string) error {
options := types.ContainerStartOptions{}
return docker.cli.ContainerStart(docker.ctx, name, options)
}
// ContainerStop function stops container, just that.
//
// It utilizes ContainerStopTimeout constant.
func (docker *Docker) ContainerStop(name string) error {
timeout := ContainerStopTimeout
return docker.cli.ContainerStop(docker.ctx, name, &timeout)
}
// ContainerRemove function removes container, just that.
func (docker *Docker) ContainerRemove(name string) error {
options := types.ContainerRemoveOptions{}
return docker.cli.ContainerRemove(docker.ctx, name, options)
}
// ContainerMounts returns mounts of created container.
func (docker *Docker) ContainerMounts(name string) ([]mount.Mount, error) {
inspect, err := docker.cli.ContainerInspect(docker.ctx, name)
if err != nil {
return nil, err
}
mounts := make([]mount.Mount, 0)
for _, v := range inspect.Mounts {
mnt := mount.Mount{
Source: v.Source,
Target: v.Destination,
Type: v.Type,
ReadOnly: !v.RW,
}
mounts = append(mounts, mnt)
}
return mounts, nil
}
// ContainerExec function executes a command in running container.
//
// Command is executed in bash shell by default.
//
// Command can be executed as root.
//
// Command can be executed interactively.
//
// Command can be empty, in that case just bash is executed.
func (docker *Docker) ContainerExec(args ContainerExecArgs) error {
config := types.ExecConfig{
Cmd: []string{"bash"},
WorkingDir: args.WorkDir,
AttachStdin: args.Interactive,
AttachStdout: true,
AttachStderr: true,
Tty: true,
}
check := types.ExecStartCheck{
Tty: true,
Detach: false,
}
if args.Skip {
return nil
}
if args.AsRoot {
config.User = "root"
}
if args.Cmd != "" {
config.Cmd = append(config.Cmd, "-c", args.Cmd)
}
err := docker.ContainerNetwork(args.Name, args.Network)
if err != nil {
return err
}
response, err := docker.cli.ContainerExecCreate(docker.ctx, args.Name, config)
if err != nil {
return err
}
hijack, err := docker.cli.ContainerExecAttach(docker.ctx, response.ID, check)
if err != nil {
return err
}
if args.Interactive {
fd := os.Stdin.Fd()
if term.IsTerminal(fd) {
oldState, err := term.MakeRaw(fd)
if err != nil {
return err
}
defer term.RestoreTerminal(fd, oldState)
err = docker.ContainerExecResize(response.ID, fd)
if err != nil {
return err
}
go docker.resizeIfChanged(response.ID, fd)
go io.Copy(hijack.Conn, os.Stdin)
}
}
io.Copy(os.Stdout, hijack.Conn)
hijack.Close()
if !args.Interactive {
inspect, err := docker.cli.ContainerExecInspect(docker.ctx, response.ID)
if err != nil {
return err
}
if inspect.ExitCode != 0 {
return errors.New("command exited with non-zero status")
}
}
return nil
}
func (docker *Docker) resizeIfChanged(execID string, fd uintptr) {
channel := make(chan os.Signal)
signal.Notify(channel, syscall.SIGWINCH)
for {
<-channel
docker.ContainerExecResize(execID, fd)
}
}
// ContainerExecResize function resizes TTY for exec process.
func (docker *Docker) ContainerExecResize(execID string, fd uintptr) error {
winSize, err := term.GetWinsize(fd)
if err != nil {
return err
}
options := types.ResizeOptions{
Height: uint(winSize.Height),
Width: uint(winSize.Width),
}
err = docker.cli.ContainerExecResize(docker.ctx, execID, options)
if err != nil {
return err
}
return nil
}
// ContainerNetwork checks if container is connected to network
// and then connects it or disconnects per caller request.
func (docker *Docker) ContainerNetwork(name string, wantConnected bool) error {
network := "bridge"
gotConnected := false
inspect, err := docker.cli.ContainerInspect(docker.ctx, name)
if err != nil {
return err
}
for net := range inspect.NetworkSettings.Networks {
if net == network {
gotConnected = true
}
}
if wantConnected && !gotConnected {
return docker.cli.NetworkConnect(docker.ctx, network, name, nil)
}
if !wantConnected && gotConnected {
return docker.cli.NetworkDisconnect(docker.ctx, network, name, false)
}
return nil
}
// ContainerList returns a list of containers that match passed criteria.
func (docker *Docker) ContainerList(prefix string) ([]string, error) {
containers := make([]string, 0)
options := types.ContainerListOptions{
All: true,
}
list, err := docker.cli.ContainerList(docker.ctx, options)
if err != nil {
return nil, err
}
for _, v := range list {
for _, name := range v.Names {
name = strings.TrimPrefix(name, "/")
if strings.HasPrefix(name, prefix) {
containers = append(containers, name)
}
}
}
return containers, nil
}