Browse code

vendor: github.com/moby/buildkit v0.8.2

full diff: https://github.com/moby/buildkit/compare/68bb095353c65bc3993fd534c26cf77fe05e61b1...9065b18ba4633c75862befca8188de4338d9f94a

- fix seccomp compatibility in 32bit arm
- fixes Unable to build alpine:edge containers for armv7
- fixes Buildx failing to build for arm/v7 platform on arm64 machine
- resolver: avoid error caching on token fetch
- fixes "Error: i/o timeout should not be cached"
- fileop: fix checksum to contain indexes of inputs
- frontend/dockerfile: add RunCommand.FlagsUsed field
- relates to [20.10] Classic builder silently ignores unsupported Dockerfile command flags
- update qemu emulators
- relates to "Impossible to run git clone inside buildx with non x86 architecture"
- Fix reference count issues on typed errors with mount references
- fixes errors on releasing mounts with typed execerror refs
- fixes / addresses invalid mutable ref when using shared cache mounts
- dockerfile/docs: fix frontend image tags
- git: set token only for main remote access
- fixes "Loading repositories with submodules is repeated. Failed to clone submodule from googlesource"
- allow skipping empty layer detection on cache export

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Tibor Vass <tibor@docker.com>
(cherry picked from commit 9962a3f74e73d048394dcaac96468a8864e46dd4)
Signed-off-by: Tibor Vass <tibor@docker.com>

Sebastiaan van Stijn authored on 2021/02/22 18:41:18
Showing 16 changed files
... ...
@@ -33,7 +33,7 @@ github.com/imdario/mergo                            1afb36080aec31e0d1528973ebe6
33 33
 golang.org/x/sync                                   cd5d95a43a6e21273425c7ae415d3df9ea832eeb
34 34
 
35 35
 # buildkit
36
-github.com/moby/buildkit                            68bb095353c65bc3993fd534c26cf77fe05e61b1 # v0.8 branch
36
+github.com/moby/buildkit                            9065b18ba4633c75862befca8188de4338d9f94a # v0.8.2
37 37
 github.com/tonistiigi/fsutil                        0834f99b7b85462efb69b4f571a4fa3ca7da5ac9
38 38
 github.com/tonistiigi/units                         6950e57a87eaf136bbe44ef2ec8e75b9e3569de2
39 39
 github.com/grpc-ecosystem/grpc-opentracing          8e809c8a86450a29b90dcc9efbf062d0fe6d9746
... ...
@@ -10,6 +10,10 @@ import (
10 10
 	"github.com/pkg/errors"
11 11
 )
12 12
 
13
+// EmptyLayerRemovalSupported defines if implementation supports removal of empty layers. Buildkit image exporter
14
+// removes empty layers, but moby layerstore based implementation does not.
15
+var EmptyLayerRemovalSupported = true
16
+
13 17
 // sortConfig sorts the config structure to make sure it is deterministic
14 18
 func sortConfig(cc *CacheConfig) {
15 19
 	type indexedLayer struct {
... ...
@@ -239,7 +243,7 @@ func marshalRemote(r *solver.Remote, state *marshalState) string {
239 239
 	}
240 240
 	desc := r.Descriptors[len(r.Descriptors)-1]
241 241
 
242
-	if desc.Digest == exptypes.EmptyGZLayer {
242
+	if desc.Digest == exptypes.EmptyGZLayer && EmptyLayerRemovalSupported {
243 243
 		return parentID
244 244
 	}
245 245
 
... ...
@@ -108,6 +108,15 @@ func (fl *Flag) IsUsed() bool {
108 108
 	return false
109 109
 }
110 110
 
111
+// Used returns a slice of flag names that are set
112
+func (bf *BFlags) Used() []string {
113
+	used := make([]string, 0, len(bf.used))
114
+	for f := range bf.used {
115
+		used = append(used, f)
116
+	}
117
+	return used
118
+}
119
+
111 120
 // IsTrue checks if a bool flag is true
112 121
 func (fl *Flag) IsTrue() bool {
113 122
 	if fl.flagType != boolType {
... ...
@@ -269,6 +269,7 @@ type RunCommand struct {
269 269
 	withNameAndCode
270 270
 	withExternalData
271 271
 	ShellDependantCmdLine
272
+	FlagsUsed []string
272 273
 }
273 274
 
274 275
 // CmdCommand : CMD foo
... ...
@@ -375,7 +375,7 @@ func parseRun(req parseRequest) (*RunCommand, error) {
375 375
 	if err := req.flags.Parse(); err != nil {
376 376
 		return nil, err
377 377
 	}
378
-
378
+	cmd.FlagsUsed = req.flags.Used()
379 379
 	cmd.ShellDependantCmdLine = parseShellDependentCommand(req, false)
380 380
 	cmd.withNameAndCode = newWithNameAndCode(req)
381 381
 
... ...
@@ -127,6 +127,7 @@ type MountRef struct {
127 127
 type MountMutableRef struct {
128 128
 	Ref        cache.MutableRef
129 129
 	MountIndex int
130
+	NoCommit   bool
130 131
 }
131 132
 
132 133
 type MakeMutable func(m *opspb.Mount, ref cache.ImmutableRef) (cache.MutableRef, error)
... ...
@@ -196,6 +197,7 @@ func PrepareMounts(ctx context.Context, mm *mounts.MountManager, cm cache.Manage
196 196
 			p.Actives = append(p.Actives, MountMutableRef{
197 197
 				MountIndex: i,
198 198
 				Ref:        active,
199
+				NoCommit:   true,
199 200
 			})
200 201
 			if m.Output != opspb.SkipOutput && ref != nil {
201 202
 				p.OutputRefs = append(p.OutputRefs, MountRef{
... ...
@@ -21,10 +21,15 @@ func (e *ExecError) Unwrap() error {
21 21
 }
22 22
 
23 23
 func (e *ExecError) EachRef(fn func(solver.Result) error) (err error) {
24
+	m := map[solver.Result]struct{}{}
24 25
 	for _, res := range e.Inputs {
25 26
 		if res == nil {
26 27
 			continue
27 28
 		}
29
+		if _, ok := m[res]; ok {
30
+			continue
31
+		}
32
+		m[res] = struct{}{}
28 33
 		if err1 := fn(res); err1 != nil && err == nil {
29 34
 			err = err1
30 35
 		}
... ...
@@ -33,6 +38,10 @@ func (e *ExecError) EachRef(fn func(solver.Result) error) (err error) {
33 33
 		if res == nil {
34 34
 			continue
35 35
 		}
36
+		if _, ok := m[res]; ok {
37
+			continue
38
+		}
39
+		m[res] = struct{}{}
36 40
 		if err1 := fn(res); err1 != nil && err == nil {
37 41
 			err = err1
38 42
 		}
... ...
@@ -235,7 +235,7 @@ func (e *execOp) Exec(ctx context.Context, g session.Group, inputs []solver.Resu
235 235
 				if m.Input == -1 {
236 236
 					continue
237 237
 				}
238
-				execInputs[i] = inputs[m.Input]
238
+				execInputs[i] = inputs[m.Input].Clone()
239 239
 			}
240 240
 			execMounts := make([]solver.Result, len(e.op.Mounts))
241 241
 			copy(execMounts, execInputs)
... ...
@@ -243,12 +243,16 @@ func (e *execOp) Exec(ctx context.Context, g session.Group, inputs []solver.Resu
243 243
 				execMounts[p.OutputRefs[i].MountIndex] = res
244 244
 			}
245 245
 			for _, active := range p.Actives {
246
-				ref, cerr := active.Ref.Commit(ctx)
247
-				if cerr != nil {
248
-					err = errors.Wrapf(err, "error committing %s: %s", active.Ref.ID(), cerr)
249
-					continue
246
+				if active.NoCommit {
247
+					active.Ref.Release(context.TODO())
248
+				} else {
249
+					ref, cerr := active.Ref.Commit(ctx)
250
+					if cerr != nil {
251
+						err = errors.Wrapf(err, "error committing %s: %s", active.Ref.ID(), cerr)
252
+						continue
253
+					}
254
+					execMounts[active.MountIndex] = worker.NewWorkerRefResult(ref, e.w)
250 255
 				}
251
-				execMounts[active.MountIndex] = worker.NewWorkerRefResult(ref, e.w)
252 256
 			}
253 257
 			err = errdefs.WithExecError(err, execInputs, execMounts)
254 258
 		} else {
... ...
@@ -27,6 +27,7 @@ var qemuArchMap = map[string]string{
27 27
 	"arm":     "arm",
28 28
 	"s390x":   "s390x",
29 29
 	"ppc64le": "ppc64le",
30
+	"386":     "i386",
30 31
 }
31 32
 
32 33
 type emulator struct {
... ...
@@ -61,6 +61,8 @@ func (f *fileOp) CacheMap(ctx context.Context, g session.Group, index int) (*sol
61 61
 		}
62 62
 	}
63 63
 
64
+	indexes := make([][]int, 0, len(f.op.Actions))
65
+
64 66
 	for _, action := range f.op.Actions {
65 67
 		var dt []byte
66 68
 		var err error
... ...
@@ -103,14 +105,21 @@ func (f *fileOp) CacheMap(ctx context.Context, g session.Group, index int) (*sol
103 103
 		}
104 104
 
105 105
 		actions = append(actions, dt)
106
+		indexes = append(indexes, []int{int(action.Input), int(action.SecondaryInput), int(action.Output)})
107
+	}
108
+
109
+	if isDefaultIndexes(indexes) {
110
+		indexes = nil
106 111
 	}
107 112
 
108 113
 	dt, err := json.Marshal(struct {
109 114
 		Type    string
110 115
 		Actions [][]byte
116
+		Indexes [][]int `json:"indexes,omitempty"`
111 117
 	}{
112 118
 		Type:    fileCacheType,
113 119
 		Actions: actions,
120
+		Indexes: indexes,
114 121
 	})
115 122
 	if err != nil {
116 123
 		return nil, false, err
... ...
@@ -421,7 +430,6 @@ func (s *FileOpSolver) getInput(ctx context.Context, idx int, inputs []fileoptyp
421 421
 					if cerr == nil {
422 422
 						outputRes[idx-len(inputs)] = worker.NewWorkerRefResult(ref.(cache.ImmutableRef), s.w)
423 423
 					}
424
-					inpMount.Release(context.TODO())
425 424
 				}
426 425
 
427 426
 				// If the action has a secondary input, commit it and set the ref on
... ...
@@ -611,3 +619,39 @@ func (s *FileOpSolver) getInput(ctx context.Context, idx int, inputs []fileoptyp
611 611
 	}
612 612
 	return inp.(input), err
613 613
 }
614
+
615
+func isDefaultIndexes(idxs [][]int) bool {
616
+	// Older version of checksum did not contain indexes for actions resulting in possibility for a wrong cache match.
617
+	// We detect the most common pattern for indexes and maintain old checksum for that case to minimize cache misses on upgrade.
618
+	// If a future change causes braking changes in instruction cache consider removing this exception.
619
+	if len(idxs) == 0 {
620
+		return false
621
+	}
622
+
623
+	for i, idx := range idxs {
624
+		if len(idx) != 3 {
625
+			return false
626
+		}
627
+		// input for first action is first input
628
+		if i == 0 && idx[0] != 0 {
629
+			return false
630
+		}
631
+		// input for other actions is previous action
632
+		if i != 0 && idx[0] != len(idxs)+(i-1) {
633
+			return false
634
+		}
635
+		// secondary input is second input or -1
636
+		if idx[1] != -1 && idx[1] != 1 {
637
+			return false
638
+		}
639
+		// last action creates output
640
+		if i == len(idxs)-1 && idx[2] != 0 {
641
+			return false
642
+		}
643
+		// other actions do not create an output
644
+		if i != len(idxs)-1 && idx[2] != -1 {
645
+			return false
646
+		}
647
+	}
648
+	return true
649
+}
... ...
@@ -47,7 +47,7 @@ type splitResult struct {
47 47
 
48 48
 func (r *splitResult) Release(ctx context.Context) error {
49 49
 	if atomic.AddInt64(&r.released, 1) > 1 {
50
-		err := errors.Errorf("releasing already released reference")
50
+		err := errors.Errorf("releasing already released reference %+v", r.Result.ID())
51 51
 		logrus.Error(err)
52 52
 		return err
53 53
 	}
... ...
@@ -78,10 +78,14 @@ func NewSharedCachedResult(res CachedResult) *SharedCachedResult {
78 78
 	}
79 79
 }
80 80
 
81
-func (r *SharedCachedResult) Clone() CachedResult {
81
+func (r *SharedCachedResult) CloneCachedResult() CachedResult {
82 82
 	return &clonedCachedResult{Result: r.SharedResult.Clone(), cr: r.CachedResult}
83 83
 }
84 84
 
85
+func (r *SharedCachedResult) Clone() Result {
86
+	return r.CloneCachedResult()
87
+}
88
+
85 89
 func (r *SharedCachedResult) Release(ctx context.Context) error {
86 90
 	return r.SharedResult.Release(ctx)
87 91
 }
... ...
@@ -244,7 +244,7 @@ func (s *scheduler) build(ctx context.Context, edge Edge) (CachedResult, error)
244 244
 	if err := p.Receiver.Status().Err; err != nil {
245 245
 		return nil, err
246 246
 	}
247
-	return p.Receiver.Status().Value.(*edgeState).result.Clone(), nil
247
+	return p.Receiver.Status().Value.(*edgeState).result.CloneCachedResult(), nil
248 248
 }
249 249
 
250 250
 // newPipe creates a new request pipe between two edges
... ...
@@ -61,6 +61,7 @@ type Result interface {
61 61
 	ID() string
62 62
 	Release(context.Context) error
63 63
 	Sys() interface{}
64
+	Clone() Result
64 65
 }
65 66
 
66 67
 // CachedResult is a result connected with its cache key
... ...
@@ -231,7 +231,7 @@ func (gs *gitSourceHandler) getAuthToken(ctx context.Context, g session.Group) e
231 231
 			if s.token {
232 232
 				dt = []byte("basic " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("x-access-token:%s", dt))))
233 233
 			}
234
-			gs.auth = []string{"-c", "http.extraheader=Authorization: " + string(dt)}
234
+			gs.auth = []string{"-c", "http." + tokenScope(gs.src.Remote) + ".extraheader=Authorization: " + string(dt)}
235 235
 			break
236 236
 		}
237 237
 		return nil
... ...
@@ -631,3 +631,14 @@ func argsNoDepth(args []string) []string {
631 631
 	}
632 632
 	return out
633 633
 }
634
+
635
+func tokenScope(remote string) string {
636
+	// generally we can only use the token for fetching main remote but in case of github.com we do best effort
637
+	// to try reuse same token for all github.com remotes. This is the same behavior actions/checkout uses
638
+	for _, pfx := range []string{"https://github.com/", "https://www.github.com/"} {
639
+		if strings.HasPrefix(remote, pfx) {
640
+			return pfx
641
+		}
642
+	}
643
+	return remote
644
+}
... ...
@@ -220,15 +220,13 @@ func (a *dockerAuthorizer) AddResponses(ctx context.Context, responses []*http.R
220 220
 
221 221
 // authResult is used to control limit rate.
222 222
 type authResult struct {
223
-	sync.WaitGroup
224 223
 	token   string
225
-	err     error
226 224
 	expires time.Time
227 225
 }
228 226
 
229 227
 // authHandler is used to handle auth request per registry server.
230 228
 type authHandler struct {
231
-	sync.Mutex
229
+	g flightcontrol.Group
232 230
 
233 231
 	client *http.Client
234 232
 
... ...
@@ -240,7 +238,8 @@ type authHandler struct {
240 240
 
241 241
 	// scopedTokens caches token indexed by scopes, which used in
242 242
 	// bearer auth case
243
-	scopedTokens map[string]*authResult
243
+	scopedTokens   map[string]*authResult
244
+	scopedTokensMu sync.Mutex
244 245
 
245 246
 	lastUsed time.Time
246 247
 
... ...
@@ -292,46 +291,44 @@ func (ah *authHandler) doBearerAuth(ctx context.Context, sm *session.Manager, g
292 292
 	// Docs: https://docs.docker.com/registry/spec/auth/scope
293 293
 	scoped := strings.Join(to.Scopes, " ")
294 294
 
295
-	ah.Lock()
296
-	for {
295
+	res, err := ah.g.Do(ctx, scoped, func(ctx context.Context) (interface{}, error) {
296
+		ah.scopedTokensMu.Lock()
297 297
 		r, exist := ah.scopedTokens[scoped]
298
-		if !exist {
299
-			// no entry cached
300
-			break
301
-		}
302
-		ah.Unlock()
303
-		r.Wait()
304
-		if r.err != nil {
305
-			select {
306
-			case <-ctx.Done():
307
-				return "", r.err
308
-			default:
298
+		ah.scopedTokensMu.Unlock()
299
+		if exist {
300
+			if r.expires.IsZero() || r.expires.After(time.Now()) {
301
+				return r, nil
309 302
 			}
310 303
 		}
311
-		if !errors.Is(r.err, context.Canceled) &&
312
-			(r.expires.IsZero() || r.expires.After(time.Now())) {
313
-			return r.token, r.err
314
-		}
315
-		// r.err is canceled or token expired. Get rid of it and try again
316
-		ah.Lock()
317
-		r2, exist := ah.scopedTokens[scoped]
318
-		if exist && r == r2 {
319
-			delete(ah.scopedTokens, scoped)
304
+		r, err := ah.fetchToken(ctx, sm, g, to)
305
+		if err != nil {
306
+			return nil, err
320 307
 		}
308
+		ah.scopedTokensMu.Lock()
309
+		ah.scopedTokens[scoped] = r
310
+		ah.scopedTokensMu.Unlock()
311
+		return r, nil
312
+	})
313
+
314
+	if err != nil || res == nil {
315
+		return "", err
321 316
 	}
317
+	r := res.(*authResult)
318
+	if r == nil {
319
+		return "", nil
320
+	}
321
+	return r.token, nil
322
+}
322 323
 
323
-	// only one fetch token job
324
-	r := new(authResult)
325
-	r.Add(1)
326
-	ah.scopedTokens[scoped] = r
327
-	ah.Unlock()
328
-
324
+func (ah *authHandler) fetchToken(ctx context.Context, sm *session.Manager, g session.Group, to auth.TokenOptions) (r *authResult, err error) {
329 325
 	var issuedAt time.Time
330 326
 	var expires int
327
+	var token string
331 328
 	defer func() {
332 329
 		token = fmt.Sprintf("Bearer %s", token)
333
-		r.token, r.err = token, err
330
+
334 331
 		if err == nil {
332
+			r = &authResult{token: token}
335 333
 			if issuedAt.IsZero() {
336 334
 				issuedAt = time.Now()
337 335
 			}
... ...
@@ -339,7 +336,6 @@ func (ah *authHandler) doBearerAuth(ctx context.Context, sm *session.Manager, g
339 339
 				r.expires = exp
340 340
 			}
341 341
 		}
342
-		r.Done()
343 342
 	}()
344 343
 
345 344
 	if ah.authority != nil {
... ...
@@ -351,10 +347,11 @@ func (ah *authHandler) doBearerAuth(ctx context.Context, sm *session.Manager, g
351 351
 			Scopes:   to.Scopes,
352 352
 		}, sm, g)
353 353
 		if err != nil {
354
-			return "", err
354
+			return nil, err
355 355
 		}
356 356
 		issuedAt, expires = time.Unix(resp.IssuedAt, 0), int(resp.ExpiresIn)
357
-		return resp.Token, nil
357
+		token = resp.Token
358
+		return nil, nil
358 359
 	}
359 360
 
360 361
 	// fetch token for the resource scope
... ...
@@ -374,29 +371,32 @@ func (ah *authHandler) doBearerAuth(ctx context.Context, sm *session.Manager, g
374 374
 				if (errStatus.StatusCode == 405 && to.Username != "") || errStatus.StatusCode == 404 || errStatus.StatusCode == 401 {
375 375
 					resp, err := auth.FetchTokenWithOAuth(ctx, ah.client, nil, "buildkit-client", to)
376 376
 					if err != nil {
377
-						return "", err
377
+						return nil, err
378 378
 					}
379 379
 					issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
380
-					return resp.AccessToken, nil
380
+					token = resp.AccessToken
381
+					return nil, nil
381 382
 				}
382 383
 				log.G(ctx).WithFields(logrus.Fields{
383 384
 					"status": errStatus.Status,
384 385
 					"body":   string(errStatus.Body),
385 386
 				}).Debugf("token request failed")
386 387
 			}
387
-			return "", err
388
+			return nil, err
388 389
 		}
389 390
 		issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
390
-		return resp.Token, nil
391
+		token = resp.Token
392
+		return nil, nil
391 393
 	}
392 394
 	// do request anonymously
393 395
 	resp, err := auth.FetchToken(ctx, ah.client, nil, to)
394 396
 	if err != nil {
395
-		return "", errors.Wrap(err, "failed to fetch anonymous token")
397
+		return nil, errors.Wrap(err, "failed to fetch anonymous token")
396 398
 	}
397 399
 	issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
398 400
 
399
-	return resp.Token, nil
401
+	token = resp.Token
402
+	return nil, nil
400 403
 }
401 404
 
402 405
 func invalidAuthorization(c auth.Challenge, responses []*http.Response) error {
... ...
@@ -52,3 +52,11 @@ func (r *workerRefResult) Release(ctx context.Context) error {
52 52
 func (r *workerRefResult) Sys() interface{} {
53 53
 	return r.WorkerRef
54 54
 }
55
+
56
+func (r *workerRefResult) Clone() solver.Result {
57
+	r2 := *r
58
+	if r.ImmutableRef != nil {
59
+		r.ImmutableRef = r.ImmutableRef.Clone()
60
+	}
61
+	return &r2
62
+}