vendor latest c/common main

Includes several rootless-netns fixes.

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
This commit is contained in:
Paul Holzinger
2024-04-02 18:45:45 +02:00
parent 976640474b
commit ce04fbc16a
47 changed files with 661 additions and 267 deletions

View File

@ -13,6 +13,7 @@ import (
dockerArchiveTransport "github.com/containers/image/v5/docker/archive"
ociArchiveTransport "github.com/containers/image/v5/oci/archive"
ociTransport "github.com/containers/image/v5/oci/layout"
"github.com/containers/image/v5/transports"
"github.com/containers/image/v5/types"
"github.com/sirupsen/logrus"
)
@ -21,6 +22,30 @@ type LoadOptions struct {
CopyOptions
}
// doLoadReference does the heavy lifting for LoadReference() and Load(),
// without adding debug messages or handling defaults.
func (r *Runtime) doLoadReference(ctx context.Context, ref types.ImageReference, options *LoadOptions) (images []string, transportName string, err error) {
transportName = ref.Transport().Name()
switch transportName {
case dockerArchiveTransport.Transport.Name():
images, err = r.loadMultiImageDockerArchive(ctx, ref, &options.CopyOptions)
default:
images, err = r.copyFromDefault(ctx, ref, &options.CopyOptions)
}
return images, ref.Transport().Name(), err
}
// LoadReference loads one or more images from the specified location.
func (r *Runtime) LoadReference(ctx context.Context, ref types.ImageReference, options *LoadOptions) ([]string, error) {
logrus.Debugf("Loading image from %q", transports.ImageName(ref))
if options == nil {
options = &LoadOptions{}
}
images, _, err := r.doLoadReference(ctx, ref, options)
return images, err
}
// Load loads one or more images (depending on the transport) from the
// specified path. The path may point to an image the following transports:
// oci, oci-archive, dir, docker-archive.
@ -41,8 +66,7 @@ func (r *Runtime) Load(ctx context.Context, path string, options *LoadOptions) (
if err != nil {
return nil, ociTransport.Transport.Name(), err
}
images, err := r.copyFromDefault(ctx, ref, &options.CopyOptions)
return images, ociTransport.Transport.Name(), err
return r.doLoadReference(ctx, ref, options)
},
// OCI-ARCHIVE
@ -52,8 +76,7 @@ func (r *Runtime) Load(ctx context.Context, path string, options *LoadOptions) (
if err != nil {
return nil, ociArchiveTransport.Transport.Name(), err
}
images, err := r.copyFromDefault(ctx, ref, &options.CopyOptions)
return images, ociArchiveTransport.Transport.Name(), err
return r.doLoadReference(ctx, ref, options)
},
// DOCKER-ARCHIVE
@ -63,8 +86,7 @@ func (r *Runtime) Load(ctx context.Context, path string, options *LoadOptions) (
if err != nil {
return nil, dockerArchiveTransport.Transport.Name(), err
}
images, err := r.loadMultiImageDockerArchive(ctx, ref, &options.CopyOptions)
return images, dockerArchiveTransport.Transport.Name(), err
return r.doLoadReference(ctx, ref, options)
},
// DIR
@ -74,8 +96,7 @@ func (r *Runtime) Load(ctx context.Context, path string, options *LoadOptions) (
if err != nil {
return nil, dirTransport.Transport.Name(), err
}
images, err := r.copyFromDefault(ctx, ref, &options.CopyOptions)
return images, dirTransport.Transport.Name(), err
return r.doLoadReference(ctx, ref, options)
},
} {
loadedImages, transportName, err := f()

View File

@ -314,6 +314,29 @@ type ManifestListAddOptions struct {
Password string
}
func (m *ManifestList) parseNameToExtantReference(ctx context.Context, name string, manifestList bool, what string) (types.ImageReference, error) {
ref, err := alltransports.ParseImageName(name)
if err != nil {
withDocker := fmt.Sprintf("%s://%s", docker.Transport.Name(), name)
ref, err = alltransports.ParseImageName(withDocker)
if err == nil {
var src types.ImageSource
src, err = ref.NewImageSource(ctx, nil)
if err == nil {
src.Close()
}
}
if err != nil {
image, _, lookupErr := m.image.runtime.LookupImage(name, &LookupImageOptions{ManifestList: manifestList})
if lookupErr != nil {
return nil, fmt.Errorf("locating %s: %q: %w; %q: %w", what, withDocker, err, name, lookupErr)
}
ref, err = image.storageReference, nil
}
}
return ref, err
}
// Add adds one or more manifests to the manifest list and returns the digest
// of the added instance.
func (m *ManifestList) Add(ctx context.Context, name string, options *ManifestListAddOptions) (digest.Digest, error) {
@ -321,13 +344,9 @@ func (m *ManifestList) Add(ctx context.Context, name string, options *ManifestLi
options = &ManifestListAddOptions{}
}
ref, err := alltransports.ParseImageName(name)
ref, err := m.parseNameToExtantReference(ctx, name, false, "image to add to manifest list")
if err != nil {
withDocker := fmt.Sprintf("%s://%s", docker.Transport.Name(), name)
ref, err = alltransports.ParseImageName(withDocker)
if err != nil {
return "", err
}
return "", err
}
// Now massage in the copy-related options into the system context.
@ -428,17 +447,9 @@ func (m *ManifestList) AddArtifact(ctx context.Context, options *ManifestListAdd
opts.LayerMediaType = &options.LayerType
}
if options.Subject != "" {
ref, err := alltransports.ParseImageName(options.Subject)
ref, err := m.parseNameToExtantReference(ctx, options.Subject, true, "subject for artifact manifest")
if err != nil {
withDocker := fmt.Sprintf("%s://%s", docker.Transport.Name(), options.Subject)
ref, err = alltransports.ParseImageName(withDocker)
if err != nil {
image, _, err := m.image.runtime.LookupImage(options.Subject, &LookupImageOptions{ManifestList: true})
if err != nil {
return "", fmt.Errorf("locating subject for artifact manifest: %w", err)
}
ref = image.storageReference
}
return "", err
}
opts.SubjectReference = ref
}
@ -541,17 +552,9 @@ func (m *ManifestList) AnnotateInstance(d digest.Digest, options *ManifestListAn
}
}
if options.Subject != "" {
ref, err := alltransports.ParseImageName(options.Subject)
ref, err := m.parseNameToExtantReference(ctx, options.Subject, true, "subject for image index")
if err != nil {
withDocker := fmt.Sprintf("%s://%s", docker.Transport.Name(), options.Subject)
ref, err = alltransports.ParseImageName(withDocker)
if err != nil {
image, _, err := m.image.runtime.LookupImage(options.Subject, &LookupImageOptions{ManifestList: true})
if err != nil {
return fmt.Errorf("locating subject for image index: %w", err)
}
ref = image.storageReference
}
return err
}
src, err := ref.NewImageSource(ctx, &m.image.runtime.systemContext)
if err != nil {

View File

@ -495,6 +495,14 @@ func prepareAddWithCompression(variants []string) ([]cp.OptionCompressionVariant
return res, nil
}
func mapToSlice(m map[string]string) []string {
slice := make([]string, 0, len(m))
for key, value := range m {
slice = append(slice, key+"="+value)
}
return slice
}
// Add adds information about the specified image to the list, computing the
// image's manifest's digest, retrieving OS and architecture information from
// the image's configuration, and recording the image's reference so that it
@ -516,6 +524,7 @@ func (l *list) Add(ctx context.Context, sys *types.SystemContext, ref types.Imag
Size int64
ConfigInfo types.BlobInfo
ArtifactType string
URLs []string
}
var instanceInfos []instanceInfo
var manifestDigest digest.Digest
@ -547,6 +556,8 @@ func (l *list) Add(ctx context.Context, sys *types.SystemContext, ref types.Imag
OSFeatures: append([]string{}, platform.OSFeatures...),
Size: instance.Size,
ArtifactType: instance.ArtifactType,
Annotations: mapToSlice(instance.Annotations),
URLs: instance.URLs,
}
instanceInfos = append(instanceInfos, instanceInfo)
}
@ -578,6 +589,8 @@ func (l *list) Add(ctx context.Context, sys *types.SystemContext, ref types.Imag
OSFeatures: append([]string{}, platform.OSFeatures...),
Size: instance.Size,
ArtifactType: instance.ArtifactType,
Annotations: mapToSlice(instance.Annotations),
URLs: instance.URLs,
}
instanceInfos = append(instanceInfos, instanceInfo)
added = true
@ -649,6 +662,9 @@ func (l *list) Add(ctx context.Context, sys *types.SystemContext, ref types.Imag
if err != nil {
return "", fmt.Errorf("adding instance with digest %q: %w", *instanceInfo.instanceDigest, err)
}
if err = l.List.SetURLs(*instanceInfo.instanceDigest, instanceInfo.URLs); err != nil {
return "", fmt.Errorf("setting URLs for instance with digest %q: %w", *instanceInfo.instanceDigest, err)
}
if _, ok := l.instances[*instanceInfo.instanceDigest]; !ok {
l.instances[*instanceInfo.instanceDigest] = transports.ImageName(ref)
}

View File

@ -240,6 +240,15 @@ func (r *Runtime) copyFromDefault(ctx context.Context, ref types.ImageReference,
// Figure out a name for the storage destination.
var storageName, imageName string
switch ref.Transport().Name() {
case registryTransport.Transport.Name():
// Normalize to docker.io if needed (see containers/podman/issues/10998).
named, err := reference.ParseNormalizedNamed(strings.TrimLeft(ref.StringWithinTransport(), ":/"))
if err != nil {
return nil, err
}
imageName = named.String()
storageName = imageName
case dockerDaemonTransport.Transport.Name():
// Normalize to docker.io if needed (see containers/podman/issues/10998).
named, err := reference.ParseNormalizedNamed(ref.StringWithinTransport())

View File

@ -100,18 +100,37 @@ func (n *Netns) getOrCreateNetns() (ns.NetNS, bool, error) {
nsPath := n.getPath(rootlessNetnsDir)
nsRef, err := ns.GetNS(nsPath)
if err == nil {
// TODO check if slirp4netns is alive
return nsRef, false, nil
}
logrus.Debugf("Creating rootless network namespace at %q", nsPath)
// We have to create the netns dir again here because it is possible
// that cleanup() removed it.
if err := os.MkdirAll(n.dir, 0o700); err != nil {
return nil, false, wrapError("", err)
}
netns, err := netns.NewNSAtPath(nsPath)
if err != nil {
return nil, false, wrapError("create netns", err)
pidPath := n.getPath(rootlessNetNsConnPidFile)
pid, err := readPidFile(pidPath)
if err == nil {
// quick check if pasta/slirp4netns are still running
err := unix.Kill(pid, 0)
if err == nil {
// All good, return the netns.
return nsRef, false, nil
}
// Print warnings in case things went wrong, we might be able to recover
// but maybe not so make sure to leave some hints so we can figure out what went wrong.
if errors.Is(err, unix.ESRCH) {
logrus.Warn("rootless netns program no longer running, trying to start it again")
} else {
logrus.Warnf("failed to check if rootless netns program is running: %v, trying to start it again", err)
}
} else {
logrus.Warnf("failed to read rootless netns program pid: %v", err)
}
// In case of errors continue and setup the network cmd again.
} else {
logrus.Debugf("Creating rootless network namespace at %q", nsPath)
// We have to create the netns dir again here because it is possible
// that cleanup() removed it.
if err := os.MkdirAll(n.dir, 0o700); err != nil {
return nil, false, wrapError("", err)
}
nsRef, err = netns.NewNSAtPath(nsPath)
if err != nil {
return nil, false, wrapError("create netns", err)
}
}
switch strings.ToLower(n.config.Network.DefaultRootlessNetworkCmd) {
case "", slirp4netns.BinaryName:
@ -121,7 +140,17 @@ func (n *Netns) getOrCreateNetns() (ns.NetNS, bool, error) {
default:
err = fmt.Errorf("invalid rootless network command %q", n.config.Network.DefaultRootlessNetworkCmd)
}
return netns, true, err
// If pasta or slirp4netns fail here we need to get rid of the netns again to not leak it,
// otherwise the next command thinks the netns was successfully setup.
if err != nil {
if nerr := netns.UnmountNS(nsPath); nerr != nil {
logrus.Error(nerr)
}
_ = nsRef.Close()
return nil, false, err
}
return nsRef, true, nil
}
func (n *Netns) cleanup() error {
@ -165,11 +194,7 @@ func (n *Netns) setupPasta(nsPath string) error {
if systemd.RunsOnSystemd() {
// Treat these as fatal - if pasta failed to write a PID file something is probably wrong.
pidfile, err := os.ReadFile(pidPath)
if err != nil {
return fmt.Errorf("unable to open pasta PID file: %w", err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(pidfile)))
pid, err := readPidFile(pidPath)
if err != nil {
return fmt.Errorf("unable to decode pasta PID: %w", err)
}
@ -245,16 +270,12 @@ func (n *Netns) setupSlirp4netns(nsPath string) error {
func (n *Netns) cleanupRootlessNetns() error {
pidFile := n.getPath(rootlessNetNsConnPidFile)
b, err := os.ReadFile(pidFile)
pid, err := readPidFile(pidFile)
if err == nil {
var i int
i, err = strconv.Atoi(strings.TrimSpace(string(b)))
if err == nil {
// kill the slirp process so we do not leak it
err = unix.Kill(i, unix.SIGTERM)
if err == unix.ESRCH {
err = nil
}
// kill the slirp/pasta process so we do not leak it
err = unix.Kill(pid, unix.SIGTERM)
if err == unix.ESRCH {
err = nil
}
}
return err
@ -294,6 +315,13 @@ func (n *Netns) setupMounts() error {
return wrapError("create new mount namespace", err)
}
// Ensure we mount private in our mountns to prevent accidentally
// overwriting the host mounts in case the default propagation is shared.
err = unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, "")
if err != nil {
return wrapError("make tree private in new mount namespace", err)
}
xdgRuntimeDir, err := homedir.GetRuntimeDir()
if err != nil {
return fmt.Errorf("could not get runtime directory: %w", err)
@ -301,7 +329,7 @@ func (n *Netns) setupMounts() error {
newXDGRuntimeDir := n.getPath(xdgRuntimeDir)
// 1. Mount the netns into the new run to keep them accessible.
// Otherwise cni setup will fail because it cannot access the netns files.
err = mountAndMkdirDest(xdgRuntimeDir, newXDGRuntimeDir, none, unix.MS_BIND|unix.MS_SHARED|unix.MS_REC)
err = mountAndMkdirDest(xdgRuntimeDir, newXDGRuntimeDir, none, unix.MS_BIND|unix.MS_REC)
if err != nil {
return err
}
@ -556,15 +584,12 @@ func (n *Netns) Run(lock *lockfile.LockFile, toRun func() error) error {
logrus.Errorf("Failed to decrement ref count: %v", err)
return inErr
}
if count == 0 {
// runInner() already cleans up the netns when it created a new one on errors
// so we only need to do that if there was no error.
if inErr == nil && count == 0 {
err = n.cleanup()
if err != nil {
err = wrapError("cleanup", err)
if inErr == nil {
return err
}
logrus.Errorf("Failed to cleanup rootless netns: %v", err)
return inErr
return wrapError("cleanup", err)
}
}
@ -599,3 +624,11 @@ func refCount(dir string, inc int) (int, error) {
return currentCount, nil
}
func readPidFile(path string) (int, error) {
b, err := os.ReadFile(path)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(b)))
}

View File

@ -135,7 +135,11 @@ func NewNetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) {
}
var netns *rootlessnetns.Netns
if unshare.IsRootless() {
// Do not use unshare.IsRootless() here. We only care if we are running re-exec in the userns,
// IsRootless() also returns true if we are root in a userns which is not what we care about and
// causes issues as this slower more complicated rootless-netns logic should not be used as root.
_, useRootlessNetns := os.LookupEnv(unshare.UsernsEnvName)
if useRootlessNetns {
netns, err = rootlessnetns.New(conf.NetworkRunDir, rootlessnetns.Netavark, conf.Config)
if err != nil {
return nil, err
@ -147,7 +151,7 @@ func NewNetworkInterface(conf *InitConfig) (types.ContainerNetwork, error) {
networkRunDir: conf.NetworkRunDir,
netavarkBinary: conf.NetavarkBinary,
aardvarkBinary: conf.AardvarkBinary,
networkRootless: unshare.IsRootless(),
networkRootless: useRootlessNetns,
ipamDBPath: filepath.Join(conf.NetworkRunDir, "ipam.db"),
firewallDriver: conf.Config.Network.FirewallDriver,
defaultNetwork: defaultNetworkName,

View File

@ -328,6 +328,11 @@ type EngineConfig struct {
// this slice takes precedence.
HooksDir attributedstring.Slice `toml:"hooks_dir,omitempty"`
// Location of CDI configuration files. These define mounts devices and
// other configs according to the CDI spec. In particular this is used
// for GPU passthrough.
CdiSpecDirs attributedstring.Slice `toml:"cdi_spec_dirs,omitempty"`
// ImageBuildFormat (DEPRECATED) indicates the default image format to
// building container images. Should use ImageDefaultFormat
ImageBuildFormat string `toml:"image_build_format,omitempty"`
@ -772,7 +777,7 @@ func (m *MachineConfig) URI() string {
}
func (c *EngineConfig) findRuntime() string {
// Search for crun first followed by runc, kata, runsc
// Search for crun first followed by runc, runj, kata, runsc, ocijail
for _, name := range []string{"crun", "runc", "runj", "kata", "runsc", "ocijail"} {
for _, v := range c.OCIRuntimes[name] {
if _, err := os.Stat(v); err == nil {

View File

@ -544,6 +544,12 @@ default_sysctls = [
# "/usr/share/containers/oci/hooks.d",
#]
# Directories to scan for CDI Spec files.
#
#cdi_spec_dirs = [
# "/etc/cdi",
#]
# Manifest Type (oci, v2s2, or v2s1) to use when pulling, pushing, building
# container images. By default image pulled and pushed match the format of the
# source image. Building/committing defaults to OCI.

View File

@ -414,6 +414,12 @@ default_sysctls = [
# "/usr/local/share/containers/oci/hooks.d",
#]
# Directories to scan for CDI Spec files.
#
#cdi_spec_dirs = [
# "/etc/cdi",
#]
# Manifest Type (oci, v2s2, or v2s1) to use when pulling, pushing, building
# container images. By default image pulled and pushed match the format of the
# source image. Building/committing defaults to OCI.

View File

@ -74,6 +74,8 @@ var (
ErrInvalidArg = errors.New("invalid argument")
// DefaultHooksDirs defines the default hooks directory.
DefaultHooksDirs = []string{"/usr/share/containers/oci/hooks.d"}
// DefaultCdiSpecDirs defines the default cdi spec directories.
DefaultCdiSpecDirs = []string{"/etc/cdi"}
// DefaultCapabilities is the default for the default_capabilities option in the containers.conf file.
DefaultCapabilities = []string{
"CAP_CHOWN",
@ -347,6 +349,7 @@ func defaultEngineConfig() (*EngineConfig, error) {
c.HelperBinariesDir.Set(append([]string{additionalHelperBinariesDir}, c.HelperBinariesDir.Get()...))
}
c.HooksDir.Set(DefaultHooksDirs)
c.CdiSpecDirs.Set(DefaultCdiSpecDirs)
c.ImageDefaultTransport = _defaultTransport
c.ImageVolumeMode = _defaultImageVolumeMode

View File

@ -2,6 +2,7 @@ package config
import (
"fmt"
"strings"
)
// PullPolicy determines how and which images are being pulled from a container
@ -73,14 +74,14 @@ func (p PullPolicy) Validate() error {
// * "newer" <-> PullPolicyNewer (also "ifnewer")
// * "never" <-> PullPolicyNever
func ParsePullPolicy(s string) (PullPolicy, error) {
switch s {
case "always", "Always":
switch strings.ToLower(s) {
case "always":
return PullPolicyAlways, nil
case "missing", "Missing", "ifnotpresent", "IfNotPresent", "":
case "missing", "ifmissing", "ifnotpresent", "":
return PullPolicyMissing, nil
case "newer", "Newer", "ifnewer", "IfNewer":
case "newer", "ifnewer":
return PullPolicyNewer, nil
case "never", "Never":
case "never":
return PullPolicyNever, nil
default:
return PullPolicyUnsupported, fmt.Errorf("unsupported pull policy %q", s)

View File

@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"strings"
"github.com/containers/common/internal"
"github.com/containers/image/v5/manifest"
@ -80,10 +81,18 @@ func Create() List {
}
}
func sliceToMap(s []string) map[string]string {
m := make(map[string]string, len(s))
for _, spec := range s {
key, value, _ := strings.Cut(spec, "=")
m[key] = value
}
return m
}
// AddInstance adds an entry for the specified manifest digest, with assorted
// additional information specified in parameters, to the list or index.
func (l *list) AddInstance(manifestDigest digest.Digest, manifestSize int64, manifestType, osName, architecture, osVersion string, osFeatures []string, variant string, features, annotations []string) error { // nolint:revive
// FIXME: the annotations argument is currently ignored
if err := l.Remove(manifestDigest); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
@ -116,10 +125,11 @@ func (l *list) AddInstance(manifestDigest digest.Digest, manifestSize int64, man
ociv1platform = nil
}
l.oci.Manifests = append(l.oci.Manifests, v1.Descriptor{
MediaType: manifestType,
Size: manifestSize,
Digest: manifestDigest,
Platform: ociv1platform,
MediaType: manifestType,
Size: manifestSize,
Digest: manifestDigest,
Platform: ociv1platform,
Annotations: sliceToMap(annotations),
})
return nil

View File

@ -15,21 +15,35 @@ const (
// Note: This function is copied from containers/podman libpod/util.go
// Please see https://github.com/containers/common/pull/1460
func queryPackageVersion(cmdArg ...string) string {
_, err := os.Stat(cmdArg[0])
if err != nil {
return ""
}
output := UnknownPackage
if 1 < len(cmdArg) {
cmd := exec.Command(cmdArg[0], cmdArg[1:]...)
if outp, err := cmd.Output(); err == nil {
output = string(outp)
deb := false
if cmdArg[0] == "/usr/bin/dlocate" {
// can return multiple matches
l := strings.Split(output, "\n")
output = l[0]
deb = true
r := strings.Split(output, ": ")
regexpFormat := `^..\s` + r[0] + `\s`
cmd = exec.Command(cmdArg[0], "-P", regexpFormat, "-l")
cmd.Env = []string{"COLUMNS=160"} // show entire value
// dlocate always returns exit code 1 for list command
if outp, _ = cmd.Output(); len(outp) > 0 {
lines := strings.Split(string(outp), "\n")
if len(lines) > 1 {
line := lines[len(lines)-2] // trailing newline
f := strings.Fields(line)
if len(f) >= 2 {
return f[1] + "_" + f[2]
}
}
}
} else if cmdArg[0] == "/usr/bin/dpkg" {
deb = true
}
if deb {
r := strings.Split(output, ": ")
queryFormat := `${Package}_${Version}_${Architecture}`
cmd = exec.Command("/usr/bin/dpkg-query", "-f", queryFormat, "-W", r[0])
@ -53,22 +67,36 @@ func Package(program string) string { // program is full path
if err != nil {
return UnknownPackage
}
packagers := [][]string{
{"/usr/bin/rpm", "-q", "-f"},
{"/usr/bin/dlocate", "-F"}, // Debian, Ubuntu (quick)
{"/usr/bin/dpkg", "-S"}, // Debian, Ubuntu (slow)
{"/usr/bin/pacman", "-Qo"}, // Arch
{"/usr/bin/qfile", "-qv"}, // Gentoo (quick)
{"/usr/bin/equery", "b"}, // Gentoo (slow)
{"/sbin/apk", "info", "-W"}, // Alpine
{"/usr/local/sbin/pkg", "which", "-q"}, // FreeBSD
type Packager struct {
Format string
Command []string
}
packagers := []Packager{
{"rpm", []string{"/usr/bin/rpm", "-q", "-f"}},
{"deb", []string{"/usr/bin/dlocate", "-F"}}, // Debian, Ubuntu (quick)
{"deb", []string{"/usr/bin/dpkg", "-S"}}, // Debian, Ubuntu (slow)
{"pacman", []string{"/usr/bin/pacman", "-Qo"}}, // Arch
{"gentoo", []string{"/usr/bin/qfile", "-qv"}}, // Gentoo (quick)
{"gentoo", []string{"/usr/bin/equery", "b"}}, // Gentoo (slow)
{"apk", []string{"/sbin/apk", "info", "-W"}}, // Alpine
{"pkg", []string{"/usr/local/sbin/pkg", "which", "-q"}}, // FreeBSD
}
for _, cmd := range packagers {
lastformat := ""
for _, packager := range packagers {
if packager.Format == lastformat {
continue
}
cmd := packager.Command
cmd = append(cmd, program)
if out := queryPackageVersion(cmd...); out != UnknownPackage {
if out == "" {
continue
}
return out
}
lastformat = packager.Format
}
return UnknownPackage
}

View File

@ -1,3 +1,8 @@
## 2.17.1
### Fixes
- If the user sets --seed=0, make sure all parallel nodes get the same seed [af0330d]
## 2.17.0
### Features

View File

@ -265,7 +265,7 @@ var FlagSections = GinkgoFlagSections{
// SuiteConfigFlags provides flags for the Ginkgo test process, and CLI
var SuiteConfigFlags = GinkgoFlags{
{KeyPath: "S.RandomSeed", Name: "seed", SectionKey: "order", UsageDefaultValue: "randomly generated by Ginkgo",
Usage: "The seed used to randomize the spec suite."},
Usage: "The seed used to randomize the spec suite.", AlwaysExport: true},
{KeyPath: "S.RandomizeAllSpecs", Name: "randomize-all", SectionKey: "order", DeprecatedName: "randomizeAllSpecs", DeprecatedDocLink: "changed-command-line-flags",
Usage: "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe, Context and When containers."},

View File

@ -24,7 +24,8 @@ type GinkgoFlag struct {
DeprecatedDocLink string
DeprecatedVersion string
ExportAs string
ExportAs string
AlwaysExport bool
}
type GinkgoFlags []GinkgoFlag
@ -431,7 +432,7 @@ func (ssv stringSliceVar) Set(s string) error {
return nil
}
//given a set of GinkgoFlags and bindings, generate flag arguments suitable to be passed to an application with that set of flags configured.
// given a set of GinkgoFlags and bindings, generate flag arguments suitable to be passed to an application with that set of flags configured.
func GenerateFlagArgs(flags GinkgoFlags, bindings interface{}) ([]string, error) {
result := []string{}
for _, flag := range flags {
@ -451,19 +452,19 @@ func GenerateFlagArgs(flags GinkgoFlags, bindings interface{}) ([]string, error)
iface := value.Interface()
switch value.Type() {
case reflect.TypeOf(string("")):
if iface.(string) != "" {
if iface.(string) != "" || flag.AlwaysExport {
result = append(result, fmt.Sprintf("--%s=%s", name, iface))
}
case reflect.TypeOf(int64(0)):
if iface.(int64) != 0 {
if iface.(int64) != 0 || flag.AlwaysExport {
result = append(result, fmt.Sprintf("--%s=%d", name, iface))
}
case reflect.TypeOf(float64(0)):
if iface.(float64) != 0 {
if iface.(float64) != 0 || flag.AlwaysExport {
result = append(result, fmt.Sprintf("--%s=%f", name, iface))
}
case reflect.TypeOf(int(0)):
if iface.(int) != 0 {
if iface.(int) != 0 || flag.AlwaysExport {
result = append(result, fmt.Sprintf("--%s=%d", name, iface))
}
case reflect.TypeOf(bool(true)):
@ -471,7 +472,7 @@ func GenerateFlagArgs(flags GinkgoFlags, bindings interface{}) ([]string, error)
result = append(result, fmt.Sprintf("--%s", name))
}
case reflect.TypeOf(time.Duration(0)):
if iface.(time.Duration) != time.Duration(0) {
if iface.(time.Duration) != time.Duration(0) || flag.AlwaysExport {
result = append(result, fmt.Sprintf("--%s=%s", name, iface))
}

View File

@ -1,3 +1,3 @@
package types
const VERSION = "2.17.0"
const VERSION = "2.17.1"