vendor: bump c/common to 9b0d134f392

Bump common to 9b0d134f392f41de3f3065aad162e73a3904168e

Signed-off-by: flouthoc <flouthoc.git@gmail.com>
This commit is contained in:
flouthoc
2025-04-01 09:58:40 -07:00
parent 69408391f6
commit 51bb71d1b3
60 changed files with 178 additions and 301 deletions

View File

@ -178,7 +178,7 @@ type Copier struct {
// Note that fields in options *may* overwrite the counterparts of
// the specified system context. Please make sure to call `(*Copier).Close()`.
func (r *Runtime) newCopier(options *CopyOptions) (*Copier, error) {
return NewCopier(options, r.SystemContext(), nil)
return NewCopier(options, r.SystemContext())
}
// storageAllowedPolicyScopes overrides the policy for local storage
@ -225,7 +225,7 @@ func getDockerAuthConfig(name, passwd, creds, idToken string) (*types.DockerAuth
// NewCopier creates a Copier based on a provided system context.
// Note that fields in options *may* overwrite the counterparts of
// the specified system context. Please make sure to call `(*Copier).Close()`.
func NewCopier(options *CopyOptions, sc *types.SystemContext, reportResolvedReference *types.ImageReference) (*Copier, error) {
func NewCopier(options *CopyOptions, sc *types.SystemContext) (*Copier, error) {
c := Copier{extendTimeoutSocket: options.extendTimeoutSocket}
sysContextCopy := *sc
c.systemContext = &sysContextCopy
@ -332,7 +332,6 @@ func NewCopier(options *CopyOptions, sc *types.SystemContext, reportResolvedRefe
c.imageCopyOptions.SignBySigstorePrivateKeyFile = options.SignBySigstorePrivateKeyFile
c.imageCopyOptions.SignSigstorePrivateKeyPassphrase = options.SignSigstorePrivateKeyPassphrase
c.imageCopyOptions.ReportWriter = options.Writer
c.imageCopyOptions.ReportResolvedReference = reportResolvedReference
defaultContainerConfig, err := config.Default()
if err != nil {
@ -489,7 +488,7 @@ func (c *Copier) copyToStorage(ctx context.Context, source, destination types.Im
var resolvedReference types.ImageReference
_, err := c.copyInternal(ctx, source, destination, &resolvedReference)
if err != nil {
return nil, fmt.Errorf("internal error: unable to copy from source %s: %w", source, err)
return nil, fmt.Errorf("internal error: unable to copy from source %s: %w", transports.ImageName(source), err)
}
if resolvedReference == nil {
return nil, fmt.Errorf("internal error: After attempting to copy %s, resolvedReference is nil", source)

View File

@ -463,13 +463,13 @@ func (i *Image) removeRecursive(ctx context.Context, rmMap map[string]*RemoveIma
skipRemove := false
numNames := len(i.Names())
// NOTE: the `numNames == 1` check is not only a performance
// NOTE: the `numNames != 1` check is not only a performance
// optimization but also preserves existing Podman/Docker behaviour.
// If image "foo" is used by a container and has only this tag/name,
// an `rmi foo` will not untag "foo" but instead attempt to remove the
// entire image. If there's a container using "foo", we should get an
// error.
if !(referencedBy == "" || numNames == 1) {
if referencedBy != "" && numNames != 1 {
byID := strings.HasPrefix(i.ID(), referencedBy)
byDigest := strings.HasPrefix(referencedBy, "sha256:")
if !options.Force {

View File

@ -115,7 +115,7 @@ func (r *Runtime) Load(ctx context.Context, path string, options *LoadOptions) (
// Give a decent error message if nothing above worked.
// we want the colon here for the multiline error
//nolint:revive
//nolint:revive,staticcheck
loadError := errors.New("payload does not match any of the supported image formats:")
for _, err := range loadErrors {
loadError = fmt.Errorf("%v\n * %v", loadError, err)

View File

@ -30,7 +30,7 @@ func NormalizeName(name string) (reference.Named, error) {
// Enforce "localhost" if needed.
registry := reference.Domain(named)
if !(strings.ContainsAny(registry, ".:") || registry == "localhost") {
if !strings.ContainsAny(registry, ".:") && registry != "localhost" {
name = toLocalImageName(ref.String())
}

View File

@ -217,7 +217,7 @@ func (r *Runtime) searchImageInRegistry(ctx context.Context, term, registry stri
paramsArr := []SearchResult{}
for i := range limit {
// Check whether query matches filters
if !(filterMatchesAutomatedFilter(&options.Filter, results[i]) && filterMatchesOfficialFilter(&options.Filter, results[i]) && filterMatchesStarFilter(&options.Filter, results[i])) {
if !filterMatchesAutomatedFilter(&options.Filter, results[i]) || !filterMatchesOfficialFilter(&options.Filter, results[i]) || !filterMatchesStarFilter(&options.Filter, results[i]) {
continue
}
official := ""

View File

@ -191,7 +191,7 @@ func (n *cniNetwork) loadNetworks() error {
}
if !types.NameRegex.MatchString(conf.Name) {
logrus.Warnf("CNI config list %s has invalid name, skipping: %v", file, types.RegexError)
logrus.Warnf("CNI config list %s has invalid name, skipping: %v", file, types.ErrInvalidName)
continue
}

View File

@ -19,7 +19,7 @@ func CreateBridge(n NetUtil, network *types.Network, usedNetworks []*net.IPNet,
}
}
if !types.NameRegex.MatchString(network.NetworkInterface) {
return fmt.Errorf("bridge name %s invalid: %w", network.NetworkInterface, types.RegexError)
return fmt.Errorf("bridge name %s invalid: %w", network.NetworkInterface, types.ErrInvalidName)
}
} else {
var err error

View File

@ -23,7 +23,7 @@ func CommonNetworkCreate(n NetUtil, network *types.Network) error {
// validate the name when given
if network.Name != "" {
if !types.NameRegex.MatchString(network.Name) {
return fmt.Errorf("network name %s invalid: %w", network.Name, types.RegexError)
return fmt.Errorf("network name %s invalid: %w", network.Name, types.ErrInvalidName)
}
if _, err := n.Network(network.Name); err == nil {
return fmt.Errorf("network name %s already used: %w", network.Name, types.ErrNetworkExists)

View File

@ -294,10 +294,7 @@ func createIpvlanOrMacvlan(network *types.Network) error {
}
driver := network.Driver
isMacVlan := true
if driver == types.IPVLANNetworkDriver {
isMacVlan = false
}
isMacVlan := driver != types.IPVLANNetworkDriver
// always turn dns off with macvlan, it is not implemented in netavark
// and makes little sense to support with macvlan

View File

@ -248,7 +248,7 @@ func (n *netavarkNetwork) loadNetworks() error {
}
if !types.NameRegex.MatchString(network.Name) {
logrus.Warnf("Network config %q has invalid name: %q, skipping: %v", path, network.Name, types.RegexError)
logrus.Warnf("Network config %q has invalid name: %q, skipping: %v", path, network.Name, types.ErrInvalidName)
continue
}

View File

@ -682,7 +682,7 @@ func openSlirp4netnsPort(apiSocket, proto, hostip string, hostport, guestport ui
if err != nil {
return fmt.Errorf("cannot marshal JSON for slirp4netns: %w", err)
}
if _, err := conn.Write([]byte(fmt.Sprintf("%s\n", data))); err != nil {
if _, err := fmt.Fprintf(conn, "%s\n", data); err != nil {
return fmt.Errorf("cannot write to control socket %s: %w", apiSocket, err)
}
//nolint:errcheck // This cast should never fail, if it does we get a interface

View File

@ -24,8 +24,10 @@ var (
// NameRegex is a regular expression to validate names.
// This must NOT be changed.
NameRegex = regexp.Delayed("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")
// RegexError is thrown in presence of an invalid name.
RegexError = fmt.Errorf("names must match [a-zA-Z0-9][a-zA-Z0-9_.-]*: %w", ErrInvalidArg) // nolint:revive // This lint is new and we do not want to break the API.
// ErrInvalidName is thrown in presence of an invalid name.
ErrInvalidName = fmt.Errorf("names must match [a-zA-Z0-9][a-zA-Z0-9_.-]*: %w", ErrInvalidArg)
// Deprecated: use [ErrInvalidName] instead.
RegexError = ErrInvalidName
// NotHexRegex is a regular expression to check if a string is
// a hexadecimal string.

View File

@ -173,10 +173,10 @@ func Login(ctx context.Context, systemContext *types.SystemContext, opts *LoginO
if opts.StdinPassword {
var stdinPasswordStrBuilder strings.Builder
if opts.Password != "" {
return errors.New("Can't specify both --password-stdin and --password")
return errors.New("can't specify both --password-stdin and --password")
}
if opts.Username == "" {
return errors.New("Must provide --username with --password-stdin")
return errors.New("must provide --username with --password-stdin")
}
scanner := bufio.NewScanner(opts.Stdin)
for scanner.Scan() {

View File

@ -221,7 +221,7 @@ func MoveUnderCgroup(cgroup, subtree string, processes []uint32) error {
}
// root cgroup, skip it
if parts[2] == "/" && !(unifiedMode && parts[1] == "") {
if parts[2] == "/" && (!unifiedMode || parts[1] != "") {
continue
}
@ -261,7 +261,7 @@ func MoveUnderCgroup(cgroup, subtree string, processes []uint32) error {
if len(processes) > 0 {
for _, pid := range processes {
if _, err := f.WriteString(fmt.Sprintf("%d\n", pid)); err != nil {
if _, err := fmt.Fprintf(f, "%d\n", pid); err != nil {
logrus.Debugf("Cannot move process %d to cgroup %q: %v", pid, newCgroup, err)
}
}

View File

@ -17,7 +17,7 @@ func DeviceFromPath(device string) ([]devices.Device, error) {
return nil, err
}
if unshare.IsRootless() && src != dst {
return nil, fmt.Errorf("Renaming device %s to %s is not supported in rootless containers", src, dst)
return nil, fmt.Errorf("renaming device %s to %s is not supported in rootless containers", src, dst)
}
srcInfo, err := os.Stat(src)
if err != nil {

View File

@ -5,10 +5,12 @@ import (
"io"
"math"
"net"
"net/http"
"net/url"
"syscall"
"time"
"github.com/containers/image/v5/docker"
"github.com/docker/distribution/registry/api/errcode"
errcodev2 "github.com/docker/distribution/registry/api/v2"
"github.com/hashicorp/go-multierror"
@ -47,7 +49,7 @@ func IfNecessary(ctx context.Context, operation func() error, options *Options)
logrus.Warnf("Failed, retrying in %s ... (%d/%d). Error: %v", delay, attempt+1, options.MaxRetry, err)
select {
case <-time.After(delay):
break
// Do nothing.
case <-ctx.Done():
return err
}
@ -81,6 +83,13 @@ func IsErrorRetryable(err error) bool {
return false
}
return true
case docker.UnexpectedHTTPStatusError:
// Retry on 502, 502 and 503 http server errors, they appear to be quite common in the field.
// https://github.com/containers/common/issues/2299
if e.StatusCode >= http.StatusBadGateway && e.StatusCode <= http.StatusGatewayTimeout {
return true
}
return false
case *net.OpError:
return IsErrorRetryable(e.Err)
case *url.Error: // This includes errors returned by the net/http client.

View File

@ -166,7 +166,7 @@ func (s *SecretsManager) Store(name string, data []byte, driverType string, opti
return "", err
}
if !(len(data) > 0 && len(data) < maxSecretSize) {
if len(data) == 0 || len(data) >= maxSecretSize {
return "", errDataSize
}
var secr *Secret

View File

@ -322,7 +322,7 @@ func addSubscriptionsFromMountsFile(filePath, mountLabel, containerRunDir string
func containerHasEtcSystemFips(subscriptionsDir, mountPoint string) (bool, error) {
containerEtc, err := securejoin.SecureJoin(mountPoint, "etc")
if err != nil {
return false, fmt.Errorf("Container /etc resolution error: %w", err)
return false, fmt.Errorf("container /etc resolution error: %w", err)
}
if fileutils.Lexists(filepath.Join(containerEtc, "system-fips")) != nil {
logrus.Debug("/etc/system-fips does not exist in the container, not creating /run/secrets/system-fips")
@ -331,7 +331,7 @@ func containerHasEtcSystemFips(subscriptionsDir, mountPoint string) (bool, error
fipsFileTarget, err := securejoin.SecureJoin(mountPoint, "etc/system-fips")
if err != nil {
return false, fmt.Errorf("Container /etc/system-fips resolution error: %w", err)
return false, fmt.Errorf("container /etc/system-fips resolution error: %w", err)
}
if fipsFileTarget != filepath.Join(mountPoint, subscriptionsDir, "system-fips") {
logrus.Warnf("/etc/system-fips exists in the container, but is not a symlink to %[1]v/system-fips; not creating %[1]v/system-fips", subscriptionsDir)
@ -448,24 +448,24 @@ func addFIPSMounts(mounts *[]rspec.Mount, containerRunDir, mountPoint, mountLabe
destPolicyConfig := "/etc/crypto-policies/config"
srcPolicyConfigOnHost, err := securejoin.SecureJoin(mountPoint, srcPolicyConfig)
if err != nil {
return fmt.Errorf("Could not expand %q in container: %w", srcPolicyConfig, err)
return fmt.Errorf("could not expand %q in container: %w", srcPolicyConfig, err)
}
if err = fileutils.Exists(srcPolicyConfigOnHost); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("Could not check whether %q exists in container: %w", srcPolicyConfig, err)
return fmt.Errorf("could not check whether %q exists in container: %w", srcPolicyConfig, err)
}
// /usr/share/crypto-policies/default-fips-config does not exist, let's create it ourselves
cryptoPoliciesConfigFile := filepath.Join(containerRunDir, "fips-config")
if err := os.WriteFile(cryptoPoliciesConfigFile, []byte("FIPS\n"), 0o644); err != nil {
return fmt.Errorf("Failed to write fips config file in container for FIPS mode: %w", err)
return fmt.Errorf("failed to write fips config file in container for FIPS mode: %w", err)
}
if err = label.Relabel(cryptoPoliciesConfigFile, mountLabel, false); err != nil {
return fmt.Errorf("Failed to apply correct labels on fips config file: %w", err)
return fmt.Errorf("failed to apply correct labels on fips config file: %w", err)
}
if err := os.Chown(cryptoPoliciesConfigFile, uid, gid); err != nil {
return fmt.Errorf("Failed to chown fips config file: %w", err)
return fmt.Errorf("failed to chown fips config file: %w", err)
}
srcPolicyConfigOnHost = cryptoPoliciesConfigFile

View File

@ -31,8 +31,9 @@ func GetTimestamp(value string, reference time.Time) (string, error) {
}
var format string
// if the string has a Z or a + or three dashes use parse otherwise use parseinlocation
parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3)
// If the string has a Z, or a +, or three dashes,
// then use time.Parse, otherwise use time.ParseInLocation.
parseInLocation := !strings.ContainsAny(value, "zZ+") && strings.Count(value, "-") != 3
switch {
case strings.Contains(value, "."):

View File

@ -20,10 +20,10 @@ import (
// It returns the path of the created /etc/localtime file if needed.
func ConfigureContainerTimeZone(timezone, containerRunDir, mountPoint, etcPath, containerID string) (localTimePath string, err error) {
var timezonePath string
switch {
case timezone == "":
switch timezone {
case "":
return "", nil
case timezone == "local":
case "local":
timezonePath, err = filepath.EvalSymlinks("/etc/localtime")
if err != nil {
return "", fmt.Errorf("finding local timezone for container %s: %w", containerID, err)

View File

@ -35,9 +35,9 @@ type bodyReader struct {
body io.ReadCloser // The currently open connection we use to read data, or nil if there is nothing to read from / close.
lastRetryOffset int64 // -1 if N/A
lastRetryTime time.Time // time.Time{} if N/A
lastRetryTime time.Time // IsZero() if N/A
offset int64 // Current offset within the blob
lastSuccessTime time.Time // time.Time{} if N/A
lastSuccessTime time.Time // IsZero() if N/A
}
// newBodyReader creates a bodyReader for request path in c.
@ -207,9 +207,9 @@ func (br *bodyReader) Read(p []byte) (int, error) {
}
// millisecondsSinceOptional is like currentTime.Sub(tm).Milliseconds, but it returns a floating-point value.
// If tm is time.Time{}, it returns math.NaN()
// If tm.IsZero(), it returns math.NaN()
func millisecondsSinceOptional(currentTime time.Time, tm time.Time) float64 {
if tm == (time.Time{}) {
if tm.IsZero() {
return math.NaN()
}
return float64(currentTime.Sub(tm).Nanoseconds()) / 1_000_000.0
@ -229,7 +229,7 @@ func (br *bodyReader) errorIfNotReconnecting(originalErr error, redactedURL stri
logrus.Infof("Reading blob body from %s failed (%v), reconnecting after %d bytes…", redactedURL, originalErr, progress)
return nil
}
if br.lastRetryTime == (time.Time{}) {
if br.lastRetryTime.IsZero() {
logrus.Infof("Reading blob body from %s failed (%v), reconnecting (first reconnection)…", redactedURL, originalErr)
return nil
}

View File

@ -213,12 +213,12 @@ type instanceCandidate struct {
digest digest.Digest // Instance digest
}
func (ic instanceCandidate) isPreferredOver(other *instanceCandidate, preferGzip bool) bool {
func (ic instanceCandidate) isPreferredOver(other *instanceCandidate, preferGzip types.OptionalBool) bool {
switch {
case ic.platformIndex != other.platformIndex:
return ic.platformIndex < other.platformIndex
case ic.isZstd != other.isZstd:
if !preferGzip {
if preferGzip != types.OptionalBoolTrue {
return ic.isZstd
} else {
return !ic.isZstd
@ -232,10 +232,6 @@ func (ic instanceCandidate) isPreferredOver(other *instanceCandidate, preferGzip
// chooseInstance is a private equivalent to ChooseInstanceByCompression,
// shared by ChooseInstance and ChooseInstanceByCompression.
func (index *OCI1IndexPublic) chooseInstance(ctx *types.SystemContext, preferGzip types.OptionalBool) (digest.Digest, error) {
didPreferGzip := false
if preferGzip == types.OptionalBoolTrue {
didPreferGzip = true
}
wantedPlatforms := platform.WantedPlatforms(ctx)
var bestMatch *instanceCandidate
bestMatch = nil
@ -251,7 +247,7 @@ func (index *OCI1IndexPublic) chooseInstance(ctx *types.SystemContext, preferGzi
}
candidate.platformIndex = platformIndex
}
if bestMatch == nil || candidate.isPreferredOver(bestMatch, didPreferGzip) {
if bestMatch == nil || candidate.isPreferredOver(bestMatch, preferGzip) {
bestMatch = &candidate
}
}

View File

@ -920,7 +920,7 @@ func tlsCacheGet(config *restConfig) (http.RoundTripper, error) {
// TLSConfigFor returns a tls.Config that will provide the transport level security defined
// by the provided Config. Will return nil if no transport level security is requested.
func tlsConfigFor(c *restConfig) (*tls.Config, error) {
if !(c.HasCA() || c.HasCertAuth() || c.Insecure) {
if !c.HasCA() && !c.HasCertAuth() && !c.Insecure {
return nil, nil
}
if c.HasCA() && c.Insecure {

View File

@ -235,7 +235,7 @@ func parseShortNameValue(alias string) (reference.Named, error) {
}
registry := reference.Domain(named)
if !(strings.ContainsAny(registry, ".:") || registry == "localhost") {
if !strings.ContainsAny(registry, ".:") && registry != "localhost" {
return nil, fmt.Errorf("invalid alias %q: must contain registry and repository", alias)
}

View File

@ -126,7 +126,7 @@ lint_task:
folder: $GOPATH/pkg/mod
build_script: |
apt-get update
apt-get install -y libbtrfs-dev
apt-get install -y libbtrfs-dev libsubid-dev
test_script: |
make TAGS=regex_precompile local-validate
make lint

View File

@ -1,7 +1,17 @@
---
run:
concurrency: 6
timeout: 5m
linters:
version: "2"
formatters:
enable:
- gofumpt
linters:
exclusions:
presets:
- comments
- std-error-handling
settings:
staticcheck:
checks:
- all
- -ST1003 # https://staticcheck.dev/docs/checks/#ST1003 Poorly chosen identifier.
- -QF1008 # https://staticcheck.dev/docs/checks/#QF1008 Omit embedded fields from selector expression.

View File

@ -35,7 +35,7 @@ TESTFLAGS := $(shell $(GO) test -race $(BUILDFLAGS) ./pkg/stringutils 2>&1 > /de
# N/B: This value is managed by Renovate, manual changes are
# possible, as long as they don't disturb the formatting
# (i.e. DO NOT ADD A 'v' prefix!)
GOLANGCI_LINT_VERSION := 1.64.8
GOLANGCI_LINT_VERSION := 2.0.2
default all: local-binary docs local-validate local-cross ## validate all checks, build and cross-build\nbinaries and docs

View File

@ -517,7 +517,7 @@ func (a *Driver) isParent(id, parent string) bool {
if parent == "" && len(parents) > 0 {
return false
}
return !(len(parents) > 0 && parent != parents[0])
return len(parents) == 0 || parent == parents[0]
}
// Diff produces an archive of the changes between the specified
@ -778,6 +778,6 @@ func (a *Driver) SupportsShifting() bool {
}
// Dedup performs deduplication of the driver's storage.
func (d *Driver) Dedup(req graphdriver.DedupArgs) (graphdriver.DedupResult, error) {
func (a *Driver) Dedup(req graphdriver.DedupArgs) (graphdriver.DedupResult, error) {
return graphdriver.DedupResult{}, nil
}

View File

@ -40,7 +40,7 @@ const (
)
// CopyRegularToFile copies the content of a file to another
func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { // nolint: revive,golint
func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint: revive
srcFile, err := os.Open(srcPath)
if err != nil {
return err
@ -72,7 +72,7 @@ func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, c
}
// CopyRegular copies the content of a file to another
func CopyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { // nolint: revive,golint
func CopyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint: revive
// If the destination file already exists, we shouldn't blow it away
dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileinfo.Mode())
if err != nil {

View File

@ -24,7 +24,7 @@ func DirCopy(srcDir, dstDir string, _ Mode, _ bool) error {
}
// CopyRegularToFile copies the content of a file to another
func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint: revive,golint // "func name will be used as copy.CopyRegularToFile by other packages, and that stutters"
func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint: revive // "func name will be used as copy.CopyRegularToFile by other packages, and that stutters"
f, err := os.Open(srcPath)
if err != nil {
return err
@ -35,6 +35,6 @@ func CopyRegularToFile(srcPath string, dstFile *os.File, fileinfo os.FileInfo, c
}
// CopyRegular copies the content of a file to another
func CopyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint:revive,golint // "func name will be used as copy.CopyRegular by other packages, and that stutters"
func CopyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error { //nolint:revive // "func name will be used as copy.CopyRegular by other packages, and that stutters"
return chrootarchive.NewArchiver(nil).CopyWithTar(srcPath, dstPath)
}

View File

@ -54,8 +54,8 @@ type MountOpts struct {
// Mount label is the MAC Labels to assign to mount point (SELINUX)
MountLabel string
// UidMaps & GidMaps are the User Namespace mappings to be assigned to content in the mount point
UidMaps []idtools.IDMap //nolint: revive,golint
GidMaps []idtools.IDMap //nolint: revive,golint
UidMaps []idtools.IDMap //nolint: revive
GidMaps []idtools.IDMap //nolint: revive
Options []string
// Volatile specifies whether the container storage can be optimized

View File

@ -53,7 +53,7 @@ func generateComposeFsBlob(verityDigests map[string]string, toc interface{}, com
}
destFile := getComposefsBlob(composefsDir)
writerJson, err := getComposeFsHelper()
writerJSON, err := getComposeFsHelper()
if err != nil {
return fmt.Errorf("failed to find mkcomposefs: %w", err)
}
@ -74,7 +74,7 @@ func generateComposeFsBlob(verityDigests map[string]string, toc interface{}, com
defer outFile.Close()
errBuf := &bytes.Buffer{}
cmd := exec.Command(writerJson, "--from-file", "-", "-")
cmd := exec.Command(writerJSON, "--from-file", "-", "-")
cmd.Stderr = errBuf
cmd.Stdin = dumpReader
cmd.Stdout = outFile

View File

@ -130,6 +130,9 @@ type Driver struct {
usingMetacopy bool
usingComposefs bool
stagingDirsLocksMutex sync.Mutex
// stagingDirsLocks access is not thread safe, it is required that callers take
// stagingDirsLocksMutex on each access to guard against concurrent map writes.
stagingDirsLocks map[string]*lockfile.LockFile
supportsIDMappedMounts *bool
@ -428,17 +431,18 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error)
}
d := &Driver{
name: "overlay",
home: home,
imageStore: options.ImageStore,
runhome: runhome,
ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(fileSystemType)),
supportsDType: supportsDType,
usingMetacopy: usingMetacopy,
supportsVolatile: supportsVolatile,
usingComposefs: opts.useComposefs,
options: *opts,
stagingDirsLocks: make(map[string]*lockfile.LockFile),
name: "overlay",
home: home,
imageStore: options.ImageStore,
runhome: runhome,
ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(fileSystemType)),
supportsDType: supportsDType,
usingMetacopy: usingMetacopy,
supportsVolatile: supportsVolatile,
usingComposefs: opts.useComposefs,
options: *opts,
stagingDirsLocksMutex: sync.Mutex{},
stagingDirsLocks: make(map[string]*lockfile.LockFile),
}
d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, graphdriver.NewNaiveLayerIDMapUpdater(d))
@ -639,6 +643,8 @@ func SupportsNativeOverlay(home, runhome string) (bool, error) {
case "true":
logrus.Debugf("overlay: storage already configured with a mount-program")
return false, nil
case "false":
// Do nothing.
default:
needsMountProgram, err := scanForMountProgramIndicators(home)
if err != nil && !os.IsNotExist(err) {
@ -652,7 +658,6 @@ func SupportsNativeOverlay(home, runhome string) (bool, error) {
}
// fall through to check if we find ourselves needing to use a
// mount program now
case "false":
}
for _, dir := range []string{home, runhome} {
@ -867,10 +872,12 @@ func (d *Driver) Cleanup() error {
// pruneStagingDirectories cleans up any staging directory that was leaked.
// It returns whether any staging directory is still present.
func (d *Driver) pruneStagingDirectories() bool {
d.stagingDirsLocksMutex.Lock()
for _, lock := range d.stagingDirsLocks {
lock.Unlock()
}
d.stagingDirsLocks = make(map[string]*lockfile.LockFile)
clear(d.stagingDirsLocks)
d.stagingDirsLocksMutex.Unlock()
anyPresent := false
@ -2168,10 +2175,12 @@ func (d *Driver) DiffGetter(id string) (_ graphdriver.FileGetCloser, Err error)
func (d *Driver) CleanupStagingDirectory(stagingDirectory string) error {
parentStagingDir := filepath.Dir(stagingDirectory)
d.stagingDirsLocksMutex.Lock()
if lock, ok := d.stagingDirsLocks[parentStagingDir]; ok {
delete(d.stagingDirsLocks, parentStagingDir)
lock.Unlock()
}
d.stagingDirsLocksMutex.Unlock()
return os.RemoveAll(parentStagingDir)
}
@ -2230,11 +2239,15 @@ func (d *Driver) ApplyDiffWithDiffer(options *graphdriver.ApplyDiffWithDifferOpt
}
defer func() {
if errRet != nil {
d.stagingDirsLocksMutex.Lock()
delete(d.stagingDirsLocks, layerDir)
d.stagingDirsLocksMutex.Unlock()
lock.Unlock()
}
}()
d.stagingDirsLocksMutex.Lock()
d.stagingDirsLocks[layerDir] = lock
d.stagingDirsLocksMutex.Unlock()
lock.Lock()
logrus.Debugf("Applying differ in %s", applyDir)
@ -2266,10 +2279,12 @@ func (d *Driver) ApplyDiffFromStagingDirectory(id, parent string, diffOutput *gr
parentStagingDir := filepath.Dir(stagingDirectory)
defer func() {
d.stagingDirsLocksMutex.Lock()
if lock, ok := d.stagingDirsLocks[parentStagingDir]; ok {
delete(d.stagingDirsLocks, parentStagingDir)
lock.Unlock()
}
d.stagingDirsLocksMutex.Unlock()
}()
diffPath, err := d.getDiffPath(id)

View File

@ -13,7 +13,7 @@ import (
"github.com/sirupsen/logrus"
)
var notSupported = errors.New("reflinks are not supported on this platform")
var errNotSupported = errors.New("reflinks are not supported on this platform")
const (
DedupHashInvalid DedupHashMethod = iota
@ -134,7 +134,7 @@ func DedupDirs(dirs []string, options DedupOptions) (DedupResult, error) {
break
}
logrus.Debugf("Failed to deduplicate: %v", err)
if errors.Is(err, notSupported) {
if errors.Is(err, errNotSupported) {
return dedupBytes, err
}
}
@ -153,7 +153,7 @@ func DedupDirs(dirs []string, options DedupOptions) (DedupResult, error) {
return nil
}); err != nil {
// if reflinks are not supported, return immediately without errors
if errors.Is(err, notSupported) {
if errors.Is(err, errNotSupported) {
return res, nil
}
return res, err

View File

@ -98,7 +98,7 @@ func (d *dedupFiles) dedup(src, dst string, fiDst fs.FileInfo) (uint64, error) {
}
if errors.Is(err, unix.ENOTSUP) {
return 0, notSupported
return 0, errNotSupported
}
return 0, fmt.Errorf("failed to clone file %q: %w", src, err)
}

View File

@ -9,19 +9,19 @@ import (
type dedupFiles struct{}
func newDedupFiles() (*dedupFiles, error) {
return nil, notSupported
return nil, errNotSupported
}
// isFirstVisitOf records that the file is being processed. Returns true if the file was already visited.
func (d *dedupFiles) isFirstVisitOf(fi fs.FileInfo) (bool, error) {
return false, notSupported
return false, errNotSupported
}
// dedup deduplicates the file at src path to dst path
func (d *dedupFiles) dedup(src, dst string, fiDst fs.FileInfo) (uint64, error) {
return 0, notSupported
return 0, errNotSupported
}
func readAllFile(path string, info fs.FileInfo, fn func([]byte) (string, error)) (string, error) {
return "", notSupported
return "", errNotSupported
}

View File

@ -687,7 +687,7 @@ func extractTarFileEntry(path, extractDir string, hdr *tar.Header, reader io.Rea
case tar.TypeDir:
// Create directory unless it exists as a directory already.
// In that case we just want to merge the two
if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
if fi, err := os.Lstat(path); err != nil || !fi.IsDir() {
if err := os.Mkdir(path, mask); err != nil {
return err
}
@ -1130,7 +1130,7 @@ loop:
continue
}
if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
if !fi.IsDir() || hdr.Typeflag != tar.TypeDir {
if err := os.RemoveAll(path); err != nil {
return err
}

View File

@ -70,7 +70,7 @@ func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] }
// files, we handle this by comparing for exact times, *or* same
// second count and either a or b having exactly 0 nanoseconds
func sameFsTime(a, b time.Time) bool {
return a == b ||
return a.Equal(b) ||
(a.Unix() == b.Unix() &&
(a.Nanosecond() == 0 || b.Nanosecond() == 0))
}

View File

@ -174,14 +174,7 @@ func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) {
ix1 := 0
ix2 := 0
for {
if ix1 >= len(names1) {
break
}
if ix2 >= len(names2) {
break
}
for ix1 < len(names1) && ix2 < len(names2) {
ni1 := names1[ix1]
ni2 := names2[ix2]

View File

@ -178,7 +178,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64,
if err := resetImmutable(path, &fi); err != nil {
return 0, err
}
if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
if !fi.IsDir() || hdr.Typeflag != tar.TypeDir {
if err := os.RemoveAll(path); err != nil {
return 0, err
}

View File

@ -7,6 +7,7 @@ import (
"fmt"
"io"
"maps"
"slices"
"strconv"
"time"
@ -17,7 +18,6 @@ import (
"github.com/vbatts/tar-split/archive/tar"
"github.com/vbatts/tar-split/tar/asm"
"github.com/vbatts/tar-split/tar/storage"
expMaps "golang.org/x/exp/maps"
)
const (
@ -310,7 +310,7 @@ func ensureTOCMatchesTarSplit(toc *minimal.TOC, tarSplit []byte) error {
return err
}
if len(pendingFiles) != 0 {
remaining := expMaps.Keys(pendingFiles)
remaining := slices.Collect(maps.Keys(pendingFiles))
if len(remaining) > 5 {
remaining = remaining[:5] // Just to limit the size of the output.
}

View File

@ -142,10 +142,7 @@ func (rc *rollingChecksumReader) Read(b []byte) (bool, int, error) {
rc.IsLastChunkZeros = false
if rc.pendingHole > 0 {
toCopy := int64(len(b))
if rc.pendingHole < toCopy {
toCopy = rc.pendingHole
}
toCopy := min(rc.pendingHole, int64(len(b)))
rc.pendingHole -= toCopy
for i := int64(0); i < toCopy; i++ {
b[i] = 0

View File

@ -698,18 +698,12 @@ func (c *chunkedDiffer) prepareCompressedStreamToFile(partCompression compressed
// hashHole writes SIZE zeros to the specified hasher
func hashHole(h hash.Hash, size int64, copyBuffer []byte) error {
count := int64(len(copyBuffer))
if size < count {
count = size
}
count := min(size, int64(len(copyBuffer)))
for i := int64(0); i < count; i++ {
copyBuffer[i] = 0
}
for size > 0 {
count = int64(len(copyBuffer))
if size < count {
count = size
}
count = min(size, int64(len(copyBuffer)))
if _, err := h.Write(copyBuffer[:count]); err != nil {
return err
}
@ -1271,7 +1265,7 @@ func getBlobAtConverterGoroutine(stream chan streamOrErr, streams chan io.ReadCl
tooManyStreams := false
streamsSoFar := 0
err := errors.New("Unexpected error in getBlobAtGoroutine")
err := errors.New("unexpected error in getBlobAtGoroutine")
defer func() {
if err != nil {

View File

@ -25,7 +25,7 @@ func CreateIDMappedMount(source, target string, pid int) error {
}
defer userNsFile.Close()
targetDirFd, err := unix.OpenTree(0, source, unix.OPEN_TREE_CLONE)
targetDirFd, err := unix.OpenTree(unix.AT_FDCWD, source, unix.OPEN_TREE_CLONE)
if err != nil {
return &os.PathError{Op: "open_tree", Path: source, Err: err}
}

View File

@ -429,25 +429,25 @@ func parseOverrideXattr(xstat []byte) (Stat, error) {
var stat Stat
attrs := strings.Split(string(xstat), ":")
if len(attrs) < 3 {
return stat, fmt.Errorf("The number of parts in %s is less than 3",
return stat, fmt.Errorf("the number of parts in %s is less than 3",
ContainersOverrideXattr)
}
value, err := strconv.ParseUint(attrs[0], 10, 32)
if err != nil {
return stat, fmt.Errorf("Failed to parse UID: %w", err)
return stat, fmt.Errorf("failed to parse UID: %w", err)
}
stat.IDs.UID = int(value)
value, err = strconv.ParseUint(attrs[1], 10, 32)
if err != nil {
return stat, fmt.Errorf("Failed to parse GID: %w", err)
return stat, fmt.Errorf("failed to parse GID: %w", err)
}
stat.IDs.GID = int(value)
value, err = strconv.ParseUint(attrs[2], 8, 32)
if err != nil {
return stat, fmt.Errorf("Failed to parse mode: %w", err)
return stat, fmt.Errorf("failed to parse mode: %w", err)
}
stat.Mode = os.FileMode(value) & os.ModePerm
if value&0o1000 != 0 {
@ -484,7 +484,7 @@ func parseOverrideXattr(xstat []byte) (Stat, error) {
return stat, err
}
} else {
return stat, fmt.Errorf("Invalid file type %s", typ)
return stat, fmt.Errorf("invalid file type %s", typ)
}
}
return stat, nil
@ -494,18 +494,18 @@ func parseDevice(typ string) (int, int, error) {
parts := strings.Split(typ, "-")
// If there are more than 3 parts, just ignore them to be forward compatible
if len(parts) < 3 {
return 0, 0, fmt.Errorf("Invalid device type %s", typ)
return 0, 0, fmt.Errorf("invalid device type %s", typ)
}
if parts[0] != "block" && parts[0] != "char" {
return 0, 0, fmt.Errorf("Invalid device type %s", typ)
return 0, 0, fmt.Errorf("invalid device type %s", typ)
}
major, err := strconv.Atoi(parts[1])
if err != nil {
return 0, 0, fmt.Errorf("Failed to parse major number: %w", err)
return 0, 0, fmt.Errorf("failed to parse major number: %w", err)
}
minor, err := strconv.Atoi(parts[2])
if err != nil {
return 0, 0, fmt.Errorf("Failed to parse minor number: %w", err)
return 0, 0, fmt.Errorf("failed to parse minor number: %w", err)
}
return major, minor, nil
}

View File

@ -29,9 +29,7 @@ struct subid_range get_range(struct subid_range *ranges, int i)
*/
import "C"
var (
onceInit sync.Once
)
var onceInit sync.Once
func readSubid(username string, isUser bool) (ranges, error) {
var ret ranges

View File

@ -93,10 +93,7 @@ loop0:
}
// add new byte slice to the buffers slice and continue writing
nextCap := b.Cap() * 2
if nextCap > maxCap {
nextCap = maxCap
}
nextCap := min(b.Cap()*2, maxCap)
bp.buf = append(bp.buf, getBuffer(nextCap))
}
bp.wait.Broadcast()

View File

@ -16,8 +16,8 @@ import (
// Loopback related errors
var (
ErrAttachLoopbackDevice = errors.New("loopback attach failed")
ErrGetLoopbackBackingFile = errors.New("Unable to get loopback backing file")
ErrSetCapacity = errors.New("Unable set loopback capacity")
ErrGetLoopbackBackingFile = errors.New("unable to get loopback backing file")
ErrSetCapacity = errors.New("unable set loopback capacity")
)
func stringToLoopName(src string) [LoNameSize]uint8 {

View File

@ -32,9 +32,9 @@ type Cmd struct {
*exec.Cmd
UnshareFlags int
UseNewuidmap bool
UidMappings []specs.LinuxIDMapping // nolint: revive,golint
UidMappings []specs.LinuxIDMapping //nolint: revive
UseNewgidmap bool
GidMappings []specs.LinuxIDMapping // nolint: revive,golint
GidMappings []specs.LinuxIDMapping //nolint: revive
GidMappingsEnableSetgroups bool
Setsid bool
Setpgrp bool
@ -249,7 +249,7 @@ func (c *Cmd) Start() (retErr error) {
if err != nil {
return fmt.Errorf("finding newgidmap: %w", err)
}
cmd := exec.Command(path, append([]string{pidString}, strings.Fields(strings.Replace(g.String(), "\n", " ", -1))...)...)
cmd := exec.Command(path, append([]string{pidString}, strings.Fields(g.String())...)...)
g.Reset()
cmd.Stdout = g
cmd.Stderr = g
@ -267,7 +267,7 @@ func (c *Cmd) Start() (retErr error) {
}
logrus.Warnf("Falling back to single mapping")
g.Reset()
g.Write([]byte(fmt.Sprintf("0 %d 1\n", os.Getegid())))
fmt.Fprintf(g, "0 %d 1\n", os.Getegid())
}
}
if !gidmapSet {
@ -309,7 +309,7 @@ func (c *Cmd) Start() (retErr error) {
if err != nil {
return fmt.Errorf("finding newuidmap: %w", err)
}
cmd := exec.Command(path, append([]string{pidString}, strings.Fields(strings.Replace(u.String(), "\n", " ", -1))...)...)
cmd := exec.Command(path, append([]string{pidString}, strings.Fields(u.String())...)...)
u.Reset()
cmd.Stdout = u
cmd.Stderr = u
@ -328,7 +328,7 @@ func (c *Cmd) Start() (retErr error) {
logrus.Warnf("Falling back to single mapping")
u.Reset()
u.Write([]byte(fmt.Sprintf("0 %d 1\n", os.Geteuid())))
fmt.Fprintf(u, "0 %d 1\n", os.Geteuid())
}
}
if !uidmapSet {

View File

@ -3723,7 +3723,7 @@ func makeBigDataBaseName(key string) string {
if err != nil || size != 1 {
break
}
if ch != '.' && !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'z') {
if ch != '.' && (ch < '0' || ch > '9') && (ch < 'a' || ch > 'z') {
break
}
}

View File

@ -394,7 +394,7 @@ func ReloadConfigurationFileIfNeeded(configFile string, storeOptions *StoreOptio
}
mtime := fi.ModTime()
if prevReloadConfig.storeOptions != nil && prevReloadConfig.mod == mtime && prevReloadConfig.configFile == configFile {
if prevReloadConfig.storeOptions != nil && mtime.Equal(prevReloadConfig.mod) && prevReloadConfig.configFile == configFile {
*storeOptions = *prevReloadConfig.storeOptions
return nil
}

View File

@ -14,7 +14,7 @@ import (
func expandEnvPath(path string, rootlessUID int) (string, error) {
var err error
path = strings.Replace(path, "$UID", strconv.Itoa(rootlessUID), -1)
path = strings.ReplaceAll(path, "$UID", strconv.Itoa(rootlessUID))
path = os.ExpandEnv(path)
newpath, err := filepath.EvalSymlinks(path)
if err != nil {
@ -61,7 +61,7 @@ func reloadConfigurationFileIfNeeded(configFile string, storeOptions *StoreOptio
}
mtime := fi.ModTime()
if prevReloadConfig.storeOptions != nil && prevReloadConfig.mod == mtime && prevReloadConfig.configFile == configFile {
if prevReloadConfig.storeOptions != nil && mtime.Equal(prevReloadConfig.mod) && prevReloadConfig.configFile == configFile {
*storeOptions = *prevReloadConfig.storeOptions
return
}

View File

@ -276,10 +276,7 @@ func (s *store) getAutoUserNS(options *types.AutoUserNsOptions, image *Image, rl
// bigger than s.autoNsMaxSize.
// This is a best effort heuristic.
if requestedSize == 0 {
size = initialSize
if s.autoNsMinSize > size {
size = s.autoNsMinSize
}
size = max(s.autoNsMinSize, initialSize)
if image != nil {
sizeFromImage, err := s.getMaxSizeFromImage(image, rlstore, lstores, options.PasswdFile, options.GroupFile)
if err != nil {