/
buildkitutil.go
183 lines (165 loc) · 5.34 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
/*
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 (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/containerd/nerdctl/pkg/rootlessutil"
"github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
)
const (
// DefaultDockerfileName is the Default filename, read by nerdctl build
DefaultDockerfileName string = "Dockerfile"
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 {
logrus.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 allErr error
for _, p := range hostRel {
logrus.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 {
logrus.Debugf("Chosen buildkit host %q", buildkitHost)
return buildkitHost, nil
}
allErr = multierror.Append(allErr, fmt.Errorf("failed to ping to host %s: %w", buildkitHost, err))
}
logrus.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 != "" {
logrus.Error(string(out))
}
return fmt.Errorf(getHint()+": %w", err)
}
return nil
}
func pingBKDaemon(buildkitHost string) (output string, _ error) {
if runtime.GOOS != "linux" {
return "", errors.New("only linux is 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
}