File: docker-container.go

package info (click to toggle)
docker-buildx 0.13.1%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,356 kB
  • sloc: sh: 299; makefile: 87
file content (98 lines) | stat: -rw-r--r-- 2,068 bytes parent folder | download
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
package workers

import (
	"context"
	"os"
	"os/exec"
	"path/filepath"
	"sync"

	"github.com/moby/buildkit/identity"
	"github.com/moby/buildkit/util/testutil/integration"
	"github.com/pkg/errors"
)

func InitDockerContainerWorker() {
	integration.Register(&containerWorker{
		id: "docker-container",
	})
}

type containerWorker struct {
	id string

	unsupported []string

	docker      integration.Backend
	dockerClose func() error
	dockerErr   error
	dockerOnce  sync.Once
}

func (w *containerWorker) Name() string {
	return w.id
}

func (w *containerWorker) Rootless() bool {
	return false
}

func (w *containerWorker) NetNSDetached() bool {
	return false
}

func (w *containerWorker) New(ctx context.Context, cfg *integration.BackendConfig) (integration.Backend, func() error, error) {
	w.dockerOnce.Do(func() {
		w.docker, w.dockerClose, w.dockerErr = dockerWorker{id: w.id}.New(ctx, cfg)
	})
	if w.dockerErr != nil {
		return w.docker, w.dockerClose, w.dockerErr
	}

	cfgfile, err := integration.WriteConfig(cfg.DaemonConfig)
	if err != nil {
		return nil, nil, err
	}
	defer os.RemoveAll(filepath.Dir(cfgfile))
	name := "integration-container-" + identity.NewID()
	cmd := exec.Command("buildx", "create",
		"--bootstrap",
		"--name="+name,
		"--buildkitd-config="+cfgfile,
		"--driver=docker-container",
		"--driver-opt=network=host",
	)
	cmd.Env = append(
		os.Environ(),
		"BUILDX_CONFIG=/tmp/buildx-"+name,
		"DOCKER_CONTEXT="+w.docker.DockerAddress(),
	)
	if err := cmd.Run(); err != nil {
		return nil, nil, errors.Wrapf(err, "failed to create buildx instance %s", name)
	}

	cl := func() error {
		cmd := exec.Command("buildx", "rm", "-f", name)
		return cmd.Run()
	}

	return &backend{
		context:             w.docker.DockerAddress(),
		builder:             name,
		unsupportedFeatures: w.unsupported,
	}, cl, nil
}

func (w *containerWorker) Close() error {
	if c := w.dockerClose; c != nil {
		return c()
	}

	// reset the worker to be ready to go again
	w.docker = nil
	w.dockerClose = nil
	w.dockerErr = nil
	w.dockerOnce = sync.Once{}

	return nil
}