Skip to content

Commit

Permalink
fix: avoid panic from releasing unacquired semaphore (#363)
Browse files Browse the repository at this point in the history
When using this pattern:

```go
eg, egCtx := errgroup.WithContext(ctx)
for /* ... */ {
	limiter.Acquire(ctx, 1)
	eg.Go(func() error {
		defer limiter.Release(1)
		// ...
		return nil
	})
}
if err := eg.Wait(); err != nil {
	return err
}
```

If `ctx` is cancelled then `Acquire` may return an error, which will
then cause `Release` to panic after it's called more times than the
semaphore was successfully acquired.

This change uses the
[SetLimit](https://pkg.go.dev/golang.org/x/sync@v0.1.0/errgroup#Group.SetLimit)
functionality which has been added to `errgroup.Group` and provides a
small wrapper around it in the internal/syncutil package to improve the
ergonomics of its usage.

Signed-off-by: Andy Bursavich <abursavich@gmail.com>
  • Loading branch information
abursavich authored Dec 6, 2022
1 parent ff05195 commit a5be49a
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 20 deletions.
21 changes: 4 additions & 17 deletions content.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ import (
"io"

ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"oras.land/oras-go/v2/content"
"oras.land/oras-go/v2/errdef"
"oras.land/oras-go/v2/internal/cas"
"oras.land/oras-go/v2/internal/docker"
"oras.land/oras-go/v2/internal/interfaces"
"oras.land/oras-go/v2/internal/platform"
"oras.land/oras-go/v2/internal/registryutil"
"oras.land/oras-go/v2/internal/syncutil"
"oras.land/oras-go/v2/registry"
"oras.land/oras-go/v2/registry/remote/auth"
)
Expand Down Expand Up @@ -119,13 +118,10 @@ func TagN(ctx context.Context, target Target, srcReference string, dstReferences
return err
}

limiter := semaphore.NewWeighted(opts.Concurrency)
eg, egCtx := errgroup.WithContext(ctx)
eg, egCtx := syncutil.LimitGroup(ctx, int(opts.Concurrency))
for _, dstRef := range dstReferences {
limiter.Acquire(ctx, 1)
eg.Go(func(dst string) func() error {
return func() error {
defer limiter.Release(1)
r := bytes.NewReader(contentBytes)
if err := refPusher.PushReference(egCtx, desc, r, dst); err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
return fmt.Errorf("failed to tag %s as %s: %w", srcReference, dst, err)
Expand All @@ -141,13 +137,10 @@ func TagN(ctx context.Context, target Target, srcReference string, dstReferences
if err != nil {
return err
}
limiter := semaphore.NewWeighted(opts.Concurrency)
eg, egCtx := errgroup.WithContext(ctx)
eg, egCtx := syncutil.LimitGroup(ctx, int(opts.Concurrency))
for _, dstRef := range dstReferences {
limiter.Acquire(ctx, 1)
eg.Go(func(dst string) func() error {
return func() error {
defer limiter.Release(1)
if err := target.Tag(egCtx, desc, dst); err != nil {
return fmt.Errorf("failed to tag %s as %s: %w", srcReference, dst, err)
}
Expand Down Expand Up @@ -376,14 +369,11 @@ func TagBytesN(ctx context.Context, target Target, mediaType string, contentByte
if opts.Concurrency <= 0 {
opts.Concurrency = defaultTagConcurrency
}
limiter := semaphore.NewWeighted(opts.Concurrency)
eg, egCtx := errgroup.WithContext(ctx)
eg, egCtx := syncutil.LimitGroup(ctx, int(opts.Concurrency))
if refPusher, ok := target.(registry.ReferencePusher); ok {
for _, reference := range references {
limiter.Acquire(ctx, 1)
eg.Go(func(ref string) func() error {
return func() error {
defer limiter.Release(1)
r := bytes.NewReader(contentBytes)
if err := refPusher.PushReference(egCtx, desc, r, ref); err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
return fmt.Errorf("failed to tag %s: %w", ref, err)
Expand All @@ -397,12 +387,9 @@ func TagBytesN(ctx context.Context, target Target, mediaType string, contentByte
if err := target.Push(ctx, desc, r); err != nil && !errors.Is(err, errdef.ErrAlreadyExists) {
return ocispec.Descriptor{}, fmt.Errorf("failed to push content: %w", err)
}

for _, reference := range references {
limiter.Acquire(ctx, 1)
eg.Go(func(ref string) func() error {
return func() error {
defer limiter.Release(1)
if err := target.Tag(egCtx, desc, ref); err != nil {
return fmt.Errorf("failed to tag %s: %w", ref, err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ go 1.18
require (
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.0-rc2
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sync v0.1.0
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.0-rc2 h1:2zx/Stx4Wc5pIPDvIxHXvXtQFW/7XWJGmnM7r3wg034=
github.com/opencontainers/image-spec v1.1.0-rc2/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
67 changes: 67 additions & 0 deletions internal/syncutil/limitgroup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
Copyright The ORAS 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.
*/

package syncutil

import (
"context"

"golang.org/x/sync/errgroup"
)

// A LimitedGroup is a collection of goroutines working on subtasks that are part of
// the same overall task.
type LimitedGroup struct {
grp *errgroup.Group
ctx context.Context
}

// LimitGroup returns a new LimitedGroup and an associated Context derived from ctx.
//
// The number of active goroutines in this group is limited to the given limit.
// A negative value indicates no limit.
//
// The derived Context is canceled the first time a function passed to Go
// returns a non-nil error or the first time Wait returns, whichever occurs
// first.
func LimitGroup(ctx context.Context, limit int) (*LimitedGroup, context.Context) {
grp, ctx := errgroup.WithContext(ctx)
grp.SetLimit(limit)
return &LimitedGroup{grp: grp, ctx: ctx}, ctx
}

// Go calls the given function in a new goroutine.
// It blocks until the new goroutine can be added without the number of
// active goroutines in the group exceeding the configured limit.
//
// The first call to return a non-nil error cancels the group's context.
// After which, any subsequent calls to Go will not execute their given function.
// The error will be returned by Wait.
func (g *LimitedGroup) Go(f func() error) {
g.grp.Go(func() error {
select {
case <-g.ctx.Done():
return g.ctx.Err()
default:
return f()
}
})
}

// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.
func (g *LimitedGroup) Wait() error {
return g.grp.Wait()
}

0 comments on commit a5be49a

Please sign in to comment.