forked from concourse/oci-build-task
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
416 lines (338 loc) · 9.41 KB
/
task.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
package task
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/layout"
"github.com/google/go-containerregistry/pkg/v1/tarball"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Q: Audit name to not include "/"?
func StoreSecret(req *Request, name, value string) error {
secretDir := filepath.Join(os.TempDir(), "buildkit-secrets")
secretFile := filepath.Join(secretDir, name)
err := os.MkdirAll(secretDir, 0700)
if err != nil {
return fmt.Errorf("unable to create secret directory: %w", err)
}
err = ioutil.WriteFile(secretFile, []byte(value), 0600)
if err != nil {
return fmt.Errorf("unable to write secret to file: %w", err)
}
if req.Config.BuildkitSecrets == nil {
req.Config.BuildkitSecrets = make(map[string]string, 1)
}
req.Config.BuildkitSecrets[name] = secretFile
return nil
}
func Build(buildkitd *Buildkitd, outputsDir string, req Request) (Response, error) {
if req.Config.Debug {
logrus.SetLevel(logrus.DebugLevel)
}
cfg := req.Config
err := sanitize(&cfg)
if err != nil {
return Response{}, errors.Wrap(err, "config")
}
cacheDir := filepath.Join(outputsDir, "cache")
res := Response{
Outputs: []string{"image", "cache"},
}
dockerfileDir := filepath.Dir(cfg.DockerfilePath)
dockerfileName := filepath.Base(cfg.DockerfilePath)
buildctlArgs := []string{
"build",
"--progress", "plain",
"--frontend", "dockerfile.v0",
"--local", "context=" + cfg.ContextDir,
"--local", "dockerfile=" + dockerfileDir,
"--opt", "filename=" + dockerfileName,
}
for _, arg := range cfg.Labels {
buildctlArgs = append(buildctlArgs,
"--opt", "label:"+arg,
)
}
for _, arg := range cfg.BuildArgs {
buildctlArgs = append(buildctlArgs,
"--opt", "build-arg:"+arg,
)
}
if len(req.Config.ImageArgs) > 0 {
imagePaths := map[string]string{}
for _, arg := range req.Config.ImageArgs {
segs := strings.SplitN(arg, "=", 2)
imagePaths[segs[0]] = segs[1]
}
registry, err := LoadRegistry(imagePaths)
if err != nil {
return Response{}, fmt.Errorf("create local image registry: %w", err)
}
port, err := ServeRegistry(registry)
if err != nil {
return Response{}, fmt.Errorf("create local image registry: %w", err)
}
for _, arg := range registry.BuildArgs(port) {
buildctlArgs = append(buildctlArgs,
"--opt", "build-arg:"+arg,
)
}
}
if _, err := os.Stat(cacheDir); err == nil {
buildctlArgs = append(buildctlArgs,
"--export-cache", "type=local,mode=max,dest="+cacheDir,
)
}
for id, src := range cfg.BuildkitSecrets {
buildctlArgs = append(buildctlArgs,
"--secret", "id="+id+",src="+src,
)
}
var builds [][]string
var targets []string
var imagePaths []string
outputType := "docker"
if cfg.OutputOCI {
outputType = "oci"
}
for _, t := range cfg.AdditionalTargets {
// prevent re-use of the buildctlArgs slice as it is appended to later on,
// and that would clobber args for all targets if the slice was re-used
targetArgs := make([]string, len(buildctlArgs))
copy(targetArgs, buildctlArgs)
targetArgs = append(targetArgs, "--opt", "target="+t)
targetDir := filepath.Join(outputsDir, t)
if _, err := os.Stat(targetDir); err == nil {
imagePath := filepath.Join(targetDir, "image.tar")
imagePaths = append(imagePaths, imagePath)
targetArgs = append(targetArgs,
"--output", "type="+outputType+",dest="+imagePath,
)
}
builds = append(builds, targetArgs)
targets = append(targets, t)
}
finalTargetDir := filepath.Join(outputsDir, "image")
if _, err := os.Stat(finalTargetDir); err == nil {
imagePath := filepath.Join(finalTargetDir, "image.tar")
imagePaths = append(imagePaths, imagePath)
buildctlArgs = append(buildctlArgs,
"--output", "type="+outputType+",dest="+imagePath,
)
}
if cfg.Target != "" {
buildctlArgs = append(buildctlArgs,
"--opt", "target="+cfg.Target,
)
}
if cfg.AddHosts != "" {
buildctlArgs = append(buildctlArgs,
"--opt", "add-hosts="+cfg.AddHosts,
)
}
if cfg.BuildkitSSH != "" {
buildctlArgs = append(buildctlArgs,
"--ssh", cfg.BuildkitSSH,
)
}
if req.Config.ImagePlatform != "" {
buildctlArgs = append(buildctlArgs,
"--opt", "platform="+req.Config.ImagePlatform,
)
}
builds = append(builds, buildctlArgs)
targets = append(targets, "")
for i, args := range builds {
if i > 0 {
fmt.Fprintln(os.Stderr)
}
targetName := targets[i]
if targetName == "" {
logrus.Info("building image")
} else {
logrus.Infof("building target '%s'", targetName)
}
if _, err := os.Stat(filepath.Join(cacheDir, "index.json")); err == nil {
args = append(args,
"--import-cache", "type=local,src="+cacheDir,
)
}
logrus.Debugf("running buildctl %s", strings.Join(args, " "))
err = buildctl(buildkitd.Addr, os.Stdout, args...)
if err != nil {
return Response{}, errors.Wrap(err, "build")
}
}
if req.Config.OutputOCI {
err = loadOciImages(imagePaths, req)
if err != nil {
return Response{}, err
}
} else {
err = loadImages(imagePaths, req)
if err != nil {
return Response{}, err
}
}
return res, nil
}
func loadImages(imagePaths []string, req Request) error {
for _, imagePath := range imagePaths {
image, err := tarball.ImageFromPath(imagePath, nil)
if err != nil {
return errors.Wrap(err, "open oci image")
}
outputDir := filepath.Dir(imagePath)
m, err := image.Manifest()
if err != nil {
return errors.Wrap(err, "get image manifest")
}
err = writeDigest(outputDir, m.Config.Digest)
if err != nil {
return err
}
if req.Config.UnpackRootfs {
err = unpackRootfs(outputDir, image, req.Config)
if err != nil {
return errors.Wrap(err, "unpack rootfs")
}
}
}
return nil
}
func loadOciImages(imagePaths []string, req Request) error {
for _, imagePath := range imagePaths {
_, err := os.Stat(imagePath)
if err != nil {
return errors.Wrapf(err, "image path %s not valid", imagePath)
}
// go-containerregistry does not currently have support for loading a OCI formated
// image from a tarball, so we decompress it before doing anything.
targetDir := filepath.Dir(imagePath)
imageDir := filepath.Join(targetDir, "image")
logrus.Infof("decompressing OCI image tar to: %s", imageDir)
err = os.MkdirAll(imageDir, 0700)
if err != nil {
return errors.Wrapf(err, "unable to create image dir %s", imageDir)
}
run(os.Stdout, "tar", "-xvf", imagePath, "-C", imageDir)
l, err := layout.ImageIndexFromPath(imageDir)
if err != nil {
return errors.Wrapf(err, "failed to load %s as OCI layout", imagePath)
}
m, err := l.IndexManifest()
if err != nil {
return errors.Wrap(err, "error getting index manifest")
}
manifest := m.Manifests[0]
outputDir := filepath.Dir(imagePath)
err = writeDigest(outputDir, manifest.Digest)
if err != nil {
return err
}
}
return nil
}
func writeDigest(dest string, digest v1.Hash) error {
digestPath := filepath.Join(dest, "digest")
err := ioutil.WriteFile(digestPath, []byte(digest.String()), 0644)
if err != nil {
return errors.Wrap(err, "write digest file")
}
return nil
}
func unpackRootfs(dest string, image v1.Image, cfg Config) error {
rootfsDir := filepath.Join(dest, "rootfs")
metadataPath := filepath.Join(dest, "metadata.json")
logrus.Info("unpacking image")
err := unpackImage(rootfsDir, image, cfg.Debug)
if err != nil {
return errors.Wrap(err, "unpack image")
}
err = writeImageMetadata(metadataPath, image)
if err != nil {
return errors.Wrap(err, "write image metadata")
}
return nil
}
func writeImageMetadata(metadataPath string, image v1.Image) error {
cfg, err := image.ConfigFile()
if err != nil {
return errors.Wrap(err, "load image config")
}
meta, err := os.Create(metadataPath)
if err != nil {
return errors.Wrap(err, "create metadata file")
}
err = json.NewEncoder(meta).Encode(ImageMetadata{
Env: cfg.Config.Env,
User: cfg.Config.User,
})
if err != nil {
return errors.Wrap(err, "encode metadata")
}
err = meta.Close()
if err != nil {
return errors.Wrap(err, "close meta")
}
return nil
}
func sanitize(cfg *Config) error {
if cfg.ContextDir == "" {
cfg.ContextDir = "."
}
if cfg.DockerfilePath == "" {
cfg.DockerfilePath = filepath.Join(cfg.ContextDir, "Dockerfile")
}
if cfg.TargetFile != "" {
target, err := ioutil.ReadFile(cfg.TargetFile)
if err != nil {
return errors.Wrap(err, "read target file")
}
cfg.Target = strings.TrimSpace(string(target))
}
if cfg.BuildArgsFile != "" {
buildArgs, err := ioutil.ReadFile(cfg.BuildArgsFile)
if err != nil {
return errors.Wrap(err, "read build args file")
}
for _, arg := range strings.Split(string(buildArgs), "\n") {
if len(arg) == 0 {
// skip blank lines
continue
}
cfg.BuildArgs = append(cfg.BuildArgs, arg)
}
}
if cfg.LabelsFile != "" {
Labels, err := ioutil.ReadFile(cfg.LabelsFile)
if err != nil {
return errors.Wrap(err, "read labels file")
}
for _, arg := range strings.Split(string(Labels), "\n") {
if len(arg) == 0 {
// skip blank lines
continue
}
cfg.Labels = append(cfg.Labels, arg)
}
}
return nil
}
func buildctl(addr string, out io.Writer, args ...string) error {
return run(out, "buildctl", append([]string{"--addr=" + addr}, args...)...)
}
func run(out io.Writer, path string, args ...string) error {
cmd := exec.Command(path, args...)
cmd.Stdout = out
cmd.Stderr = out
cmd.Stdin = os.Stdin
return cmd.Run()
}