File: config.go

package info (click to toggle)
singularity-container 4.1.5%2Bds4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 43,876 kB
  • sloc: asm: 14,840; sh: 3,190; ansic: 1,751; awk: 414; makefile: 413; python: 99
file content (542 lines) | stat: -rw-r--r-- 14,888 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
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
package dockerui

import (
	"bytes"
	"context"
	"encoding/json"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/containerd/platforms"
	"github.com/distribution/reference"
	controlapi "github.com/moby/buildkit/api/services/control"
	"github.com/moby/buildkit/client/llb"
	"github.com/moby/buildkit/frontend/attestations"
	"github.com/moby/buildkit/frontend/dockerfile/linter"
	"github.com/moby/buildkit/frontend/gateway/client"
	"github.com/moby/buildkit/solver/pb"
	"github.com/moby/buildkit/util/flightcontrol"
	dockerspec "github.com/moby/docker-image-spec/specs-go/v1"
	"github.com/moby/patternmatcher/ignorefile"
	digest "github.com/opencontainers/go-digest"
	ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
)

const (
	buildArgPrefix = "build-arg:"
	labelPrefix    = "label:"

	keyTarget           = "target"
	keyCgroupParent     = "cgroup-parent"
	keyForceNetwork     = "force-network-mode"
	keyGlobalAddHosts   = "add-hosts"
	keyHostname         = "hostname"
	keyImageResolveMode = "image-resolve-mode"
	keyMultiPlatform    = "multi-platform"
	keyNoCache          = "no-cache"
	keyShmSize          = "shm-size"
	keyTargetPlatform   = "platform"
	keyUlimit           = "ulimit"
	keyCacheFrom        = "cache-from"    // for registry only. deprecated in favor of keyCacheImports
	keyCacheImports     = "cache-imports" // JSON representation of []CacheOptionsEntry

	// Don't forget to update frontend documentation if you add
	// a new build-arg: frontend/dockerfile/docs/reference.md
	keyCacheNSArg              = "build-arg:BUILDKIT_CACHE_MOUNT_NS"
	keyMultiPlatformArg        = "build-arg:BUILDKIT_MULTI_PLATFORM"
	keyHostnameArg             = "build-arg:BUILDKIT_SANDBOX_HOSTNAME"
	keyDockerfileLintArg       = "build-arg:BUILDKIT_DOCKERFILE_CHECK"
	keyContextKeepGitDirArg    = "build-arg:BUILDKIT_CONTEXT_KEEP_GIT_DIR"
	keySourceDateEpoch         = "build-arg:SOURCE_DATE_EPOCH"
	keyCopyIgnoredCheckEnabled = "build-arg:BUILDKIT_DOCKERFILE_CHECK_COPYIGNORED_EXPERIMENT"
)

type Config struct {
	BuildArgs               map[string]string
	CacheIDNamespace        string
	CgroupParent            string
	Epoch                   *time.Time
	ExtraHosts              []llb.HostIP
	Hostname                string
	ImageResolveMode        llb.ResolveMode
	Labels                  map[string]string
	NetworkMode             pb.NetMode
	ShmSize                 int64
	Target                  string
	Ulimits                 []pb.Ulimit
	LinterConfig            *linter.Config
	CopyIgnoredCheckEnabled bool

	CacheImports           []client.CacheOptionsEntry
	TargetPlatforms        []ocispecs.Platform // nil means default
	BuildPlatforms         []ocispecs.Platform
	MultiPlatformRequested bool
	SBOM                   *SBOM
}

type Client struct {
	Config
	client      client.Client
	ignoreCache []string
	g           flightcontrol.CachedGroup[*buildContext]
	bopts       client.BuildOpts

	dockerignore     []byte
	dockerignoreName string
}

type SBOM struct {
	Generator string
}

type Source struct {
	*llb.SourceMap
	Warn func(context.Context, string, client.WarnOpts)
}

type ContextOpt struct {
	NoDockerignore bool
	AsyncLocalOpts func() []llb.LocalOption
	Platform       *ocispecs.Platform
	ResolveMode    string
	CaptureDigest  *digest.Digest
}

func validateMinCaps(c client.Client) error {
	opts := c.BuildOpts().Opts
	caps := c.BuildOpts().LLBCaps

	if err := caps.Supports(pb.CapFileBase); err != nil {
		return errors.Wrap(err, "needs BuildKit 0.5 or later")
	}
	if opts["override-copy-image"] != "" {
		return errors.New("support for \"override-copy-image\" was removed in BuildKit 0.11")
	}
	if v, ok := opts["build-arg:BUILDKIT_DISABLE_FILEOP"]; ok {
		if b, err := strconv.ParseBool(v); err == nil && b {
			return errors.New("support for \"BUILDKIT_DISABLE_FILEOP\" build-arg was removed in BuildKit 0.11")
		}
	}
	return nil
}

func NewClient(c client.Client) (*Client, error) {
	if err := validateMinCaps(c); err != nil {
		return nil, err
	}

	bc := &Client{
		client: c,
		bopts:  c.BuildOpts(), // avoid grpc on every call
	}

	if err := bc.init(); err != nil {
		return nil, err
	}

	return bc, nil
}

func (bc *Client) BuildOpts() client.BuildOpts {
	return bc.bopts
}

func (bc *Client) init() error {
	opts := bc.bopts.Opts

	defaultBuildPlatform := platforms.Normalize(platforms.DefaultSpec())
	if workers := bc.bopts.Workers; len(workers) > 0 && len(workers[0].Platforms) > 0 {
		defaultBuildPlatform = workers[0].Platforms[0]
	}
	buildPlatforms := []ocispecs.Platform{defaultBuildPlatform}
	targetPlatforms := []ocispecs.Platform{}
	if v := opts[keyTargetPlatform]; v != "" {
		var err error
		targetPlatforms, err = parsePlatforms(v)
		if err != nil {
			return err
		}
	}
	bc.BuildPlatforms = buildPlatforms
	bc.TargetPlatforms = targetPlatforms

	resolveMode, err := parseResolveMode(opts[keyImageResolveMode])
	if err != nil {
		return err
	}
	bc.ImageResolveMode = resolveMode

	extraHosts, err := parseExtraHosts(opts[keyGlobalAddHosts])
	if err != nil {
		return errors.Wrap(err, "failed to parse additional hosts")
	}
	bc.ExtraHosts = extraHosts

	shmSize, err := parseShmSize(opts[keyShmSize])
	if err != nil {
		return errors.Wrap(err, "failed to parse shm size")
	}
	bc.ShmSize = shmSize

	ulimits, err := parseUlimits(opts[keyUlimit])
	if err != nil {
		return errors.Wrap(err, "failed to parse ulimit")
	}
	bc.Ulimits = ulimits

	defaultNetMode, err := parseNetMode(opts[keyForceNetwork])
	if err != nil {
		return err
	}
	bc.NetworkMode = defaultNetMode

	var ignoreCache []string
	if v, ok := opts[keyNoCache]; ok {
		if v == "" {
			ignoreCache = []string{} // means all stages
		} else {
			ignoreCache = strings.Split(v, ",")
		}
	}
	bc.ignoreCache = ignoreCache

	multiPlatform := len(targetPlatforms) > 1
	if v := opts[keyMultiPlatformArg]; v != "" {
		opts[keyMultiPlatform] = v
	}
	if v := opts[keyMultiPlatform]; v != "" {
		b, err := strconv.ParseBool(v)
		if err != nil {
			return errors.Errorf("invalid boolean value for multi-platform: %s", v)
		}
		if !b && multiPlatform {
			return errors.Errorf("conflicting config: returning multiple target platforms is not allowed")
		}
		multiPlatform = b
	}
	bc.MultiPlatformRequested = multiPlatform

	var cacheImports []client.CacheOptionsEntry
	// new API
	if cacheImportsStr := opts[keyCacheImports]; cacheImportsStr != "" {
		var cacheImportsUM []controlapi.CacheOptionsEntry
		if err := json.Unmarshal([]byte(cacheImportsStr), &cacheImportsUM); err != nil {
			return errors.Wrapf(err, "failed to unmarshal %s (%q)", keyCacheImports, cacheImportsStr)
		}
		for _, um := range cacheImportsUM {
			cacheImports = append(cacheImports, client.CacheOptionsEntry{Type: um.Type, Attrs: um.Attrs})
		}
	}
	// old API
	if cacheFromStr := opts[keyCacheFrom]; cacheFromStr != "" {
		cacheFrom := strings.Split(cacheFromStr, ",")
		for _, s := range cacheFrom {
			im := client.CacheOptionsEntry{
				Type: "registry",
				Attrs: map[string]string{
					"ref": s,
				},
			}
			// FIXME(AkihiroSuda): skip append if already exists
			cacheImports = append(cacheImports, im)
		}
	}
	bc.CacheImports = cacheImports

	epoch, err := parseSourceDateEpoch(opts[keySourceDateEpoch])
	if err != nil {
		return err
	}
	bc.Epoch = epoch

	attests, err := attestations.Parse(opts)
	if err != nil {
		return err
	}
	if attrs, ok := attests[attestations.KeyTypeSbom]; ok {
		src, ok := attrs["generator"]
		if !ok {
			return errors.Errorf("sbom scanner cannot be empty")
		}
		ref, err := reference.ParseNormalizedNamed(src)
		if err != nil {
			return errors.Wrapf(err, "failed to parse sbom scanner %s", src)
		}
		ref = reference.TagNameOnly(ref)
		bc.SBOM = &SBOM{
			Generator: ref.String(),
		}
	}

	bc.BuildArgs = filter(opts, buildArgPrefix)
	bc.Labels = filter(opts, labelPrefix)
	bc.CacheIDNamespace = opts[keyCacheNSArg]
	bc.CgroupParent = opts[keyCgroupParent]
	bc.Target = opts[keyTarget]

	if v, ok := opts[keyHostnameArg]; ok && len(v) > 0 {
		opts[keyHostname] = v
	}
	bc.Hostname = opts[keyHostname]

	if v, ok := opts[keyDockerfileLintArg]; ok {
		bc.LinterConfig, err = linter.ParseLintOptions(v)
		if err != nil {
			return errors.Wrapf(err, "failed to parse %s", keyDockerfileLintArg)
		}
	}

	// CopyIgnoredCheckEnabled is an experimental feature to check if COPY is ignored by .dockerignore,
	// and it is disabled by default. It is expected that this feature will be enabled by default in a future
	// release, and this build-arg will be removed.
	if v, ok := opts[keyCopyIgnoredCheckEnabled]; ok {
		bc.CopyIgnoredCheckEnabled, err = strconv.ParseBool(v)
		if err != nil {
			return errors.Wrapf(err, "failed to parse %s", keyCopyIgnoredCheckEnabled)
		}
	}
	return nil
}

func (bc *Client) buildContext(ctx context.Context) (*buildContext, error) {
	return bc.g.Do(ctx, "initcontext", func(ctx context.Context) (*buildContext, error) {
		return bc.initContext(ctx)
	})
}

func (bc *Client) ReadEntrypoint(ctx context.Context, lang string, opts ...llb.LocalOption) (*Source, error) {
	bctx, err := bc.buildContext(ctx)
	if err != nil {
		return nil, err
	}

	var src *llb.State

	if !bctx.forceLocalDockerfile {
		if bctx.dockerfile != nil {
			src = bctx.dockerfile
		}
	}

	if src == nil {
		name := "load build definition from " + bctx.filename

		filenames := []string{bctx.filename, bctx.filename + ".dockerignore"}

		// dockerfile is also supported casing moby/moby#10858
		if path.Base(bctx.filename) == DefaultDockerfileName {
			filenames = append(filenames, path.Join(path.Dir(bctx.filename), strings.ToLower(DefaultDockerfileName)))
		}

		opts = append([]llb.LocalOption{
			llb.FollowPaths(filenames),
			llb.SessionID(bc.bopts.SessionID),
			llb.SharedKeyHint(bctx.dockerfileLocalName),
			WithInternalName(name),
			llb.Differ(llb.DiffNone, false),
		}, opts...)

		lsrc := llb.Local(bctx.dockerfileLocalName, opts...)
		src = &lsrc
	}

	def, err := src.Marshal(ctx, bc.marshalOpts()...)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to marshal local source")
	}

	defVtx, err := def.Head()
	if err != nil {
		return nil, err
	}

	res, err := bc.client.Solve(ctx, client.SolveRequest{
		Definition: def.ToPB(),
	})
	if err != nil {
		return nil, errors.Wrapf(err, "failed to resolve dockerfile")
	}

	ref, err := res.SingleRef()
	if err != nil {
		return nil, err
	}

	dt, err := ref.ReadFile(ctx, client.ReadRequest{
		Filename: bctx.filename,
	})
	if err != nil {
		if path.Base(bctx.filename) == DefaultDockerfileName {
			var err1 error
			dt, err1 = ref.ReadFile(ctx, client.ReadRequest{
				Filename: path.Join(path.Dir(bctx.filename), strings.ToLower(DefaultDockerfileName)),
			})
			if err1 == nil {
				err = nil
			}
		}
		if err != nil {
			return nil, errors.Wrapf(err, "failed to read dockerfile")
		}
	}
	smap := llb.NewSourceMap(src, bctx.filename, lang, dt)
	smap.Definition = def

	dt, err = ref.ReadFile(ctx, client.ReadRequest{
		Filename: bctx.filename + ".dockerignore",
	})
	if err == nil {
		bc.dockerignore = dt
		bc.dockerignoreName = bctx.filename + ".dockerignore"
	}

	return &Source{
		SourceMap: smap,
		Warn: func(ctx context.Context, msg string, opts client.WarnOpts) {
			if opts.Level == 0 {
				opts.Level = 1
			}
			if opts.SourceInfo == nil {
				opts.SourceInfo = &pb.SourceInfo{
					Data:       smap.Data,
					Filename:   smap.Filename,
					Language:   smap.Language,
					Definition: smap.Definition.ToPB(),
				}
			}
			bc.client.Warn(ctx, defVtx, msg, opts)
		},
	}, nil
}

func (bc *Client) MainContext(ctx context.Context, opts ...llb.LocalOption) (*llb.State, error) {
	bctx, err := bc.buildContext(ctx)
	if err != nil {
		return nil, err
	}

	if bctx.context != nil {
		return bctx.context, nil
	}

	excludes, err := bc.dockerIgnorePatterns(ctx, bctx)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to read dockerignore patterns")
	}

	opts = append([]llb.LocalOption{
		llb.SessionID(bc.bopts.SessionID),
		llb.ExcludePatterns(excludes),
		llb.SharedKeyHint(bctx.contextLocalName),
		WithInternalName("load build context"),
	}, opts...)

	st := llb.Local(bctx.contextLocalName, opts...)

	return &st, nil
}

func (bc *Client) NamedContext(ctx context.Context, name string, opt ContextOpt) (*llb.State, *dockerspec.DockerOCIImage, error) {
	named, err := reference.ParseNormalizedNamed(name)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "invalid context name %s", name)
	}
	name = strings.TrimSuffix(reference.FamiliarString(named), ":latest")

	pp := platforms.DefaultSpec()
	if opt.Platform != nil {
		pp = *opt.Platform
	}
	pname := name + "::" + platforms.Format(platforms.Normalize(pp))
	st, img, err := bc.namedContext(ctx, name, pname, opt)
	if err != nil || st != nil {
		return st, img, err
	}
	return bc.namedContext(ctx, name, name, opt)
}

func (bc *Client) IsNoCache(name string) bool {
	if len(bc.ignoreCache) == 0 {
		return bc.ignoreCache != nil
	}
	for _, n := range bc.ignoreCache {
		if strings.EqualFold(n, name) {
			return true
		}
	}
	return false
}

func (bc *Client) DockerIgnorePatterns(ctx context.Context) ([]string, error) {
	if bc == nil {
		return nil, nil
	}
	bctx, err := bc.buildContext(ctx)
	if err != nil {
		return nil, err
	}
	if bctx.context != nil {
		return nil, nil
	}

	return bc.dockerIgnorePatterns(ctx, bctx)
}

func DefaultMainContext(opts ...llb.LocalOption) *llb.State {
	opts = append([]llb.LocalOption{
		llb.SharedKeyHint(DefaultLocalNameContext),
		WithInternalName("load build context"),
	}, opts...)
	st := llb.Local(DefaultLocalNameContext, opts...)
	return &st
}

func WithInternalName(name string) llb.ConstraintsOpt {
	return llb.WithCustomName("[internal] " + name)
}

func (bc *Client) dockerIgnorePatterns(ctx context.Context, bctx *buildContext) ([]string, error) {
	if bc.dockerignore == nil {
		st := llb.Local(bctx.contextLocalName,
			llb.SessionID(bc.bopts.SessionID),
			llb.FollowPaths([]string{DefaultDockerignoreName}),
			llb.SharedKeyHint(bctx.contextLocalName+"-"+DefaultDockerignoreName),
			WithInternalName("load "+DefaultDockerignoreName),
			llb.Differ(llb.DiffNone, false),
		)
		def, err := st.Marshal(ctx, bc.marshalOpts()...)
		if err != nil {
			return nil, err
		}
		res, err := bc.client.Solve(ctx, client.SolveRequest{
			Definition: def.ToPB(),
		})
		if err != nil {
			return nil, err
		}
		ref, err := res.SingleRef()
		if err != nil {
			return nil, err
		}
		dt, _ := ref.ReadFile(ctx, client.ReadRequest{ // ignore error
			Filename: DefaultDockerignoreName,
		})
		if dt == nil {
			dt = []byte{}
		}
		bc.dockerignore = dt
		bc.dockerignoreName = DefaultDockerignoreName
	}
	var err error
	var excludes []string
	if len(bc.dockerignore) != 0 {
		excludes, err = ignorefile.ReadAll(bytes.NewBuffer(bc.dockerignore))
		if err != nil {
			return nil, errors.Wrapf(err, "failed parsing %s", bc.dockerignoreName)
		}
	}
	return excludes, nil
}