-
Notifications
You must be signed in to change notification settings - Fork 559
/
buildkitutil.go
233 lines (214 loc) · 6.76 KB
/
buildkitutil.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
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Portions from https://github.com/docker/cli/blob/v20.10.9/cli/command/image/build/context.go
Copyright (C) Docker authors.
Licensed under the Apache License, Version 2.0
NOTICE: https://github.com/docker/cli/blob/v20.10.9/NOTICE
*/
package buildkitutil
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/containerd/log"
"github.com/containerd/nerdctl/pkg/rootlessutil"
)
const (
// DefaultDockerfileName is the Default filename, read by nerdctl build
DefaultDockerfileName string = "Dockerfile"
ContainerfileName string = "Containerfile"
TempDockerfileName string = "docker-build-tempdockerfile-"
)
func BuildctlBinary() (string, error) {
return exec.LookPath("buildctl")
}
func BuildctlBaseArgs(buildkitHost string) []string {
return []string{"--addr=" + buildkitHost}
}
func GetBuildkitHost(namespace string) (string, error) {
if namespace == "" {
return "", fmt.Errorf("namespace must be specified")
}
// Try candidate locations of the current containerd namespace.
run := "/run/"
if rootlessutil.IsRootless() {
var err error
run, err = rootlessutil.XDGRuntimeDir()
if err != nil {
log.L.Warn(err)
run = fmt.Sprintf("/run/user/%d", rootlessutil.ParentEUID())
}
}
var hostRel []string
if namespace != "default" {
hostRel = append(hostRel, fmt.Sprintf("buildkit-%s/buildkitd.sock", namespace))
}
hostRel = append(hostRel, "buildkit-default/buildkitd.sock", "buildkit/buildkitd.sock")
var errs []error //nolint:prealloc
for _, p := range hostRel {
log.L.Debugf("Choosing the buildkit host %q, candidates=%v (in %q)", p, hostRel, run)
buildkitHost := "unix://" + filepath.Join(run, p)
_, err := pingBKDaemon(buildkitHost)
if err == nil {
log.L.Debugf("Chosen buildkit host %q", buildkitHost)
return buildkitHost, nil
}
errs = append(errs, fmt.Errorf("failed to ping to host %s: %w", buildkitHost, err))
}
allErr := errors.Join(errs...)
log.L.WithError(allErr).Error(getHint())
return "", fmt.Errorf("no buildkit host is available, tried %d candidates: %w", len(hostRel), allErr)
}
func GetWorkerLabels(buildkitHost string) (labels map[string]string, _ error) {
buildctlBinary, err := BuildctlBinary()
if err != nil {
return nil, err
}
args := BuildctlBaseArgs(buildkitHost)
args = append(args, "debug", "workers", "--format", "{{json .}}")
buildctlCheckCmd := exec.Command(buildctlBinary, args...)
buildctlCheckCmd.Env = os.Environ()
out, err := buildctlCheckCmd.Output()
if err != nil {
return nil, err
}
var workers []json.RawMessage
if err := json.Unmarshal(out, &workers); err != nil {
return nil, err
}
if len(workers) == 0 {
return nil, fmt.Errorf("no worker available")
}
metadata := map[string]json.RawMessage{}
if err := json.Unmarshal(workers[0], &metadata); err != nil {
return nil, err
}
labelsRaw, ok := metadata["labels"]
if !ok {
return nil, fmt.Errorf("worker doesn't have labels")
}
labels = map[string]string{}
if err := json.Unmarshal(labelsRaw, &labels); err != nil {
return nil, err
}
return labels, nil
}
func getHint() string {
hint := "`buildctl` needs to be installed and `buildkitd` needs to be running, see https://github.com/moby/buildkit"
if rootlessutil.IsRootless() {
hint += " , and `containerd-rootless-setuptool.sh install-buildkit` for OCI worker or `containerd-rootless-setuptool.sh install-buildkit-containerd` for containerd worker"
}
return hint
}
func PingBKDaemon(buildkitHost string) error {
if out, err := pingBKDaemon(buildkitHost); err != nil {
if out != "" {
log.L.Error(out)
}
return fmt.Errorf(getHint()+": %w", err)
}
return nil
}
func pingBKDaemon(buildkitHost string) (output string, _ error) {
if runtime.GOOS != "linux" && runtime.GOOS != "freebsd" {
return "", errors.New("only linux and freebsd are supported")
}
buildctlBinary, err := BuildctlBinary()
if err != nil {
return "", err
}
args := BuildctlBaseArgs(buildkitHost)
args = append(args, "debug", "workers")
buildctlCheckCmd := exec.Command(buildctlBinary, args...)
buildctlCheckCmd.Env = os.Environ()
if out, err := buildctlCheckCmd.CombinedOutput(); err != nil {
return string(out), err
}
return "", nil
}
// WriteTempDockerfile is from https://github.com/docker/cli/blob/v20.10.9/cli/command/image/build/context.go#L118
func WriteTempDockerfile(rc io.Reader) (dockerfileDir string, err error) {
// err is a named return value, due to the defer call below.
dockerfileDir, err = os.MkdirTemp("", TempDockerfileName)
if err != nil {
return "", fmt.Errorf("unable to create temporary context directory: %v", err)
}
defer func() {
if err != nil {
os.RemoveAll(dockerfileDir)
}
}()
f, err := os.Create(filepath.Join(dockerfileDir, DefaultDockerfileName))
if err != nil {
return "", err
}
defer f.Close()
if _, err := io.Copy(f, rc); err != nil {
return "", err
}
return dockerfileDir, nil
}
// BuildKitFile returns the values for the following buildctl args
// --localfilename=dockerfile={absDir}
// --opt=filename={file}
func BuildKitFile(dir, inputfile string) (absDir string, file string, err error) {
file = inputfile
if file == "" || file == "." {
file = DefaultDockerfileName
}
absDir, err = filepath.Abs(dir)
if err != nil {
return "", "", err
}
if file != DefaultDockerfileName {
if _, err := os.Lstat(filepath.Join(absDir, file)); err != nil {
return "", "", err
}
} else {
_, dErr := os.Lstat(filepath.Join(absDir, file))
_, cErr := os.Lstat(filepath.Join(absDir, ContainerfileName))
if dErr == nil && cErr == nil {
// both files exist, prefer Dockerfile.
dockerfile, err := os.ReadFile(filepath.Join(absDir, DefaultDockerfileName))
if err != nil {
return "", "", err
}
containerfile, err := os.ReadFile(filepath.Join(absDir, ContainerfileName))
if err != nil {
return "", "", err
}
if !bytes.Equal(dockerfile, containerfile) {
log.L.Warnf("%s and %s have different contents, building with %s", DefaultDockerfileName, ContainerfileName, DefaultDockerfileName)
}
}
if dErr != nil {
if errors.Is(dErr, fs.ErrNotExist) {
file = ContainerfileName
} else {
return "", "", dErr
}
if cErr != nil {
return "", "", cErr
}
}
}
return absDir, file, nil
}