make AllLocations accept a context (#2518)

The previous implementation would leak a goroutine if the caller of
AllLocations stopped iterating early. Now, accept a context so that the
caller can cancel the AllLocations iterator rather than leak the
goroutine.

Signed-off-by: Will Murphy <will.murphy@anchore.com>
This commit is contained in:
William Murphy
2024-01-22 11:05:59 -05:00
committed by GitHub
parent 3046d43a8a
commit c6ce1de928
22 changed files with 156 additions and 42 deletions
+2 -1
View File
@@ -1,6 +1,7 @@
package binary
import (
"context"
"errors"
"flag"
"fmt"
@@ -1237,7 +1238,7 @@ func (p *panicyResolver) RelativeFileByPath(_ file.Location, _ string) *file.Loc
return nil
}
func (p *panicyResolver) AllLocations() <-chan file.Location {
func (p *panicyResolver) AllLocations(_ context.Context) <-chan file.Location {
return nil
}
@@ -1,6 +1,7 @@
package pkgtest
import (
"context"
"fmt"
"io"
"sort"
@@ -209,8 +210,8 @@ func (r *ObservingResolver) FileContentsByLocation(location file.Location) (io.R
// For the remaining resolver methods...
func (r *ObservingResolver) AllLocations() <-chan file.Location {
return r.decorated.AllLocations()
func (r *ObservingResolver) AllLocations(ctx context.Context) <-chan file.Location {
return r.decorated.AllLocations(ctx)
}
func (r *ObservingResolver) HasPath(s string) bool {
+4 -1
View File
@@ -4,6 +4,7 @@ Package nix provides a concrete Cataloger implementation for packages within the
package nix
import (
"context"
"fmt"
"github.com/bmatcuk/doublestar/v4"
@@ -31,7 +32,9 @@ func (c *StoreCataloger) Catalog(resolver file.Resolver) ([]pkg.Package, []artif
// we want to search for only directories, which isn't possible via the stereoscope API, so we need to apply the glob manually on all returned paths
var pkgs []pkg.Package
var filesByPath = make(map[string]*file.LocationSet)
for location := range resolver.AllLocations() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for location := range resolver.AllLocations(ctx) {
matchesStorePath, err := doublestar.Match("**/nix/store/*", location.RealPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to match nix store path: %w", err)
@@ -1,6 +1,7 @@
package redhat
import (
"context"
"fmt"
"io"
"testing"
@@ -34,7 +35,7 @@ func (r rpmdbTestFileResolverMock) FileContentsByLocation(location file.Location
panic("not implemented")
}
func (r rpmdbTestFileResolverMock) AllLocations() <-chan file.Location {
func (r rpmdbTestFileResolverMock) AllLocations(_ context.Context) <-chan file.Location {
panic("not implemented")
}