-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathcontroller.go
More file actions
393 lines (343 loc) · 10.4 KB
/
controller.go
File metadata and controls
393 lines (343 loc) · 10.4 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
package container
import (
"bufio"
"bytes"
"context"
"io"
"net/netip"
"path/filepath"
"strconv"
"strings"
"github.com/moby/moby/api/pkg/stdcopy"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/client"
specs "github.com/opencontainers/image-spec/specs-go/v1"
)
type Controller struct {
cli *client.Client
}
// NewController creates a new Controller struct, which is used to interact
// with a container runtime engine (e.g. Docker or Podman etc.). It initializes
// engine client by calling client.NewClientWithOpts(client.FromEnv) and
// setting the cli field of the Controller struct to the result.
// The Controller struct is then returned.
func NewController() (c *Controller) {
var err error
c = new(Controller)
c.cli, err = client.NewClientWithOpts(
client.FromEnv,
client.WithVersion("1.45"),
)
checkErr(err)
return
}
// EnsureImage creates a new instance of the Controller struct and initializes
// the container engine client by calling client.NewClientWithOpts() with
// the client.FromEnv option. It returns the Controller instance and an error
// if one occurred while creating the client. The Controller struct has a
// method EnsureImage() which pulls an image with the given name from
// a registry and logs the output to the console.
func (c Controller) EnsureImage(imageName string) (err error) {
var reader io.ReadCloser
trace("Running ImagePull for image %s", imageName)
reader, err = c.cli.ImagePull(context.Background(), imageName, client.ImagePullOptions{})
if reader != nil {
defer func() {
checkErr(reader.Close())
}()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
trace(scanner.Text())
}
}
return
}
// ContainerRun creates a new container using the provided image and env values
// and binds it to the specified port number. It then starts the container and returns
// the ID of the container.
func (c Controller) ContainerRun(
image string,
env []string,
port int,
name string,
hostname string,
architecture string,
os string,
command []string,
unitTestFailure bool,
) string {
hostConfig := &container.HostConfig{
// On Linux Docker Engine, host.docker.internal is not set by default
// (Docker Desktop sets it automatically). Add it so containers can
// reach host services, e.g. for bak-file restore from a local HTTP server.
ExtraHosts: []string{"host.docker.internal:host-gateway"},
PortBindings: network.PortMap{
network.MustParsePort("1433/tcp"): []network.PortBinding{
{
HostIP: netip.MustParseAddr("0.0.0.0"),
HostPort: strconv.Itoa(port),
},
},
},
}
platform := specs.Platform{
Architecture: architecture,
OS: os,
}
resp, err := c.cli.ContainerCreate(context.Background(), client.ContainerCreateOptions{
Config: &container.Config{
Tty: true,
Image: image,
Cmd: command,
Env: env,
Hostname: hostname,
},
HostConfig: hostConfig,
Platform: &platform,
Name: name,
})
checkErr(err)
_, err = c.cli.ContainerStart(
context.Background(),
resp.ID,
client.ContainerStartOptions{},
)
if err != nil || unitTestFailure {
// Remove the container, because we haven't persisted to config yet, so
// uninstall won't work yet
if resp.ID != "" {
err := c.ContainerRemove(resp.ID)
checkErr(err)
}
}
checkErr(err)
return resp.ID
}
// ContainerWaitForLogEntry is used to wait for a specific string to be written
// to the logs of a container with the given ID. The function takes in the ID
// of the container and the string to look for in the logs. It creates a reader
// to stream the logs from the container, and scans the logs line by line until
// it finds the specified string. Once the string is found, the function breaks
// out of the loop and returns.
//
// This function is useful for waiting until a specific event has occurred in the
// container (e.g. a server has started up) before continuing with other operations.
func (c Controller) ContainerWaitForLogEntry(id string, text string) {
options := client.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: false,
Since: "",
Until: "",
Timestamps: false,
Follow: true,
Tail: "",
Details: false,
}
// Wait for server to start up
reader, err := c.cli.ContainerLogs(context.Background(), id, options)
checkErr(err)
defer func() {
err := reader.Close()
checkErr(err)
}()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
trace("ERRORLOG: " + scanner.Text())
if strings.Contains(scanner.Text(), text) {
break
}
}
}
// ContainerStop stops the container with the given ID. The function returns
// an error if there is an issue stopping the container.
func (c Controller) ContainerStop(id string) (err error) {
if id == "" {
panic("Must pass in non-empty id")
}
_, err = c.cli.ContainerStop(context.Background(), id, client.ContainerStopOptions{})
return
}
// ContainerStart starts the container with the given ID. The function returns
// an error if there is an issue starting the container.
func (c Controller) ContainerStart(id string) (err error) {
if id == "" {
panic("Must pass in non-empty id")
}
_, err = c.cli.ContainerStart(context.Background(), id, client.ContainerStartOptions{})
return
}
// ContainerFiles returns a list of files matching a specified pattern within
// a given container. It takes an id argument, which specifies the ID of the
// container to search, and a filespec argument, which is a string pattern used
// to match files within the container. The function returns a []string slice
// containing the names of all files that match the specified pattern.
func (c Controller) ContainerFiles(id string, filespec string) (files []string) {
if id == "" {
panic("Must pass in non-empty id")
}
if filespec == "" {
panic("Must pass in non-empty filespec")
}
cmd := []string{"find", "/", "-iname", filespec}
response, err := c.cli.ExecCreate(
context.Background(),
id,
client.ExecCreateOptions{
AttachStderr: false,
AttachStdout: true,
Cmd: cmd,
},
)
checkErr(err)
r, err := c.cli.ExecAttach(
context.Background(),
response.ID,
client.ExecAttachOptions{},
)
checkErr(err)
defer r.Close()
// read the output
var outBuf, errBuf bytes.Buffer
outputDone := make(chan error)
go func() {
// StdCopy de-multiplexes the stream into two buffers
_, err = stdcopy.StdCopy(&outBuf, &errBuf, r.Reader)
outputDone <- err
}()
err = <-outputDone
checkErr(err)
stdout, err := io.ReadAll(&outBuf)
checkErr(err)
return strings.Split(string(stdout), "\n")
}
func (c Controller) DownloadFile(id string, src string, destFolder string) {
if id == "" {
panic("Must pass in non-empty id")
}
if src == "" {
panic("Must pass in non-empty src")
}
if destFolder == "" {
panic("Must pass in non-empty destFolder")
}
_, file := filepath.Split(src)
if file == "" {
panic("src URL has no filename: " + src)
}
dest := destFolder + "/" + file // not using filepath.Join here, this is in the *nix container. always /
cmd := []string{"mkdir", "-p", destFolder}
_, _, mkdirExit := c.runCmdInContainer(id, cmd)
if mkdirExit != 0 {
panic("mkdir failed for " + destFolder)
}
cmd = []string{"wget", "-O", dest, src}
_, stderr, exitCode := c.runCmdInContainer(id, cmd)
if exitCode != 0 {
msg := "download failed: " + src
if len(stderr) > 0 {
msg += "\nwget output: " + string(stderr)
}
panic(msg)
}
}
func (c Controller) runCmdInContainer(id string, cmd []string) ([]byte, []byte, int) {
trace("Running command in container: " + strings.Join(cmd, " "))
response, err := c.cli.ExecCreate(
context.Background(),
id,
client.ExecCreateOptions{
AttachStderr: true,
AttachStdout: true,
Cmd: cmd,
},
)
checkErr(err)
r, err := c.cli.ExecAttach(
context.Background(),
response.ID,
client.ExecAttachOptions{},
)
checkErr(err)
defer r.Close()
// read the output
var outBuf, errBuf bytes.Buffer
outputDone := make(chan error)
go func() {
// StdCopy de-multiplexes the stream into two buffers
_, err = stdcopy.StdCopy(&outBuf, &errBuf, r.Reader)
outputDone <- err
}()
err = <-outputDone
checkErr(err)
stdout, err := io.ReadAll(&outBuf)
checkErr(err)
stderr, err := io.ReadAll(&errBuf)
checkErr(err)
trace("Stdout: " + string(stdout))
trace("Stderr: " + string(stderr))
// ExecInspect may rarely return Running:true after output is drained
// (moby/moby#42408). In practice the race window is negligible for
// short-lived commands like mkdir and wget.
inspect, err := c.cli.ExecInspect(
context.Background(),
response.ID,
client.ExecInspectOptions{},
)
checkErr(err)
return stdout, stderr, inspect.ExitCode
}
// ContainerRunning returns true if the container with the given ID is running.
// It returns false if the container is not running or if there is an issue
// getting the container's status.
func (c Controller) ContainerRunning(id string) (running bool) {
if id == "" {
panic("Must pass in non-empty id")
}
resp, err := c.cli.ContainerInspect(context.Background(), id, client.ContainerInspectOptions{})
checkErr(err)
if resp.Container.State != nil {
running = resp.Container.State.Running
}
return
}
// ContainerExists checks if a container with the given ID exists in the system.
// It does this by using the container runtime API to list all containers and
// filtering by the given ID. If a container with the given ID is found, it
// returns true; otherwise, it returns false.
func (c Controller) ContainerExists(id string) (exists bool) {
f := make(client.Filters).Add(
"id", id,
)
resp, err := c.cli.ContainerList(
context.Background(),
client.ContainerListOptions{Filters: f},
)
checkErr(err)
if len(resp.Items) > 0 {
trace("%v", resp.Items)
containerStatus := strings.Split(resp.Items[0].Status, " ")
status := containerStatus[0]
trace("%v", status)
exists = true
}
return
}
// ContainerRemove removes the container with the specified ID using the
// container runtime API. The function takes the ID of the container to be
// removed as an input argument, and returns an error if one occurs during
// the removal process.
func (c Controller) ContainerRemove(id string) (err error) {
if id == "" {
panic("Must pass in non-empty id")
}
options := client.ContainerRemoveOptions{
RemoveVolumes: false,
RemoveLinks: false,
Force: false,
}
_, err = c.cli.ContainerRemove(context.Background(), id, options)
return
}