-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathdocker_image.go
594 lines (541 loc) · 16.8 KB
/
docker_image.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
package airflow
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strings"
"github.com/astronomer/astro-cli/pkg/util"
cliCommand "github.com/docker/cli/cli/command"
cliConfig "github.com/docker/cli/cli/config"
cliTypes "github.com/docker/cli/cli/config/types"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
log "github.com/sirupsen/logrus"
airflowTypes "github.com/astronomer/astro-cli/airflow/types"
"github.com/astronomer/astro-cli/config"
)
const (
EchoCmd = "echo"
pushingImagePrompt = "Pushing image to Astronomer registry"
astroRunContainer = "astro-run"
pullingImagePrompt = "Pulling image from Astronomer registry"
prefix = "Bearer "
)
var errGetImageLabel = errors.New("error getting image label")
type DockerImage struct {
imageName string
}
func DockerImageInit(image string) *DockerImage {
return &DockerImage{imageName: image}
}
func (d *DockerImage) Build(dockerfile string, buildConfig airflowTypes.ImageBuildConfig) error {
dockerCommand := config.CFG.DockerCommand.GetString()
if dockerfile == "" {
dockerfile = "Dockerfile"
}
err := os.Chdir(buildConfig.Path)
if err != nil {
return err
}
args := []string{
"build",
"-t",
d.imageName,
"-f",
dockerfile,
".",
}
if buildConfig.NoCache {
args = append(args, "--no-cache")
}
if len(buildConfig.TargetPlatforms) > 0 {
args = append(args, fmt.Sprintf("--platform=%s", strings.Join(buildConfig.TargetPlatforms, ",")))
}
// Build image
var stdout, stderr io.Writer
if buildConfig.Output {
stdout = os.Stdout
stderr = os.Stderr
} else {
stdout = nil
stderr = nil
}
err = cmdExec(dockerCommand, stdout, stderr, args...)
if err != nil {
return fmt.Errorf("command '%s build -t %s failed: %w", dockerCommand, d.imageName, err)
}
return err
}
func (d *DockerImage) Pytest(pytestFile, airflowHome, envFile, testHomeDirectory string, pytestArgs []string, htmlReport bool, buildConfig airflowTypes.ImageBuildConfig) (string, error) {
// delete container
dockerCommand := config.CFG.DockerCommand.GetString()
err := cmdExec(dockerCommand, nil, nil, "rm", "astro-pytest")
if err != nil {
log.Debug(err)
}
// Change to location of Dockerfile
err = os.Chdir(buildConfig.Path)
if err != nil {
return "", err
}
args := []string{
"create",
"-i",
"--name",
"astro-pytest",
}
fileExist, err := util.Exists(airflowHome + "/" + envFile)
if err != nil {
return "", err
}
if fileExist {
args = append(args, []string{"--env-file", envFile}...)
}
args = append(args, []string{d.imageName, "pytest", pytestFile}...)
args = append(args, pytestArgs...)
// run pytest image
var stdout, stderr io.Writer
if buildConfig.Output {
stdout = os.Stdout
stderr = os.Stderr
} else {
stdout = nil
stderr = nil
}
// create pytest container
docErr := cmdExec(dockerCommand, stdout, stderr, args...)
if docErr != nil {
return "", docErr
}
// cp DAGs folder
args = []string{
"cp",
airflowHome + "/dags",
"astro-pytest:/usr/local/airflow/",
}
docErr = cmdExec(dockerCommand, stdout, stderr, args...)
if docErr != nil {
return "", docErr
}
// cp .astro folder
// on some machine .astro is being docker ignored, but not
// on every machine, hence to keep behavior consistent
// copying the .astro folder explicitly
args = []string{
"cp",
airflowHome + "/.astro",
"astro-pytest:/usr/local/airflow/",
}
docErr = cmdExec(dockerCommand, stdout, stderr, args...)
if docErr != nil {
return "", docErr
}
// start pytest container
docErr = cmdExec(dockerCommand, stdout, stderr, []string{"start", "astro-pytest", "-a"}...)
if docErr != nil {
log.Debugf("Error starting pytest container: %s", docErr.Error())
}
// get exit code
args = []string{
"inspect",
"astro-pytest",
"--format='{{.State.ExitCode}}'",
}
var outb bytes.Buffer
err = cmdExec(dockerCommand, &outb, stderr, args...)
if err != nil {
log.Debug(err)
}
if htmlReport {
// Copy the dag-test-report.html file from the container to the destination folder
err = cmdExec(dockerCommand, nil, stderr, "cp", "astro-pytest:/usr/local/airflow/dag-test-report.html", "./"+testHomeDirectory)
if err != nil {
// Remove the temporary container
err2 := cmdExec(dockerCommand, nil, stderr, "rm", "astro-pytest")
if err2 != nil {
return outb.String(), err2
}
return outb.String(), err
}
}
// delete container
err = cmdExec(dockerCommand, nil, stderr, "rm", "astro-pytest")
if err != nil {
log.Debug(err)
}
return outb.String(), docErr
}
func (d *DockerImage) ConflictTest(workingDirectory, testHomeDirectory string, buildConfig airflowTypes.ImageBuildConfig) (string, error) {
dockerCommand := config.CFG.DockerCommand.GetString()
// delete container
err := cmdExec(dockerCommand, nil, nil, "rm", "astro-temp-container")
if err != nil {
log.Debug(err)
}
// Change to location of Dockerfile
err = os.Chdir(buildConfig.Path)
if err != nil {
return "", err
}
args := []string{
"build",
"-t",
"conflict-check:latest",
"-f",
"conflict-check.Dockerfile",
".",
}
// Create a buffer to capture the command output
var stdout, stderr bytes.Buffer
multiStdout := io.MultiWriter(&stdout, os.Stdout)
multiStderr := io.MultiWriter(&stderr, os.Stdout)
// Start the command execution
err = cmdExec(dockerCommand, multiStdout, multiStderr, args...)
if err != nil {
return "", err
}
// Get the exit code
exitCode := ""
if _, ok := err.(*exec.ExitError); ok {
// The command exited with a non-zero status
exitCode = parseExitCode(stderr.String())
} else if err != nil {
// An error occurred while running the command
return "", err
}
// Run a temporary container to copy the file from the image
err = cmdExec(dockerCommand, nil, nil, "create", "--name", "astro-temp-container", "conflict-check:latest")
if err != nil {
return exitCode, err
}
// Copy the result.txt file from the container to the destination folder
err1 := cmdExec(dockerCommand, nil, nil, "cp", "astro-temp-container:/usr/local/airflow/conflict-test-results.txt", "./"+testHomeDirectory)
if err1 != nil {
// Remove the temporary container
err = cmdExec(dockerCommand, nil, nil, "rm", "astro-temp-container")
if err != nil {
return exitCode, err
}
return exitCode, err1
}
// Remove the temporary container
err = cmdExec(dockerCommand, nil, nil, "rm", "astro-temp-container")
if err != nil {
return exitCode, err
}
return exitCode, nil
}
func parseExitCode(logs string) string {
re := regexp.MustCompile(`exit code: (\d+)`)
match := re.FindStringSubmatch(logs)
if len(match) > 1 {
return match[1]
}
return ""
}
func (d *DockerImage) CreatePipFreeze(altImageName, pipFreezeFile string) error {
dockerCommand := config.CFG.DockerCommand.GetString()
// Define the Docker command and arguments
imageName := d.imageName
if altImageName != "" {
imageName = altImageName
}
dockerArgs := []string{"run", "--rm", imageName, "pip", "freeze"}
// Create a file to store the command output
file, err := os.Create(pipFreezeFile)
if err != nil {
return err
}
defer file.Close()
// Run the Docker command
err = cmdExec(dockerCommand, file, os.Stderr, dockerArgs...)
if err != nil {
return err
}
return nil
}
func (d *DockerImage) Push(registry, username, token, remoteImage string) error {
dockerCommand := config.CFG.DockerCommand.GetString()
err := cmdExec(dockerCommand, nil, nil, "tag", d.imageName, remoteImage)
if err != nil {
return fmt.Errorf("command '%s tag %s %s' failed: %w", dockerCommand, d.imageName, remoteImage, err)
}
// Push image to registry
fmt.Println(pushingImagePrompt)
configFile := cliConfig.LoadDefaultConfigFile(os.Stderr)
authConfig, err := configFile.GetAuthConfig(registry)
if err != nil {
log.Debugf("Error reading credentials: %v", err)
return fmt.Errorf("error reading credentials: %w", err)
}
if username == "" && token == "" {
registryDomain := strings.Split(registry, "/")[0]
creds := configFile.GetCredentialsStore(registryDomain)
authConfig, err = creds.Get(registryDomain)
if err != nil {
log.Debugf("Error reading credentials for domain: %s from %s credentials store: %v", dockerCommand, registryDomain, err)
}
} else {
if username != "" {
authConfig.Username = username
}
authConfig.Password = token
authConfig.ServerAddress = registry
}
log.Debugf("Exec Push %s creds %v \n", dockerCommand, authConfig)
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
log.Debugf("Error setting up new Client ops %v", err)
// if NewClientWithOpt does not work use bash to run docker commands
return useBash(&authConfig, remoteImage)
}
cli.NegotiateAPIVersion(ctx)
buf, err := json.Marshal(authConfig)
if err != nil {
log.Debugf("Error negotiating api version: %v", err)
return err
}
encodedAuth := base64.URLEncoding.EncodeToString(buf)
responseBody, err := cli.ImagePush(ctx, remoteImage, types.ImagePushOptions{RegistryAuth: encodedAuth})
if err != nil {
log.Debugf("Error pushing image to docker: %v", err)
// if NewClientWithOpt does not work use bash to run docker commands
return useBash(&authConfig, remoteImage)
}
defer responseBody.Close()
err = displayJSONMessagesToStream(responseBody, nil)
if err != nil {
return useBash(&authConfig, remoteImage)
}
// Delete the image tags we just generated
err = cmdExec(dockerCommand, nil, nil, "rmi", remoteImage)
if err != nil {
return fmt.Errorf("command '%s rmi %s' failed: %w", dockerCommand, remoteImage, err)
}
return nil
}
func (d *DockerImage) Pull(registry, username, token, remoteImage string) error {
// Pulling image to registry
fmt.Println(pullingImagePrompt)
dockerCommand := config.CFG.DockerCommand.GetString()
var err error
if username != "" { // Case for cloud image push where we have both registry user & pass, for software login happens during `astro login` itself
pass := token
pass = strings.TrimPrefix(pass, prefix)
cmd := "echo \"" + pass + "\"" + " | " + dockerCommand + " login " + registry + " -u " + username + " --password-stdin"
err = cmdExec("bash", os.Stdout, os.Stderr, "-c", cmd) // This command will only work on machines that have bash. If users have issues we will revist
}
if err != nil {
return err
}
// docker pull <image>
err = cmdExec(dockerCommand, os.Stdout, os.Stderr, "pull", remoteImage)
if err != nil {
return err
}
return nil
}
var displayJSONMessagesToStream = func(responseBody io.ReadCloser, auxCallback func(jsonmessage.JSONMessage)) error {
out := cliCommand.NewOutStream(os.Stdout)
err := jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil)
if err != nil {
return err
}
return nil
}
func (d *DockerImage) GetLabel(altImageName, labelName string) (string, error) {
dockerCommand := config.CFG.DockerCommand.GetString()
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
labelFmt := fmt.Sprintf("{{ index .Config.Labels %q }}", labelName)
var label string
imageName := d.imageName
if altImageName != "" {
imageName = altImageName
}
err := cmdExec(dockerCommand, stdout, stderr, "inspect", "--format", labelFmt, imageName)
if err != nil {
return label, err
}
if execErr := stderr.String(); execErr != "" {
return label, fmt.Errorf("%s: %w", execErr, errGetImageLabel)
}
label = stdout.String()
label = strings.Trim(label, "\n")
return label, nil
}
func (d *DockerImage) DoesImageExist(image string) error {
dockerCommand := config.CFG.DockerCommand.GetString()
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
err := cmdExec(dockerCommand, stdout, stderr, "manifest", "inspect", image)
if err != nil {
return err
}
return nil
}
func (d *DockerImage) ListLabels() (map[string]string, error) {
dockerCommand := config.CFG.DockerCommand.GetString()
stdout := new(bytes.Buffer)
stderr := new(bytes.Buffer)
var labels map[string]string
err := cmdExec(dockerCommand, stdout, stderr, "inspect", "--format", "{{ json .Config.Labels }}", d.imageName)
if err != nil {
return labels, err
}
if execErr := stderr.String(); execErr != "" {
return labels, fmt.Errorf("%s: %w", execErr, errGetImageLabel)
}
err = json.Unmarshal(stdout.Bytes(), &labels)
if err != nil {
return labels, err
}
return labels, nil
}
func (d *DockerImage) TagLocalImage(localImage string) error {
dockerCommand := config.CFG.DockerCommand.GetString()
err := cmdExec(dockerCommand, nil, nil, "tag", localImage, d.imageName)
if err != nil {
return fmt.Errorf("command '%s tag %s %s' failed: %w", dockerCommand, localImage, d.imageName, err)
}
return nil
}
func (d *DockerImage) Run(dagID, envFile, settingsFile, containerName, dagFile, executionDate string, taskLogs bool) error {
dockerCommand := config.CFG.DockerCommand.GetString()
stdout := os.Stdout
stderr := os.Stderr
// delete container
err := cmdExec(dockerCommand, nil, nil, "rm", astroRunContainer)
if err != nil {
log.Debug(err)
}
var args []string
if containerName != "" {
args = []string{
"exec",
"-t",
containerName,
}
}
// check if settings file exists
settingsFileExist, err := util.Exists("./" + settingsFile)
if err != nil {
log.Debug(err)
}
// docker exec
if containerName == "" {
args = []string{
"run",
"-t",
"--name",
astroRunContainer,
"-v",
config.WorkingPath + "/dags:/usr/local/airflow/dags:rw",
"-v",
config.WorkingPath + "/plugins:/usr/local/airflow/plugins:rw",
"-v",
config.WorkingPath + "/include:/usr/local/airflow/include:rw",
}
// if settings file exists append it to args
if settingsFileExist {
args = append(args, []string{"-v", config.WorkingPath + "/" + settingsFile + ":/usr/local/airflow/" + settingsFile}...)
}
// if env file exists append it to args
fileExist, err := util.Exists(config.WorkingPath + "/" + envFile)
if err != nil {
log.Debug(err)
}
if fileExist {
args = append(args, []string{"--env-file", envFile}...)
}
args = append(args, []string{d.imageName}...)
}
if !strings.Contains(dagFile, "dags/") {
dagFile = "./dags/" + dagFile
}
cmdArgs := []string{
"run_dag",
dagFile,
dagID,
}
// settings file exists append it to args
if settingsFileExist {
cmdArgs = append(cmdArgs, []string{"./" + settingsFile}...)
}
if executionDate != "" {
cmdArgs = append(cmdArgs, []string{"--execution-date", executionDate}...)
}
if taskLogs {
cmdArgs = append(cmdArgs, []string{"--verbose"}...)
}
args = append(args, cmdArgs...)
fmt.Println("\nStarting a DAG run for " + dagID + "...")
fmt.Println("\nLoading DAGs...")
log.Debug("args passed to docker command:")
log.Debug(args)
cmdErr := cmdExec(dockerCommand, stdout, stderr, args...)
// add back later fmt.Println("\nSee the output of this command for errors. To view task logs, use the '--task-logs' flag.")
if cmdErr != nil {
log.Debug(cmdErr)
fmt.Println("\nSee the output of this command for errors.")
fmt.Println("If you are having an issue with loading your settings file make sure both the 'variables' and 'connections' fields exist and that there are no yaml syntax errors.")
fmt.Println("If you are getting a missing `airflow_settings.yaml` or `astro-run-dag` error try restarting airflow with `astro dev restart`.")
}
if containerName == "" {
// delete container
err = cmdExec(dockerCommand, nil, nil, "rm", astroRunContainer)
if err != nil {
log.Debug(err)
}
}
return cmdErr
}
// Exec executes a docker command
var cmdExec = func(cmd string, stdout, stderr io.Writer, args ...string) error {
_, lookErr := exec.LookPath(cmd)
if lookErr != nil {
return fmt.Errorf("failed to find the %s command: %w", cmd, lookErr)
}
execCMD := exec.Command(cmd, args...)
execCMD.Stdin = os.Stdin
execCMD.Stdout = stdout
execCMD.Stderr = stderr
if cmdErr := execCMD.Run(); cmdErr != nil {
return fmt.Errorf("failed to execute cmd: %w", cmdErr)
}
return nil
}
// When login and push do not work use bash to run docker commands, this function is for users using colima
func useBash(authConfig *cliTypes.AuthConfig, image string) error {
dockerCommand := config.CFG.DockerCommand.GetString()
var err error
if authConfig.Username != "" { // Case for cloud image push where we have both registry user & pass, for software login happens during `astro login` itself
pass := authConfig.Password
pass = strings.TrimPrefix(pass, prefix)
cmd := "echo \"" + pass + "\"" + " | " + dockerCommand + " login " + authConfig.ServerAddress + " -u " + authConfig.Username + " --password-stdin"
err = cmdExec("bash", os.Stdout, os.Stderr, "-c", cmd) // This command will only work on machines that have bash. If users have issues we will revist
}
if err != nil {
return err
}
// docker push <image>
err = cmdExec(dockerCommand, os.Stdout, os.Stderr, "push", image)
if err != nil {
return err
}
// Delete the image tags we just generated
err = cmdExec(dockerCommand, nil, nil, "rmi", image)
if err != nil {
return fmt.Errorf("command '%s rmi %s' failed: %w", dockerCommand, image, err)
}
return nil
}