diff options
Diffstat (limited to 'pkg/specgen')
-rw-r--r-- | pkg/specgen/config_unsupported.go | 3 | ||||
-rw-r--r-- | pkg/specgen/container_validate.go | 35 | ||||
-rw-r--r-- | pkg/specgen/generate/config_linux.go | 9 | ||||
-rw-r--r-- | pkg/specgen/generate/config_linux_cgo.go | 11 | ||||
-rw-r--r-- | pkg/specgen/generate/container.go | 8 | ||||
-rw-r--r-- | pkg/specgen/generate/container_create.go | 13 | ||||
-rw-r--r-- | pkg/specgen/generate/kube/kube.go | 56 | ||||
-rw-r--r-- | pkg/specgen/generate/kube/seccomp.go | 6 | ||||
-rw-r--r-- | pkg/specgen/generate/kube/volume.go | 31 | ||||
-rw-r--r-- | pkg/specgen/generate/namespaces.go | 44 | ||||
-rw-r--r-- | pkg/specgen/generate/oci.go | 8 | ||||
-rw-r--r-- | pkg/specgen/generate/pod_create.go | 7 | ||||
-rw-r--r-- | pkg/specgen/generate/ports.go | 25 | ||||
-rw-r--r-- | pkg/specgen/generate/security.go | 22 | ||||
-rw-r--r-- | pkg/specgen/generate/storage.go | 38 | ||||
-rw-r--r-- | pkg/specgen/generate/validate.go | 15 | ||||
-rw-r--r-- | pkg/specgen/namespaces.go | 48 | ||||
-rw-r--r-- | pkg/specgen/pod_validate.go | 6 | ||||
-rw-r--r-- | pkg/specgen/specgen.go | 6 | ||||
-rw-r--r-- | pkg/specgen/volumes.go | 17 | ||||
-rw-r--r-- | pkg/specgen/winpath.go | 3 |
21 files changed, 208 insertions, 203 deletions
diff --git a/pkg/specgen/config_unsupported.go b/pkg/specgen/config_unsupported.go index a6bf77277..becfd2eaf 100644 --- a/pkg/specgen/config_unsupported.go +++ b/pkg/specgen/config_unsupported.go @@ -4,9 +4,10 @@ package specgen import ( + "errors" + "github.com/containers/common/libimage" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" ) func (s *SpecGenerator) getSeccompConfig(configSpec *spec.Spec, img *libimage.Image) (*spec.LinuxSeccomp, error) { diff --git a/pkg/specgen/container_validate.go b/pkg/specgen/container_validate.go index e09757d1d..63d94b6b3 100644 --- a/pkg/specgen/container_validate.go +++ b/pkg/specgen/container_validate.go @@ -1,6 +1,8 @@ package specgen import ( + "errors" + "fmt" "strconv" "strings" @@ -8,7 +10,6 @@ import ( "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/rootless" "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" ) var ( @@ -23,7 +24,7 @@ var ( ) func exclusiveOptions(opt1, opt2 string) error { - return errors.Errorf("%s and %s are mutually exclusive options", opt1, opt2) + return fmt.Errorf("%s and %s are mutually exclusive options", opt1, opt2) } // Validate verifies that the given SpecGenerator is valid and satisfies required @@ -33,18 +34,18 @@ func (s *SpecGenerator) Validate() error { // associated with them because those should be on the infra container. if len(s.Pod) > 0 && s.NetNS.NSMode == FromPod { if len(s.Networks) > 0 { - return errors.Wrap(define.ErrNetworkOnPodContainer, "networks must be defined when the pod is created") + return fmt.Errorf("networks must be defined when the pod is created: %w", define.ErrNetworkOnPodContainer) } if len(s.PortMappings) > 0 || s.PublishExposedPorts { - return errors.Wrap(define.ErrNetworkOnPodContainer, "published or exposed ports must be defined when the pod is created") + return fmt.Errorf("published or exposed ports must be defined when the pod is created: %w", define.ErrNetworkOnPodContainer) } if len(s.HostAdd) > 0 { - return errors.Wrap(define.ErrNetworkOnPodContainer, "extra host entries must be specified on the pod") + return fmt.Errorf("extra host entries must be specified on the pod: %w", define.ErrNetworkOnPodContainer) } } if s.NetNS.IsContainer() && len(s.HostAdd) > 0 { - return errors.Wrap(ErrInvalidSpecConfig, "cannot set extra host entries when the container is joined to another containers network namespace") + return fmt.Errorf("cannot set extra host entries when the container is joined to another containers network namespace: %w", ErrInvalidSpecConfig) } // @@ -52,23 +53,23 @@ func (s *SpecGenerator) Validate() error { // // Rootfs and Image cannot both populated if len(s.ContainerStorageConfig.Image) > 0 && len(s.ContainerStorageConfig.Rootfs) > 0 { - return errors.Wrap(ErrInvalidSpecConfig, "both image and rootfs cannot be simultaneously") + return fmt.Errorf("both image and rootfs cannot be simultaneously: %w", ErrInvalidSpecConfig) } // Cannot set hostname and utsns if len(s.ContainerBasicConfig.Hostname) > 0 && !s.ContainerBasicConfig.UtsNS.IsPrivate() { if s.ContainerBasicConfig.UtsNS.IsPod() { - return errors.Wrap(ErrInvalidSpecConfig, "cannot set hostname when joining the pod UTS namespace") + return fmt.Errorf("cannot set hostname when joining the pod UTS namespace: %w", ErrInvalidSpecConfig) } - return errors.Wrap(ErrInvalidSpecConfig, "cannot set hostname when running in the host UTS namespace") + return fmt.Errorf("cannot set hostname when running in the host UTS namespace: %w", ErrInvalidSpecConfig) } // systemd values must be true, false, or always if len(s.ContainerBasicConfig.Systemd) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerBasicConfig.Systemd), SystemDValues) { - return errors.Wrapf(ErrInvalidSpecConfig, "--systemd values must be one of %q", strings.Join(SystemDValues, ", ")) + return fmt.Errorf("--systemd values must be one of %q: %w", strings.Join(SystemDValues, ", "), ErrInvalidSpecConfig) } // sdnotify values must be container, conmon, or ignore if len(s.ContainerBasicConfig.SdNotifyMode) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerBasicConfig.SdNotifyMode), SdNotifyModeValues) { - return errors.Wrapf(ErrInvalidSpecConfig, "--sdnotify values must be one of %q", strings.Join(SdNotifyModeValues, ", ")) + return fmt.Errorf("--sdnotify values must be one of %q: %w", strings.Join(SdNotifyModeValues, ", "), ErrInvalidSpecConfig) } // @@ -80,12 +81,12 @@ func (s *SpecGenerator) Validate() error { } // imagevolumemode must be one of ignore, tmpfs, or anonymous if given if len(s.ContainerStorageConfig.ImageVolumeMode) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerStorageConfig.ImageVolumeMode), ImageVolumeModeValues) { - return errors.Errorf("invalid ImageVolumeMode %q, value must be one of %s", + return fmt.Errorf("invalid ImageVolumeMode %q, value must be one of %s", s.ContainerStorageConfig.ImageVolumeMode, strings.Join(ImageVolumeModeValues, ",")) } // shmsize conflicts with IPC namespace if s.ContainerStorageConfig.ShmSize != nil && (s.ContainerStorageConfig.IpcNS.IsHost() || s.ContainerStorageConfig.IpcNS.IsNone()) { - return errors.Errorf("cannot set shmsize when running in the %s IPC Namespace", s.ContainerStorageConfig.IpcNS) + return fmt.Errorf("cannot set shmsize when running in the %s IPC Namespace", s.ContainerStorageConfig.IpcNS) } // @@ -93,7 +94,7 @@ func (s *SpecGenerator) Validate() error { // // userns and idmappings conflict if s.UserNS.IsPrivate() && s.IDMappings == nil { - return errors.Wrap(ErrInvalidSpecConfig, "IDMappings are required when not creating a User namespace") + return fmt.Errorf("IDMappings are required when not creating a User namespace: %w", ErrInvalidSpecConfig) } // @@ -143,11 +144,11 @@ func (s *SpecGenerator) Validate() error { for _, limit := range tmpnproc { limitSplit := strings.SplitN(limit, "=", 2) if len(limitSplit) < 2 { - return errors.Wrapf(invalidUlimitFormatError, "missing = in %s", limit) + return fmt.Errorf("missing = in %s: %w", limit, invalidUlimitFormatError) } valueSplit := strings.SplitN(limitSplit[1], ":", 2) if len(valueSplit) < 2 { - return errors.Wrapf(invalidUlimitFormatError, "missing : in %s", limit) + return fmt.Errorf("missing : in %s: %w", limit, invalidUlimitFormatError) } hard, err := strconv.Atoi(valueSplit[0]) if err != nil { @@ -197,7 +198,7 @@ func (s *SpecGenerator) Validate() error { } if s.NetNS.NSMode != Bridge && len(s.Networks) > 0 { // Note that we also get the ip and mac in the networks map - return errors.New("Networks and static ip/mac address can only be used with Bridge mode networking") + return errors.New("networks and static ip/mac address can only be used with Bridge mode networking") } return nil diff --git a/pkg/specgen/generate/config_linux.go b/pkg/specgen/generate/config_linux.go index 60d87a8fd..a46966161 100644 --- a/pkg/specgen/generate/config_linux.go +++ b/pkg/specgen/generate/config_linux.go @@ -13,7 +13,6 @@ import ( "github.com/containers/podman/v4/pkg/util" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) @@ -46,7 +45,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error { } if len(devs) > 2 { if devmode != "" { - return errors.Wrapf(unix.EINVAL, "invalid device specification %s", devicePath) + return fmt.Errorf("invalid device specification %s: %w", devicePath, unix.EINVAL) } devmode = devs[2] } @@ -60,7 +59,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error { device = fmt.Sprintf("%s:%s", device, devmode) } if err := addDevice(g, device); err != nil { - return errors.Wrapf(err, "failed to add %s device", dpath) + return fmt.Errorf("failed to add %s device: %w", dpath, err) } } return nil @@ -68,7 +67,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error { return err } if !found { - return errors.Wrapf(unix.EINVAL, "no devices found in %s", devicePath) + return fmt.Errorf("no devices found in %s: %w", devicePath, unix.EINVAL) } return nil } @@ -131,7 +130,7 @@ func addDevice(g *generate.Generator, device string) error { } dev, err := util.DeviceFromPath(src) if err != nil { - return errors.Wrapf(err, "%s is not a valid device", src) + return fmt.Errorf("%s is not a valid device: %w", src, err) } if rootless.IsRootless() { if _, err := os.Stat(src); err != nil { diff --git a/pkg/specgen/generate/config_linux_cgo.go b/pkg/specgen/generate/config_linux_cgo.go index efab6679a..74ba4aeeb 100644 --- a/pkg/specgen/generate/config_linux_cgo.go +++ b/pkg/specgen/generate/config_linux_cgo.go @@ -5,6 +5,8 @@ package generate import ( "context" + "errors" + "fmt" "io/ioutil" "github.com/containers/common/libimage" @@ -12,7 +14,6 @@ import ( "github.com/containers/podman/v4/pkg/seccomp" "github.com/containers/podman/v4/pkg/specgen" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -39,7 +40,7 @@ func getSeccompConfig(s *specgen.SpecGenerator, configSpec *spec.Spec, img *libi logrus.Debug("Loading seccomp profile from the security config") seccompConfig, err = goSeccomp.LoadProfile(imagePolicy, configSpec) if err != nil { - return nil, errors.Wrap(err, "loading seccomp profile failed") + return nil, fmt.Errorf("loading seccomp profile failed: %w", err) } return seccompConfig, nil } @@ -48,17 +49,17 @@ func getSeccompConfig(s *specgen.SpecGenerator, configSpec *spec.Spec, img *libi logrus.Debugf("Loading seccomp profile from %q", s.SeccompProfilePath) seccompProfile, err := ioutil.ReadFile(s.SeccompProfilePath) if err != nil { - return nil, errors.Wrap(err, "opening seccomp profile failed") + return nil, fmt.Errorf("opening seccomp profile failed: %w", err) } seccompConfig, err = goSeccomp.LoadProfile(string(seccompProfile), configSpec) if err != nil { - return nil, errors.Wrapf(err, "loading seccomp profile (%s) failed", s.SeccompProfilePath) + return nil, fmt.Errorf("loading seccomp profile (%s) failed: %w", s.SeccompProfilePath, err) } } else { logrus.Debug("Loading default seccomp profile") seccompConfig, err = goSeccomp.GetDefaultProfile(configSpec) if err != nil { - return nil, errors.Wrapf(err, "loading seccomp profile (%s) failed", s.SeccompProfilePath) + return nil, fmt.Errorf("loading seccomp profile (%s) failed: %w", s.SeccompProfilePath, err) } } diff --git a/pkg/specgen/generate/container.go b/pkg/specgen/generate/container.go index 8fdd87adf..2248c9235 100644 --- a/pkg/specgen/generate/container.go +++ b/pkg/specgen/generate/container.go @@ -3,6 +3,7 @@ package generate import ( "context" "encoding/json" + "errors" "fmt" "os" "strings" @@ -17,7 +18,6 @@ import ( "github.com/containers/podman/v4/pkg/signal" "github.com/containers/podman/v4/pkg/specgen" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) @@ -115,7 +115,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat // Get Default Environment from containers.conf defaultEnvs, err := envLib.ParseSlice(rtc.GetDefaultEnvEx(s.EnvHost, s.HTTPProxy)) if err != nil { - return nil, errors.Wrap(err, "error parsing fields in containers.conf") + return nil, fmt.Errorf("error parsing fields in containers.conf: %w", err) } var envs map[string]string @@ -125,7 +125,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat // already, overriding the default environments envs, err = envLib.ParseSlice(inspectData.Config.Env) if err != nil { - return nil, errors.Wrap(err, "Env fields from image failed to parse") + return nil, fmt.Errorf("env fields from image failed to parse: %w", err) } defaultEnvs = envLib.Join(envLib.DefaultEnvVariables(), envLib.Join(defaultEnvs, envs)) } @@ -141,7 +141,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat // any case. osEnv, err := envLib.ParseSlice(os.Environ()) if err != nil { - return nil, errors.Wrap(err, "error parsing host environment variables") + return nil, fmt.Errorf("error parsing host environment variables: %w", err) } // Caller Specified defaults if s.EnvHost { diff --git a/pkg/specgen/generate/container_create.go b/pkg/specgen/generate/container_create.go index f31e46090..51d290bb4 100644 --- a/pkg/specgen/generate/container_create.go +++ b/pkg/specgen/generate/container_create.go @@ -3,6 +3,8 @@ package generate import ( "context" "encoding/json" + "errors" + "fmt" "path/filepath" "strings" @@ -15,7 +17,6 @@ import ( "github.com/containers/podman/v4/pkg/util" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/selinux/go-selinux/label" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -34,7 +35,7 @@ func MakeContainer(ctx context.Context, rt *libpod.Runtime, s *specgen.SpecGener if s.Pod != "" { pod, err = rt.LookupPod(s.Pod) if err != nil { - return nil, nil, nil, errors.Wrapf(err, "error retrieving pod %s", s.Pod) + return nil, nil, nil, fmt.Errorf("error retrieving pod %s: %w", s.Pod, err) } if pod.HasInfraContainer() { infra, err = pod.InfraContainer() @@ -140,7 +141,7 @@ func MakeContainer(ctx context.Context, rt *libpod.Runtime, s *specgen.SpecGener s.Hostname = "" } if err := s.Validate(); err != nil { - return nil, nil, nil, errors.Wrap(err, "invalid config provided") + return nil, nil, nil, fmt.Errorf("invalid config provided: %w", err) } finalMounts, finalVolumes, finalOverlays, err := finalizeMounts(ctx, s, rt, rtc, newImage) @@ -332,7 +333,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l } } default: - return nil, errors.Wrapf(err, "invalid value %q systemd option requires 'true, false, always'", s.Systemd) + return nil, fmt.Errorf("invalid value %q systemd option requires 'true, false, always': %w", s.Systemd, err) } logrus.Debugf("using systemd mode: %t", useSystemd) if useSystemd { @@ -341,7 +342,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l if s.StopSignal == nil { stopSignal, err := util.ParseSignal("RTMIN+3") if err != nil { - return nil, errors.Wrapf(err, "error parsing systemd signal") + return nil, fmt.Errorf("error parsing systemd signal: %w", err) } s.StopSignal = &stopSignal } @@ -536,7 +537,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l for _, ctr := range s.DependencyContainers { depCtr, err := rt.LookupContainer(ctr) if err != nil { - return nil, errors.Wrapf(err, "%q is not a valid container, cannot be used as a dependency", ctr) + return nil, fmt.Errorf("%q is not a valid container, cannot be used as a dependency: %w", ctr, err) } deps = append(deps, depCtr) } diff --git a/pkg/specgen/generate/kube/kube.go b/pkg/specgen/generate/kube/kube.go index c254b8192..454a1e1d0 100644 --- a/pkg/specgen/generate/kube/kube.go +++ b/pkg/specgen/generate/kube/kube.go @@ -3,6 +3,7 @@ package kube import ( "context" "encoding/json" + "errors" "fmt" "math" "net" @@ -29,7 +30,6 @@ import ( "github.com/docker/docker/pkg/system" "github.com/docker/go-units" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -146,7 +146,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener // pod name should be non-empty for Deployment objects to be able to create // multiple pods having containers with unique names if len(opts.PodName) < 1 { - return nil, errors.Errorf("got empty pod name on container creation when playing kube") + return nil, errors.New("got empty pod name on container creation when playing kube") } s.Name = fmt.Sprintf("%s-%s", opts.PodName, opts.Container.Name) @@ -163,7 +163,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener for _, o := range opts.LogOptions { split := strings.SplitN(o, "=", 2) if len(split) < 2 { - return nil, errors.Errorf("invalid log option %q", o) + return nil, fmt.Errorf("invalid log option %q", o) } switch strings.ToLower(split[0]) { case "driver": @@ -179,7 +179,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener default: switch len(split[1]) { case 0: - return nil, errors.Wrapf(define.ErrInvalidArg, "invalid log option") + return nil, fmt.Errorf("invalid log option: %w", define.ErrInvalidArg) default: // tags for journald only if s.LogConfiguration.Driver == "" || s.LogConfiguration.Driver == define.JournaldLogging { @@ -196,7 +196,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener setupSecurityContext(s, opts.Container.SecurityContext, opts.PodSecurityContext) err := setupLivenessProbe(s, opts.Container, opts.RestartPolicy) if err != nil { - return nil, errors.Wrap(err, "Failed to configure livenessProbe") + return nil, fmt.Errorf("failed to configure livenessProbe: %w", err) } // Since we prefix the container name with pod name to work-around the uniqueness requirement, @@ -207,7 +207,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener s.ResourceLimits = &spec.LinuxResources{} milliCPU, err := quantityToInt64(opts.Container.Resources.Limits.Cpu()) if err != nil { - return nil, errors.Wrap(err, "Failed to set CPU quota") + return nil, fmt.Errorf("failed to set CPU quota: %w", err) } if milliCPU > 0 { period, quota := util.CoresToPeriodAndQuota(float64(milliCPU)) @@ -219,12 +219,12 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener limit, err := quantityToInt64(opts.Container.Resources.Limits.Memory()) if err != nil { - return nil, errors.Wrap(err, "Failed to set memory limit") + return nil, fmt.Errorf("failed to set memory limit: %w", err) } memoryRes, err := quantityToInt64(opts.Container.Resources.Requests.Memory()) if err != nil { - return nil, errors.Wrap(err, "Failed to set memory reservation") + return nil, fmt.Errorf("failed to set memory reservation: %w", err) } if limit > 0 || memoryRes > 0 { @@ -337,7 +337,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener for _, volume := range opts.Container.VolumeMounts { volumeSource, exists := opts.Volumes[volume.Name] if !exists { - return nil, errors.Errorf("Volume mount %s specified for container but not configured in volumes", volume.Name) + return nil, fmt.Errorf("volume mount %s specified for container but not configured in volumes", volume.Name) } // Skip if the volume is optional. This means that a configmap for a configmap volume was not found but it was // optional so we can move on without throwing an error @@ -399,7 +399,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener } s.Devices = append(s.Devices, device) default: - return nil, errors.Errorf("Unsupported volume source type") + return nil, errors.New("unsupported volume source type") } } @@ -432,21 +432,21 @@ func parseMountPath(mountPath string, readOnly bool, propagationMode *v1.MountPr options := []string{} splitVol := strings.Split(mountPath, ":") if len(splitVol) > 2 { - return "", options, errors.Errorf("%q incorrect volume format, should be ctr-dir[:option]", mountPath) + return "", options, fmt.Errorf("%q incorrect volume format, should be ctr-dir[:option]", mountPath) } dest := splitVol[0] if len(splitVol) > 1 { options = strings.Split(splitVol[1], ",") } if err := parse.ValidateVolumeCtrDir(dest); err != nil { - return "", options, errors.Wrapf(err, "parsing MountPath") + return "", options, fmt.Errorf("parsing MountPath: %w", err) } if readOnly { options = append(options, "ro") } opts, err := parse.ValidateVolumeOpts(options) if err != nil { - return "", opts, errors.Wrapf(err, "parsing MountOptions") + return "", opts, fmt.Errorf("parsing MountOptions: %w", err) } if propagationMode != nil { switch *propagationMode { @@ -457,7 +457,7 @@ func parseMountPath(mountPath string, readOnly bool, propagationMode *v1.MountPr case v1.MountPropagationBidirectional: opts = append(opts, "rshared") default: - return "", opts, errors.Errorf("unknown propagation mode %q", *propagationMode) + return "", opts, fmt.Errorf("unknown propagation mode %q", *propagationMode) } } return dest, opts, nil @@ -504,7 +504,7 @@ func setupLivenessProbe(s *specgen.SpecGenerator, containerYAML v1.Container, re func makeHealthCheck(inCmd string, interval int32, retries int32, timeout int32, startPeriod int32) (*manifest.Schema2HealthConfig, error) { // Every healthcheck requires a command if len(inCmd) == 0 { - return nil, errors.New("Must define a healthcheck command for all healthchecks") + return nil, errors.New("must define a healthcheck command for all healthchecks") } // first try to parse option value as JSON array of strings... @@ -630,7 +630,7 @@ func quantityToInt64(quantity *resource.Quantity) (int64, error) { return i, nil } - return 0, errors.Errorf("Quantity cannot be represented as int64: %v", quantity) + return 0, fmt.Errorf("quantity cannot be represented as int64: %v", quantity) } // read a k8s secret in JSON format from the secret manager @@ -642,7 +642,7 @@ func k8sSecretFromSecretManager(name string, secretsManager *secrets.SecretsMana var secrets map[string][]byte if err := json.Unmarshal(jsonSecret, &secrets); err != nil { - return nil, errors.Errorf("Secret %v is not valid JSON: %v", name, err) + return nil, fmt.Errorf("secret %v is not valid JSON: %v", name, err) } return secrets, nil } @@ -653,7 +653,7 @@ func envVarsFrom(envFrom v1.EnvFromSource, opts *CtrSpecGenOptions) (map[string] if envFrom.ConfigMapRef != nil { cmRef := envFrom.ConfigMapRef - err := errors.Errorf("Configmap %v not found", cmRef.Name) + err := fmt.Errorf("configmap %v not found", cmRef.Name) for _, c := range opts.ConfigMaps { if cmRef.Name == c.Name { @@ -689,14 +689,14 @@ func envVarValue(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error) { if env.ValueFrom != nil { if env.ValueFrom.ConfigMapKeyRef != nil { cmKeyRef := env.ValueFrom.ConfigMapKeyRef - err := errors.Errorf("Cannot set env %v: configmap %v not found", env.Name, cmKeyRef.Name) + err := fmt.Errorf("cannot set env %v: configmap %v not found", env.Name, cmKeyRef.Name) for _, c := range opts.ConfigMaps { if cmKeyRef.Name == c.Name { if value, ok := c.Data[cmKeyRef.Key]; ok { return &value, nil } - err = errors.Errorf("Cannot set env %v: key %s not found in configmap %v", env.Name, cmKeyRef.Key, cmKeyRef.Name) + err = fmt.Errorf("cannot set env %v: key %s not found in configmap %v", env.Name, cmKeyRef.Key, cmKeyRef.Name) break } } @@ -714,10 +714,10 @@ func envVarValue(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error) { value := string(val) return &value, nil } - err = errors.Errorf("Secret %v has not %v key", secKeyRef.Name, secKeyRef.Key) + err = fmt.Errorf("secret %v has not %v key", secKeyRef.Name, secKeyRef.Key) } if secKeyRef.Optional == nil || !*secKeyRef.Optional { - return nil, errors.Errorf("Cannot set env %v: %v", env.Name, err) + return nil, fmt.Errorf("cannot set env %v: %v", env.Name, err) } return nil, nil } @@ -761,8 +761,8 @@ func envVarValueFieldRef(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error return &annotationValue, nil } - return nil, errors.Errorf( - "Can not set env %v. Reason: fieldPath %v is either not valid or not supported", + return nil, fmt.Errorf( + "can not set env %v. Reason: fieldPath %v is either not valid or not supported", env.Name, fieldPath, ) } @@ -796,15 +796,15 @@ func envVarValueResourceFieldRef(env v1.EnvVar, opts *CtrSpecGenOptions) (*strin value = resources.Requests.Cpu() isValidDivisor = isCPUDivisor(divisor) default: - return nil, errors.Errorf( - "Can not set env %v. Reason: resource %v is either not valid or not supported", + return nil, fmt.Errorf( + "can not set env %v. Reason: resource %v is either not valid or not supported", env.Name, resourceName, ) } if !isValidDivisor { - return nil, errors.Errorf( - "Can not set env %s. Reason: divisor value %s is not valid", + return nil, fmt.Errorf( + "can not set env %s. Reason: divisor value %s is not valid", env.Name, divisor.String(), ) } diff --git a/pkg/specgen/generate/kube/seccomp.go b/pkg/specgen/generate/kube/seccomp.go index 8f93b34ff..6e3accd8b 100644 --- a/pkg/specgen/generate/kube/seccomp.go +++ b/pkg/specgen/generate/kube/seccomp.go @@ -1,12 +1,12 @@ package kube import ( + "fmt" "path/filepath" "strings" "github.com/containers/podman/v4/libpod" v1 "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1" - "github.com/pkg/errors" ) // KubeSeccompPaths holds information about a pod YAML's seccomp configuration @@ -42,7 +42,7 @@ func InitializeSeccompPaths(annotations map[string]string, profileRoot string) ( // this could be caused by a user inputting either of // container.seccomp.security.alpha.kubernetes.io{,/} // both of which are invalid - return nil, errors.Errorf("Invalid seccomp path: %s", prefixAndCtr[0]) + return nil, fmt.Errorf("invalid seccomp path: %s", prefixAndCtr[0]) } path, err := verifySeccompPath(seccomp, profileRoot) @@ -80,6 +80,6 @@ func verifySeccompPath(path string, profileRoot string) (string, error) { if parts[0] == "localhost" { return filepath.Join(profileRoot, parts[1]), nil } - return "", errors.Errorf("invalid seccomp path: %s", path) + return "", fmt.Errorf("invalid seccomp path: %s", path) } } diff --git a/pkg/specgen/generate/kube/volume.go b/pkg/specgen/generate/kube/volume.go index 1d6d49b9d..f5c0c241d 100644 --- a/pkg/specgen/generate/kube/volume.go +++ b/pkg/specgen/generate/kube/volume.go @@ -1,12 +1,13 @@ package kube import ( + "errors" + "fmt" "os" "github.com/containers/common/pkg/parse" "github.com/containers/podman/v4/libpod" v1 "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -56,13 +57,13 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error) } // Label a newly created volume if err := libpod.LabelVolumePath(hostPath.Path); err != nil { - return nil, errors.Wrapf(err, "error giving %s a label", hostPath.Path) + return nil, fmt.Errorf("error giving %s a label: %w", hostPath.Path, err) } case v1.HostPathFileOrCreate: if _, err := os.Stat(hostPath.Path); os.IsNotExist(err) { f, err := os.OpenFile(hostPath.Path, os.O_RDONLY|os.O_CREATE, kubeFilePermission) if err != nil { - return nil, errors.Wrap(err, "error creating HostPath") + return nil, fmt.Errorf("error creating HostPath: %w", err) } if err := f.Close(); err != nil { logrus.Warnf("Error in closing newly created HostPath file: %v", err) @@ -70,23 +71,23 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error) } // unconditionally label a newly created volume if err := libpod.LabelVolumePath(hostPath.Path); err != nil { - return nil, errors.Wrapf(err, "error giving %s a label", hostPath.Path) + return nil, fmt.Errorf("error giving %s a label: %w", hostPath.Path, err) } case v1.HostPathSocket: st, err := os.Stat(hostPath.Path) if err != nil { - return nil, errors.Wrap(err, "error checking HostPathSocket") + return nil, fmt.Errorf("error checking HostPathSocket: %w", err) } if st.Mode()&os.ModeSocket != os.ModeSocket { - return nil, errors.Errorf("checking HostPathSocket: path %s is not a socket", hostPath.Path) + return nil, fmt.Errorf("checking HostPathSocket: path %s is not a socket", hostPath.Path) } case v1.HostPathBlockDev: dev, err := os.Stat(hostPath.Path) if err != nil { - return nil, errors.Wrap(err, "error checking HostPathBlockDevice") + return nil, fmt.Errorf("error checking HostPathBlockDevice: %w", err) } if dev.Mode()&os.ModeCharDevice == os.ModeCharDevice { - return nil, errors.Errorf("checking HostPathDevice: path %s is not a block device", hostPath.Path) + return nil, fmt.Errorf("checking HostPathDevice: path %s is not a block device", hostPath.Path) } return &KubeVolume{ Type: KubeVolumeTypeBlockDevice, @@ -95,10 +96,10 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error) case v1.HostPathCharDev: dev, err := os.Stat(hostPath.Path) if err != nil { - return nil, errors.Wrap(err, "error checking HostPathCharDevice") + return nil, fmt.Errorf("error checking HostPathCharDevice: %w", err) } if dev.Mode()&os.ModeCharDevice != os.ModeCharDevice { - return nil, errors.Errorf("checking HostPathCharDevice: path %s is not a character device", hostPath.Path) + return nil, fmt.Errorf("checking HostPathCharDevice: path %s is not a character device", hostPath.Path) } return &KubeVolume{ Type: KubeVolumeTypeCharDevice, @@ -110,12 +111,12 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error) // do nothing here because we will verify the path exists in validateVolumeHostDir break default: - return nil, errors.Errorf("Invalid HostPath type %v", hostPath.Type) + return nil, fmt.Errorf("invalid HostPath type %v", hostPath.Type) } } if err := parse.ValidateVolumeHostDir(hostPath.Path); err != nil { - return nil, errors.Wrapf(err, "error in parsing HostPath in YAML") + return nil, fmt.Errorf("error in parsing HostPath in YAML: %w", err) } return &KubeVolume{ @@ -152,7 +153,7 @@ func VolumeFromConfigMap(configMapVolumeSource *v1.ConfigMapVolumeSource, config kv.Optional = *configMapVolumeSource.Optional return kv, nil } - return nil, errors.Errorf("no such ConfigMap %q", configMapVolumeSource.Name) + return nil, fmt.Errorf("no such ConfigMap %q", configMapVolumeSource.Name) } // If there are Items specified in the volumeSource, that overwrites the Data from the configmap @@ -180,7 +181,7 @@ func VolumeFromSource(volumeSource v1.VolumeSource, configMaps []v1.ConfigMap) ( case volumeSource.ConfigMap != nil: return VolumeFromConfigMap(volumeSource.ConfigMap, configMaps) default: - return nil, errors.Errorf("HostPath, ConfigMap, and PersistentVolumeClaim are currently the only supported VolumeSource") + return nil, errors.New("HostPath, ConfigMap, and PersistentVolumeClaim are currently the only supported VolumeSource") } } @@ -191,7 +192,7 @@ func InitializeVolumes(specVolumes []v1.Volume, configMaps []v1.ConfigMap) (map[ for _, specVolume := range specVolumes { volume, err := VolumeFromSource(specVolume.VolumeSource, configMaps) if err != nil { - return nil, errors.Wrapf(err, "failed to create volume %q", specVolume.Name) + return nil, fmt.Errorf("failed to create volume %q: %w", specVolume.Name, err) } volumes[specVolume.Name] = volume diff --git a/pkg/specgen/generate/namespaces.go b/pkg/specgen/generate/namespaces.go index a3719d58e..f0d4e9153 100644 --- a/pkg/specgen/generate/namespaces.go +++ b/pkg/specgen/generate/namespaces.go @@ -1,6 +1,7 @@ package generate import ( + "errors" "fmt" "os" "strings" @@ -15,7 +16,6 @@ import ( "github.com/containers/podman/v4/pkg/util" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -94,7 +94,7 @@ func GetDefaultNamespaceMode(nsType string, cfg *config.Config, pod *libpod.Pod) return ns, err } - return toReturn, errors.Wrapf(define.ErrInvalidArg, "invalid namespace type %q passed", nsType) + return toReturn, fmt.Errorf("invalid namespace type %q passed: %w", nsType, define.ErrInvalidArg) } // namespaceOptions generates container creation options for all @@ -113,18 +113,18 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. if err != nil { // This is likely to be of the fatal kind (pod was // removed) so hard fail - return nil, errors.Wrapf(err, "error looking up pod %s infra container", pod.ID()) + return nil, fmt.Errorf("error looking up pod %s infra container: %w", pod.ID(), err) } if infraID != "" { ctr, err := rt.GetContainer(infraID) if err != nil { - return nil, errors.Wrapf(err, "error retrieving pod %s infra container %s", pod.ID(), infraID) + return nil, fmt.Errorf("error retrieving pod %s infra container %s: %w", pod.ID(), infraID, err) } infraCtr = ctr } } - errNoInfra := errors.Wrapf(define.ErrInvalidArg, "cannot use pod namespace as container is not joining a pod or pod has no infra container") + errNoInfra := fmt.Errorf("cannot use pod namespace as container is not joining a pod or pod has no infra container: %w", define.ErrInvalidArg) // PID switch s.PidNS.NSMode { @@ -136,7 +136,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: pidCtr, err := rt.LookupContainer(s.PidNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share pid namespace with") + return nil, fmt.Errorf("error looking up container to share pid namespace with: %w", err) } toReturn = append(toReturn, libpod.WithPIDNSFrom(pidCtr)) } @@ -155,10 +155,10 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: ipcCtr, err := rt.LookupContainer(s.IpcNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share ipc namespace with") + return nil, fmt.Errorf("error looking up container to share ipc namespace with: %w", err) } if ipcCtr.ConfigNoCopy().NoShmShare { - return nil, errors.Errorf("joining IPC of container %s is not allowed: non-shareable IPC (hint: use IpcMode:shareable for the donor container)", ipcCtr.ID()) + return nil, fmt.Errorf("joining IPC of container %s is not allowed: non-shareable IPC (hint: use IpcMode:shareable for the donor container)", ipcCtr.ID()) } toReturn = append(toReturn, libpod.WithIPCNSFrom(ipcCtr)) if !ipcCtr.ConfigNoCopy().NoShm { @@ -187,7 +187,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: utsCtr, err := rt.LookupContainer(s.UtsNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share uts namespace with") + return nil, fmt.Errorf("error looking up container to share uts namespace with: %w", err) } toReturn = append(toReturn, libpod.WithUTSNSFrom(utsCtr)) } @@ -222,7 +222,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: userCtr, err := rt.LookupContainer(s.UserNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share user namespace with") + return nil, fmt.Errorf("error looking up container to share user namespace with: %w", err) } toReturn = append(toReturn, libpod.WithUserNSFrom(userCtr)) } @@ -234,7 +234,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. if pod == nil { toReturn = append(toReturn, libpod.WithIDMappings(*s.IDMappings)) } else if pod.HasInfraContainer() && (len(s.IDMappings.UIDMap) > 0 || len(s.IDMappings.GIDMap) > 0) { - return nil, errors.Wrapf(define.ErrInvalidArg, "cannot specify a new uid/gid map when entering a pod with an infra container") + return nil, fmt.Errorf("cannot specify a new uid/gid map when entering a pod with an infra container: %w", define.ErrInvalidArg) } } if s.User != "" { @@ -254,7 +254,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: cgroupCtr, err := rt.LookupContainer(s.CgroupNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share cgroup namespace with") + return nil, fmt.Errorf("error looking up container to share cgroup namespace with: %w", err) } toReturn = append(toReturn, libpod.WithCgroupNSFrom(cgroupCtr)) } @@ -282,7 +282,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. case specgen.FromContainer: netCtr, err := rt.LookupContainer(s.NetNS.Value) if err != nil { - return nil, errors.Wrapf(err, "error looking up container to share net namespace with") + return nil, fmt.Errorf("error looking up container to share net namespace with: %w", err) } toReturn = append(toReturn, libpod.WithNetNSFrom(netCtr)) case specgen.Slirp: @@ -362,7 +362,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt switch s.PidNS.NSMode { case specgen.Path: if _, err := os.Stat(s.PidNS.Value); err != nil { - return errors.Wrap(err, "cannot find specified PID namespace path") + return fmt.Errorf("cannot find specified PID namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.PIDNamespace), s.PidNS.Value); err != nil { return err @@ -381,7 +381,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt switch s.IpcNS.NSMode { case specgen.Path: if _, err := os.Stat(s.IpcNS.Value); err != nil { - return errors.Wrap(err, "cannot find specified IPC namespace path") + return fmt.Errorf("cannot find specified IPC namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.IPCNamespace), s.IpcNS.Value); err != nil { return err @@ -400,7 +400,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt switch s.UtsNS.NSMode { case specgen.Path: if _, err := os.Stat(s.UtsNS.Value); err != nil { - return errors.Wrap(err, "cannot find specified UTS namespace path") + return fmt.Errorf("cannot find specified UTS namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.UTSNamespace), s.UtsNS.Value); err != nil { return err @@ -423,13 +423,13 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt case s.UtsNS.NSMode == specgen.FromContainer: utsCtr, err := rt.LookupContainer(s.UtsNS.Value) if err != nil { - return errors.Wrapf(err, "error looking up container to share uts namespace with") + return fmt.Errorf("error looking up container to share uts namespace with: %w", err) } hostname = utsCtr.Hostname() case (s.NetNS.NSMode == specgen.Host && hostname == "") || s.UtsNS.NSMode == specgen.Host: tmpHostname, err := os.Hostname() if err != nil { - return errors.Wrap(err, "unable to retrieve hostname of the host") + return fmt.Errorf("unable to retrieve hostname of the host: %w", err) } hostname = tmpHostname default: @@ -458,7 +458,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt switch s.CgroupNS.NSMode { case specgen.Path: if _, err := os.Stat(s.CgroupNS.Value); err != nil { - return errors.Wrap(err, "cannot find specified cgroup namespace path") + return fmt.Errorf("cannot find specified cgroup namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.CgroupNamespace), s.CgroupNS.Value); err != nil { return err @@ -477,7 +477,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt switch s.NetNS.NSMode { case specgen.Path: if _, err := os.Stat(s.NetNS.Value); err != nil { - return errors.Wrap(err, "cannot find specified network namespace path") + return fmt.Errorf("cannot find specified network namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), s.NetNS.Value); err != nil { return err @@ -521,7 +521,7 @@ func GetNamespaceOptions(ns []string, netnsIsHost bool) ([]libpod.PodCreateOptio case "net": options = append(options, libpod.WithPodNet()) case "mnt": - return erroredOptions, errors.Errorf("Mount sharing functionality not supported on pod level") + return erroredOptions, fmt.Errorf("mount sharing functionality not supported on pod level") case "pid": options = append(options, libpod.WithPodPID()) case "user": @@ -534,7 +534,7 @@ func GetNamespaceOptions(ns []string, netnsIsHost bool) ([]libpod.PodCreateOptio case "none": return erroredOptions, nil default: - return erroredOptions, errors.Errorf("Invalid kernel namespace to share: %s. Options are: cgroup, ipc, net, pid, uts or none", toShare) + return erroredOptions, fmt.Errorf("invalid kernel namespace to share: %s. Options are: cgroup, ipc, net, pid, uts or none", toShare) } } return options, nil diff --git a/pkg/specgen/generate/oci.go b/pkg/specgen/generate/oci.go index 1044854f4..bb5f2d0ec 100644 --- a/pkg/specgen/generate/oci.go +++ b/pkg/specgen/generate/oci.go @@ -3,6 +3,7 @@ package generate import ( "context" "encoding/json" + "fmt" "path" "strings" @@ -15,7 +16,6 @@ import ( "github.com/containers/podman/v4/pkg/specgen" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) @@ -117,7 +117,7 @@ func makeCommand(s *specgen.SpecGenerator, imageData *libimage.ImageData, rtc *c finalCommand = append(finalCommand, command...) if len(finalCommand) == 0 { - return nil, errors.Errorf("no command or entrypoint provided, and no CMD or ENTRYPOINT from image") + return nil, fmt.Errorf("no command or entrypoint provided, and no CMD or ENTRYPOINT from image") } if s.Init { @@ -126,7 +126,7 @@ func makeCommand(s *specgen.SpecGenerator, imageData *libimage.ImageData, rtc *c initPath = rtc.Engine.InitPath } if initPath == "" { - return nil, errors.Errorf("no path to init binary found but container requested an init") + return nil, fmt.Errorf("no path to init binary found but container requested an init") } finalCommand = append([]string{define.ContainerInitPath, "--"}, finalCommand...) } @@ -348,7 +348,7 @@ func SpecGenToOCI(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runt for k, v := range s.WeightDevice { statT := unix.Stat_t{} if err := unix.Stat(k, &statT); err != nil { - return nil, errors.Wrapf(err, "failed to inspect '%s' in --blkio-weight-device", k) + return nil, fmt.Errorf("failed to inspect '%s' in --blkio-weight-device: %w", k, err) } g.AddLinuxResourcesBlockIOWeightDevice((int64(unix.Major(uint64(statT.Rdev)))), (int64(unix.Minor(uint64(statT.Rdev)))), *v.Weight) //nolint: unconvert } diff --git a/pkg/specgen/generate/pod_create.go b/pkg/specgen/generate/pod_create.go index 59936c7a8..212d613fe 100644 --- a/pkg/specgen/generate/pod_create.go +++ b/pkg/specgen/generate/pod_create.go @@ -13,7 +13,6 @@ import ( "github.com/containers/podman/v4/pkg/domain/entities" "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/pkg/specgenutil" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -155,7 +154,7 @@ func MapSpec(p *specgen.PodSpecGenerator) (*specgen.SpecGenerator, error) { if len(p.InfraContainerSpec.PortMappings) > 0 || len(p.InfraContainerSpec.Networks) > 0 || p.InfraContainerSpec.NetNS.NSMode == specgen.NoNetwork { - return nil, errors.Wrapf(define.ErrInvalidArg, "cannot set host network if network-related configuration is specified") + return nil, fmt.Errorf("cannot set host network if network-related configuration is specified: %w", define.ErrInvalidArg) } p.InfraContainerSpec.NetNS.NSMode = specgen.Host case specgen.Slirp: @@ -169,11 +168,11 @@ func MapSpec(p *specgen.PodSpecGenerator) (*specgen.SpecGenerator, error) { if len(p.InfraContainerSpec.PortMappings) > 0 || len(p.InfraContainerSpec.Networks) > 0 || p.InfraContainerSpec.NetNS.NSMode == specgen.Host { - return nil, errors.Wrapf(define.ErrInvalidArg, "cannot disable pod network if network-related configuration is specified") + return nil, fmt.Errorf("cannot disable pod network if network-related configuration is specified: %w", define.ErrInvalidArg) } p.InfraContainerSpec.NetNS.NSMode = specgen.NoNetwork default: - return nil, errors.Errorf("pods presently do not support network mode %s", p.NetNS.NSMode) + return nil, fmt.Errorf("pods presently do not support network mode %s", p.NetNS.NSMode) } if len(p.InfraCommand) > 0 { diff --git a/pkg/specgen/generate/ports.go b/pkg/specgen/generate/ports.go index 4243630e2..572f256c1 100644 --- a/pkg/specgen/generate/ports.go +++ b/pkg/specgen/generate/ports.go @@ -13,7 +13,6 @@ import ( "github.com/containers/common/pkg/util" "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/pkg/specgenutil" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -46,7 +45,7 @@ func joinTwoPortsToRangePortIfPossible(ports *[]types.PortMapping, allHostPorts, // if both host port ranges overlap and the container port range did not match // we have to error because we cannot assign the same host port to more than one container port if previousPort.HostPort+previousPort.Range-1 > port.HostPort { - return nil, errors.Errorf("conflicting port mappings for host port %d (protocol %s)", port.HostPort, port.Protocol) + return nil, fmt.Errorf("conflicting port mappings for host port %d (protocol %s)", port.HostPort, port.Protocol) } } // we could not join the ports so we append the old one to the list @@ -127,7 +126,7 @@ outer: rangePort = fmt.Sprintf("with range %d ", port.Range) } - return port, errors.Errorf("failed to find an open port to expose container port %d %son the host", port.ContainerPort, rangePort) + return port, fmt.Errorf("failed to find an open port to expose container port %d %son the host", port.ContainerPort, rangePort) } // Parse port maps to port mappings. @@ -163,7 +162,7 @@ func ParsePortMapping(portMappings []types.PortMapping, exposePorts map[uint16][ } if port.HostIP != "" { if ip := net.ParseIP(port.HostIP); ip == nil { - return nil, errors.Errorf("invalid IP address %q in port mapping", port.HostIP) + return nil, fmt.Errorf("invalid IP address %q in port mapping", port.HostIP) } } @@ -174,14 +173,14 @@ func ParsePortMapping(portMappings []types.PortMapping, exposePorts map[uint16][ } containerPort := port.ContainerPort if containerPort == 0 { - return nil, errors.Errorf("container port number must be non-0") + return nil, fmt.Errorf("container port number must be non-0") } hostPort := port.HostPort if uint32(portRange-1)+uint32(containerPort) > 65535 { - return nil, errors.Errorf("container port range exceeds maximum allowable port number") + return nil, fmt.Errorf("container port range exceeds maximum allowable port number") } if uint32(portRange-1)+uint32(hostPort) > 65535 { - return nil, errors.Errorf("host port range exceeds maximum allowable port number") + return nil, fmt.Errorf("host port range exceeds maximum allowable port number") } hostProtoMap, ok := portMap[port.HostIP] @@ -351,11 +350,11 @@ func createPortMappings(s *specgen.SpecGenerator, imageData *libimage.ImageData) for _, expose := range []map[uint16]string{expose, s.Expose} { for port, proto := range expose { if port == 0 { - return nil, nil, errors.Errorf("cannot expose 0 as it is not a valid port number") + return nil, nil, fmt.Errorf("cannot expose 0 as it is not a valid port number") } protocols, err := checkProtocol(proto, false) if err != nil { - return nil, nil, errors.Wrapf(err, "error validating protocols for exposed port %d", port) + return nil, nil, fmt.Errorf("error validating protocols for exposed port %d: %w", port, err) } toExpose[port] = appendProtocolsNoDuplicates(toExpose[port], protocols) } @@ -387,11 +386,11 @@ func checkProtocol(protocol string, allowSCTP bool) ([]string, error) { protocols[protoUDP] = struct{}{} case protoSCTP: if !allowSCTP { - return nil, errors.Errorf("protocol SCTP is not allowed for exposed ports") + return nil, fmt.Errorf("protocol SCTP is not allowed for exposed ports") } protocols[protoSCTP] = struct{}{} default: - return nil, errors.Errorf("unrecognized protocol %q in port mapping", p) + return nil, fmt.Errorf("unrecognized protocol %q in port mapping", p) } } @@ -402,7 +401,7 @@ func checkProtocol(protocol string, allowSCTP bool) ([]string, error) { // This shouldn't be possible, but check anyways if len(finalProto) == 0 { - return nil, errors.Errorf("no valid protocols specified for port mapping") + return nil, fmt.Errorf("no valid protocols specified for port mapping") } return finalProto, nil @@ -415,7 +414,7 @@ func GenExposedPorts(exposedPorts map[string]struct{}) (map[uint16]string, error } toReturn, err := specgenutil.CreateExpose(expose) if err != nil { - return nil, errors.Wrapf(err, "unable to convert image EXPOSE") + return nil, fmt.Errorf("unable to convert image EXPOSE: %w", err) } return toReturn, nil } diff --git a/pkg/specgen/generate/security.go b/pkg/specgen/generate/security.go index 7268ec318..aacefcbac 100644 --- a/pkg/specgen/generate/security.go +++ b/pkg/specgen/generate/security.go @@ -1,6 +1,7 @@ package generate import ( + "fmt" "strings" "github.com/containers/common/libimage" @@ -14,7 +15,6 @@ import ( "github.com/containers/podman/v4/pkg/util" "github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/selinux/go-selinux/label" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -32,11 +32,11 @@ func setLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig s } else if pidConfig.IsContainer() { ctr, err := runtime.LookupContainer(pidConfig.Value) if err != nil { - return errors.Wrapf(err, "container %q not found", pidConfig.Value) + return fmt.Errorf("container %q not found: %w", pidConfig.Value, err) } secopts, err := label.DupSecOpt(ctr.ProcessLabel()) if err != nil { - return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) + return fmt.Errorf("failed to duplicate label %q : %w", ctr.ProcessLabel(), err) } labelOpts = append(labelOpts, secopts...) } @@ -46,11 +46,11 @@ func setLabelOpts(s *specgen.SpecGenerator, runtime *libpod.Runtime, pidConfig s } else if ipcConfig.IsContainer() { ctr, err := runtime.LookupContainer(ipcConfig.Value) if err != nil { - return errors.Wrapf(err, "container %q not found", ipcConfig.Value) + return fmt.Errorf("container %q not found: %w", ipcConfig.Value, err) } secopts, err := label.DupSecOpt(ctr.ProcessLabel()) if err != nil { - return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) + return fmt.Errorf("failed to duplicate label %q : %w", ctr.ProcessLabel(), err) } labelOpts = append(labelOpts, secopts...) } @@ -63,7 +63,7 @@ func setupApparmor(s *specgen.SpecGenerator, rtc *config.Config, g *generate.Gen hasProfile := len(s.ApparmorProfile) > 0 if !apparmor.IsEnabled() { if hasProfile && s.ApparmorProfile != "unconfined" { - return errors.Errorf("Apparmor profile %q specified, but Apparmor is not enabled on this system", s.ApparmorProfile) + return fmt.Errorf("apparmor profile %q specified, but Apparmor is not enabled on this system", s.ApparmorProfile) } return nil } @@ -129,7 +129,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, // Pass capRequiredRequested in CapAdd field to normalize capabilities names capsRequired, err := capabilities.MergeCapabilities(nil, capsRequiredRequested, nil) if err != nil { - return errors.Wrapf(err, "capabilities requested by user or image are not valid: %q", strings.Join(capsRequired, ",")) + return fmt.Errorf("capabilities requested by user or image are not valid: %q: %w", strings.Join(capsRequired, ","), err) } // Verify all capRequired are in the capList for _, cap := range capsRequired { @@ -161,7 +161,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, } else { mergedCaps, err := capabilities.MergeCapabilities(nil, s.CapAdd, nil) if err != nil { - return errors.Wrapf(err, "capabilities requested by user are not valid: %q", strings.Join(s.CapAdd, ",")) + return fmt.Errorf("capabilities requested by user are not valid: %q: %w", strings.Join(s.CapAdd, ","), err) } boundingSet, err := capabilities.BoundingSet() if err != nil { @@ -245,17 +245,17 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, for sysctlKey, sysctlVal := range s.Sysctl { if s.IpcNS.IsHost() && strings.HasPrefix(sysctlKey, "fs.mqueue.") { - return errors.Wrapf(define.ErrInvalidArg, "sysctl %s=%s can't be set since IPC Namespace set to host", sysctlKey, sysctlVal) + return fmt.Errorf("sysctl %s=%s can't be set since IPC Namespace set to host: %w", sysctlKey, sysctlVal, define.ErrInvalidArg) } // Ignore net sysctls if --net=host if s.NetNS.IsHost() && strings.HasPrefix(sysctlKey, "net.") { - return errors.Wrapf(define.ErrInvalidArg, "sysctl %s=%s can't be set since Network Namespace set to host", sysctlKey, sysctlVal) + return fmt.Errorf("sysctl %s=%s can't be set since Network Namespace set to host: %w", sysctlKey, sysctlVal, define.ErrInvalidArg) } // Ignore uts sysctls if --uts=host if s.UtsNS.IsHost() && (strings.HasPrefix(sysctlKey, "kernel.domainname") || strings.HasPrefix(sysctlKey, "kernel.hostname")) { - return errors.Wrapf(define.ErrInvalidArg, "sysctl %s=%s can't be set since UTS Namespace set to host", sysctlKey, sysctlVal) + return fmt.Errorf("sysctl %s=%s can't be set since UTS Namespace set to host: %w", sysctlKey, sysctlVal, define.ErrInvalidArg) } g.AddLinuxSysctl(sysctlKey, sysctlVal) diff --git a/pkg/specgen/generate/storage.go b/pkg/specgen/generate/storage.go index 0a4d03780..867bb4b79 100644 --- a/pkg/specgen/generate/storage.go +++ b/pkg/specgen/generate/storage.go @@ -2,6 +2,7 @@ package generate import ( "context" + "errors" "fmt" "os" "path" @@ -16,11 +17,10 @@ import ( "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/pkg/util" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) -var errDuplicateDest = errors.Errorf("duplicate mount destination") +var errDuplicateDest = errors.New("duplicate mount destination") // Produce final mounts and named volumes for a container func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runtime, rtc *config.Config, img *libimage.Image) ([]spec.Mount, []*specgen.NamedVolume, []*specgen.OverlayVolume, error) { @@ -63,7 +63,7 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru } cleanDestination := filepath.Clean(m.Destination) if _, ok := unifiedMounts[cleanDestination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict in specified mounts - multiple mounts at %q", cleanDestination) + return nil, nil, nil, fmt.Errorf("conflict in specified mounts - multiple mounts at %q: %w", cleanDestination, errDuplicateDest) } unifiedMounts[cleanDestination] = m } @@ -84,7 +84,7 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru } cleanDestination := filepath.Clean(v.Dest) if _, ok := unifiedVolumes[cleanDestination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict in specified volumes - multiple volumes at %q", cleanDestination) + return nil, nil, nil, fmt.Errorf("conflict in specified volumes - multiple volumes at %q: %w", cleanDestination, errDuplicateDest) } unifiedVolumes[cleanDestination] = v } @@ -105,7 +105,7 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru } cleanDestination := filepath.Clean(v.Destination) if _, ok := unifiedOverlays[cleanDestination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict in specified volumes - multiple volumes at %q", cleanDestination) + return nil, nil, nil, fmt.Errorf("conflict in specified volumes - multiple volumes at %q: %w", cleanDestination, errDuplicateDest) } unifiedOverlays[cleanDestination] = v } @@ -131,7 +131,7 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru return nil, nil, nil, err } if _, ok := unifiedMounts[initMount.Destination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict with mount added by --init to %q", initMount.Destination) + return nil, nil, nil, fmt.Errorf("conflict with mount added by --init to %q: %w", initMount.Destination, errDuplicateDest) } unifiedMounts[initMount.Destination] = initMount } @@ -161,12 +161,12 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru // Check for conflicts between named volumes and mounts for dest := range baseMounts { if _, ok := baseVolumes[dest]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict at mount destination %v", dest) + return nil, nil, nil, fmt.Errorf("conflict at mount destination %v: %w", dest, errDuplicateDest) } } for dest := range baseVolumes { if _, ok := baseMounts[dest]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, "conflict at mount destination %v", dest) + return nil, nil, nil, fmt.Errorf("conflict at mount destination %v: %w", dest, errDuplicateDest) } } // Final step: maps to arrays @@ -175,7 +175,7 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru if mount.Type == define.TypeBind { absSrc, err := filepath.Abs(mount.Source) if err != nil { - return nil, nil, nil, errors.Wrapf(err, "error getting absolute path of %s", mount.Source) + return nil, nil, nil, fmt.Errorf("error getting absolute path of %s: %w", mount.Source, err) } mount.Source = absSrc } @@ -208,7 +208,7 @@ func getImageVolumes(ctx context.Context, img *libimage.Image, s *specgen.SpecGe inspect, err := img.Inspect(ctx, nil) if err != nil { - return nil, nil, errors.Wrapf(err, "error inspecting image to get image volumes") + return nil, nil, fmt.Errorf("error inspecting image to get image volumes: %w", err) } for volume := range inspect.Config.Volumes { logrus.Debugf("Image has volume at %q", volume) @@ -252,16 +252,16 @@ func getVolumesFrom(volumesFrom []string, runtime *libpod.Runtime) (map[string]s switch opt { case "z": if setZ { - return nil, nil, errors.Errorf("cannot set :z more than once in mount options") + return nil, nil, errors.New("cannot set :z more than once in mount options") } setZ = true case "ro", "rw": if setRORW { - return nil, nil, errors.Errorf("cannot set ro or rw options more than once") + return nil, nil, errors.New("cannot set ro or rw options more than once") } setRORW = true default: - return nil, nil, errors.Errorf("invalid option %q specified - volumes from another container can only use z,ro,rw options", opt) + return nil, nil, fmt.Errorf("invalid option %q specified - volumes from another container can only use z,ro,rw options", opt) } } options = splitOpts @@ -269,7 +269,7 @@ func getVolumesFrom(volumesFrom []string, runtime *libpod.Runtime) (map[string]s ctr, err := runtime.LookupContainer(splitVol[0]) if err != nil { - return nil, nil, errors.Wrapf(err, "error looking up container %q for volumes-from", splitVol[0]) + return nil, nil, fmt.Errorf("error looking up container %q for volumes-from: %w", splitVol[0], err) } logrus.Debugf("Adding volumes from container %s", ctr.ID()) @@ -290,7 +290,7 @@ func getVolumesFrom(volumesFrom []string, runtime *libpod.Runtime) (map[string]s // and append them in if we can find them. spec := ctr.Spec() if spec == nil { - return nil, nil, errors.Errorf("retrieving container %s spec for volumes-from", ctr.ID()) + return nil, nil, fmt.Errorf("retrieving container %s spec for volumes-from", ctr.ID()) } for _, mnt := range spec.Mounts { if mnt.Type != define.TypeBind { @@ -364,16 +364,16 @@ func addContainerInitBinary(s *specgen.SpecGenerator, path string) (spec.Mount, } if path == "" { - return mount, fmt.Errorf("please specify a path to the container-init binary") + return mount, errors.New("please specify a path to the container-init binary") } if !s.PidNS.IsPrivate() { - return mount, fmt.Errorf("cannot add init binary as PID 1 (PID namespace isn't private)") + return mount, errors.New("cannot add init binary as PID 1 (PID namespace isn't private)") } if s.Systemd == "always" { - return mount, fmt.Errorf("cannot use container-init binary with systemd=always") + return mount, errors.New("cannot use container-init binary with systemd=always") } if _, err := os.Stat(path); os.IsNotExist(err) { - return mount, errors.Wrap(err, "container-init binary not found on the host") + return mount, fmt.Errorf("container-init binary not found on the host: %w", err) } return mount, nil } diff --git a/pkg/specgen/generate/validate.go b/pkg/specgen/generate/validate.go index a1affef31..9c933d747 100644 --- a/pkg/specgen/generate/validate.go +++ b/pkg/specgen/generate/validate.go @@ -1,6 +1,8 @@ package generate import ( + "errors" + "fmt" "io/ioutil" "os" "path/filepath" @@ -9,7 +11,6 @@ import ( "github.com/containers/common/pkg/sysinfo" "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/utils" - "github.com/pkg/errors" ) // Verify resource limits are sanely set when running on cgroup v1. @@ -23,7 +24,7 @@ func verifyContainerResourcesCgroupV1(s *specgen.SpecGenerator) ([]string, error } if s.ResourceLimits.Unified != nil { - return nil, errors.New("Cannot use --cgroup-conf without cgroup v2") + return nil, errors.New("cannot use --cgroup-conf without cgroup v2") } // Memory checks @@ -49,7 +50,7 @@ func verifyContainerResourcesCgroupV1(s *specgen.SpecGenerator) ([]string, error warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.") memory.Swappiness = nil } else if *memory.Swappiness > 100 { - return warnings, errors.Errorf("invalid value: %v, valid memory swappiness range is 0-100", *memory.Swappiness) + return warnings, fmt.Errorf("invalid value: %v, valid memory swappiness range is 0-100", *memory.Swappiness) } } if memory.Reservation != nil && !sysInfo.MemoryReservation { @@ -104,18 +105,18 @@ func verifyContainerResourcesCgroupV1(s *specgen.SpecGenerator) ([]string, error cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(cpu.Cpus) if err != nil { - return warnings, errors.Errorf("invalid value %s for cpuset cpus", cpu.Cpus) + return warnings, fmt.Errorf("invalid value %s for cpuset cpus", cpu.Cpus) } if !cpusAvailable { - return warnings, errors.Errorf("requested CPUs are not available - requested %s, available: %s", cpu.Cpus, sysInfo.Cpus) + return warnings, fmt.Errorf("requested CPUs are not available - requested %s, available: %s", cpu.Cpus, sysInfo.Cpus) } memsAvailable, err := sysInfo.IsCpusetMemsAvailable(cpu.Mems) if err != nil { - return warnings, errors.Errorf("invalid value %s for cpuset mems", cpu.Mems) + return warnings, fmt.Errorf("invalid value %s for cpuset mems", cpu.Mems) } if !memsAvailable { - return warnings, errors.Errorf("requested memory nodes are not available - requested %s, available: %s", cpu.Mems, sysInfo.Mems) + return warnings, fmt.Errorf("requested memory nodes are not available - requested %s, available: %s", cpu.Mems, sysInfo.Mems) } } diff --git a/pkg/specgen/namespaces.go b/pkg/specgen/namespaces.go index f1343f6e2..03a2049f6 100644 --- a/pkg/specgen/namespaces.go +++ b/pkg/specgen/namespaces.go @@ -1,6 +1,7 @@ package specgen import ( + "errors" "fmt" "net" "os" @@ -14,7 +15,6 @@ import ( "github.com/containers/storage" spec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate" - "github.com/pkg/errors" ) type NamespaceMode string @@ -158,18 +158,18 @@ func validateNetNS(n *Namespace) error { case "", Default, Host, Path, FromContainer, FromPod, Private, NoNetwork, Bridge: break default: - return errors.Errorf("invalid network %q", n.NSMode) + return fmt.Errorf("invalid network %q", n.NSMode) } // Path and From Container MUST have a string value set if n.NSMode == Path || n.NSMode == FromContainer { if len(n.Value) < 1 { - return errors.Errorf("namespace mode %s requires a value", n.NSMode) + return fmt.Errorf("namespace mode %s requires a value", n.NSMode) } } else if n.NSMode != Slirp { // All others except must NOT set a string value if len(n.Value) > 0 { - return errors.Errorf("namespace value %s cannot be provided with namespace mode %s", n.Value, n.NSMode) + return fmt.Errorf("namespace value %s cannot be provided with namespace mode %s", n.Value, n.NSMode) } } @@ -197,20 +197,20 @@ func (n *Namespace) validate() error { case "", Default, Host, Path, FromContainer, FromPod, Private: // Valid, do nothing case NoNetwork, Bridge, Slirp: - return errors.Errorf("cannot use network modes with non-network namespace") + return errors.New("cannot use network modes with non-network namespace") default: - return errors.Errorf("invalid namespace type %s specified", n.NSMode) + return fmt.Errorf("invalid namespace type %s specified", n.NSMode) } // Path and From Container MUST have a string value set if n.NSMode == Path || n.NSMode == FromContainer { if len(n.Value) < 1 { - return errors.Errorf("namespace mode %s requires a value", n.NSMode) + return fmt.Errorf("namespace mode %s requires a value", n.NSMode) } } else { // All others must NOT set a string value if len(n.Value) > 0 { - return errors.Errorf("namespace value %s cannot be provided with namespace mode %s", n.Value, n.NSMode) + return fmt.Errorf("namespace value %s cannot be provided with namespace mode %s", n.Value, n.NSMode) } } return nil @@ -231,19 +231,19 @@ func ParseNamespace(ns string) (Namespace, error) { case strings.HasPrefix(ns, "ns:"): split := strings.SplitN(ns, ":", 2) if len(split) != 2 { - return toReturn, errors.Errorf("must provide a path to a namespace when specifying \"ns:\"") + return toReturn, fmt.Errorf("must provide a path to a namespace when specifying \"ns:\"") } toReturn.NSMode = Path toReturn.Value = split[1] case strings.HasPrefix(ns, "container:"): split := strings.SplitN(ns, ":", 2) if len(split) != 2 { - return toReturn, errors.Errorf("must provide name or ID or a container when specifying \"container:\"") + return toReturn, fmt.Errorf("must provide name or ID or a container when specifying \"container:\"") } toReturn.NSMode = FromContainer toReturn.Value = split[1] default: - return toReturn, errors.Errorf("unrecognized namespace mode %s passed", ns) + return toReturn, fmt.Errorf("unrecognized namespace mode %s passed", ns) } return toReturn, nil @@ -266,7 +266,7 @@ func ParseCgroupNamespace(ns string) (Namespace, error) { case "private", "": toReturn.NSMode = Private default: - return toReturn, errors.Errorf("unrecognized cgroup namespace mode %s passed", ns) + return toReturn, fmt.Errorf("unrecognized cgroup namespace mode %s passed", ns) } } else { toReturn.NSMode = Host @@ -300,7 +300,7 @@ func ParseUserNamespace(ns string) (Namespace, error) { case strings.HasPrefix(ns, "auto:"): split := strings.SplitN(ns, ":", 2) if len(split) != 2 { - return toReturn, errors.Errorf("invalid setting for auto: mode") + return toReturn, errors.New("invalid setting for auto: mode") } toReturn.NSMode = Auto toReturn.Value = split[1] @@ -365,14 +365,14 @@ func ParseNetworkFlag(networks []string) (Namespace, map[string]types.PerNetwork case strings.HasPrefix(ns, "ns:"): split := strings.SplitN(ns, ":", 2) if len(split) != 2 { - return toReturn, nil, nil, errors.Errorf("must provide a path to a namespace when specifying \"ns:\"") + return toReturn, nil, nil, errors.New("must provide a path to a namespace when specifying \"ns:\"") } toReturn.NSMode = Path toReturn.Value = split[1] case strings.HasPrefix(ns, string(FromContainer)+":"): split := strings.SplitN(ns, ":", 2) if len(split) != 2 { - return toReturn, nil, nil, errors.Errorf("must provide name or ID or a container when specifying \"container:\"") + return toReturn, nil, nil, errors.New("must provide name or ID or a container when specifying \"container:\"") } toReturn.NSMode = FromContainer toReturn.Value = split[1] @@ -391,7 +391,7 @@ func ParseNetworkFlag(networks []string) (Namespace, map[string]types.PerNetwork } netOpts, err := parseBridgeNetworkOptions(parts[1]) if err != nil { - return toReturn, nil, nil, errors.Wrapf(err, "invalid option for network %s", parts[0]) + return toReturn, nil, nil, fmt.Errorf("invalid option for network %s: %w", parts[0], err) } podmanNetworks[parts[0]] = netOpts } @@ -402,24 +402,24 @@ func ParseNetworkFlag(networks []string) (Namespace, map[string]types.PerNetwork if len(networks) > 1 { if !toReturn.IsBridge() { - return toReturn, nil, nil, errors.Wrapf(define.ErrInvalidArg, "cannot set multiple networks without bridge network mode, selected mode %s", toReturn.NSMode) + return toReturn, nil, nil, fmt.Errorf("cannot set multiple networks without bridge network mode, selected mode %s: %w", toReturn.NSMode, define.ErrInvalidArg) } for _, network := range networks[1:] { parts := strings.SplitN(network, ":", 2) if parts[0] == "" { - return toReturn, nil, nil, errors.Wrapf(define.ErrInvalidArg, "network name cannot be empty") + return toReturn, nil, nil, fmt.Errorf("network name cannot be empty: %w", define.ErrInvalidArg) } if cutil.StringInSlice(parts[0], []string{string(Bridge), string(Slirp), string(FromPod), string(NoNetwork), string(Default), string(Private), string(Path), string(FromContainer), string(Host)}) { - return toReturn, nil, nil, errors.Wrapf(define.ErrInvalidArg, "can only set extra network names, selected mode %s conflicts with bridge", parts[0]) + return toReturn, nil, nil, fmt.Errorf("can only set extra network names, selected mode %s conflicts with bridge: %w", parts[0], define.ErrInvalidArg) } netOpts := types.PerNetworkOptions{} if len(parts) > 1 { var err error netOpts, err = parseBridgeNetworkOptions(parts[1]) if err != nil { - return toReturn, nil, nil, errors.Wrapf(err, "invalid option for network %s", parts[0]) + return toReturn, nil, nil, fmt.Errorf("invalid option for network %s: %w", parts[0], err) } } podmanNetworks[parts[0]] = netOpts @@ -441,7 +441,7 @@ func parseBridgeNetworkOptions(opts string) (types.PerNetworkOptions, error) { case "ip", "ip6": ip := net.ParseIP(split[1]) if ip == nil { - return netOpts, errors.Errorf("invalid ip address %q", split[1]) + return netOpts, fmt.Errorf("invalid ip address %q", split[1]) } netOpts.StaticIPs = append(netOpts.StaticIPs, ip) @@ -465,7 +465,7 @@ func parseBridgeNetworkOptions(opts string) (types.PerNetworkOptions, error) { netOpts.InterfaceName = split[1] default: - return netOpts, errors.Errorf("unknown bridge network option: %s", split[0]) + return netOpts, fmt.Errorf("unknown bridge network option: %s", split[0]) } } return netOpts, nil @@ -477,7 +477,7 @@ func SetupUserNS(idmappings *storage.IDMappingOptions, userns Namespace, g *gene switch userns.NSMode { case Path: if _, err := os.Stat(userns.Value); err != nil { - return user, errors.Wrap(err, "cannot find specified user namespace path") + return user, fmt.Errorf("cannot find specified user namespace path: %w", err) } if err := g.AddOrReplaceLinuxNamespace(string(spec.UserNamespace), userns.Value); err != nil { return user, err @@ -526,7 +526,7 @@ func privateUserNamespace(idmappings *storage.IDMappingOptions, g *generate.Gene return err } if idmappings == nil || (len(idmappings.UIDMap) == 0 && len(idmappings.GIDMap) == 0) { - return errors.Errorf("must provide at least one UID or GID mapping to configure a user namespace") + return errors.New("must provide at least one UID or GID mapping to configure a user namespace") } for _, uidmap := range idmappings.UIDMap { g.AddLinuxUIDMapping(uint32(uidmap.HostID), uint32(uidmap.ContainerID), uint32(uidmap.Size)) diff --git a/pkg/specgen/pod_validate.go b/pkg/specgen/pod_validate.go index 8d971a25e..724be213f 100644 --- a/pkg/specgen/pod_validate.go +++ b/pkg/specgen/pod_validate.go @@ -1,8 +1,10 @@ package specgen import ( + "errors" + "fmt" + "github.com/containers/podman/v4/pkg/util" - "github.com/pkg/errors" ) var ( @@ -13,7 +15,7 @@ var ( ) func exclusivePodOptions(opt1, opt2 string) error { - return errors.Wrapf(ErrInvalidPodSpecConfig, "%s and %s are mutually exclusive pod options", opt1, opt2) + return fmt.Errorf("%s and %s are mutually exclusive pod options: %w", opt1, opt2, ErrInvalidPodSpecConfig) } // Validate verifies the input is valid diff --git a/pkg/specgen/specgen.go b/pkg/specgen/specgen.go index 42b89ece1..c31c3f035 100644 --- a/pkg/specgen/specgen.go +++ b/pkg/specgen/specgen.go @@ -1,6 +1,7 @@ package specgen import ( + "errors" "net" "strings" "syscall" @@ -10,7 +11,6 @@ import ( "github.com/containers/image/v5/manifest" "github.com/containers/storage/types" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" ) // LogConfig describes the logging characteristics for a container @@ -571,10 +571,10 @@ type Secret struct { var ( // ErrNoStaticIPRootless is used when a rootless user requests to assign a static IP address // to a pod or container - ErrNoStaticIPRootless error = errors.New("rootless containers and pods cannot be assigned static IP addresses") + ErrNoStaticIPRootless = errors.New("rootless containers and pods cannot be assigned static IP addresses") // ErrNoStaticMACRootless is used when a rootless user requests to assign a static MAC address // to a pod or container - ErrNoStaticMACRootless error = errors.New("rootless containers and pods cannot be assigned static MAC addresses") + ErrNoStaticMACRootless = errors.New("rootless containers and pods cannot be assigned static MAC addresses") ) // NewSpecGenerator returns a SpecGenerator struct given one of two mandatory inputs diff --git a/pkg/specgen/volumes.go b/pkg/specgen/volumes.go index c9f944abf..84de4fdd1 100644 --- a/pkg/specgen/volumes.go +++ b/pkg/specgen/volumes.go @@ -1,12 +1,13 @@ package specgen import ( + "errors" + "fmt" "path/filepath" "strings" "github.com/containers/common/pkg/parse" spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -50,13 +51,13 @@ type ImageVolume struct { // GenVolumeMounts parses user input into mounts, volumes and overlay volumes func GenVolumeMounts(volumeFlag []string) (map[string]spec.Mount, map[string]*NamedVolume, map[string]*OverlayVolume, error) { - errDuplicateDest := errors.Errorf("duplicate mount destination") + errDuplicateDest := errors.New("duplicate mount destination") mounts := make(map[string]spec.Mount) volumes := make(map[string]*NamedVolume) overlayVolumes := make(map[string]*OverlayVolume) - volumeFormatErr := errors.Errorf("incorrect volume format, should be [host-dir:]ctr-dir[:option]") + volumeFormatErr := errors.New("incorrect volume format, should be [host-dir:]ctr-dir[:option]") for _, vol := range volumeFlag { var ( options []string @@ -67,7 +68,7 @@ func GenVolumeMounts(volumeFlag []string) (map[string]spec.Mount, map[string]*Na splitVol := SplitVolumeString(vol) if len(splitVol) > 3 { - return nil, nil, nil, errors.Wrapf(volumeFormatErr, vol) + return nil, nil, nil, fmt.Errorf("%v: %w", vol, volumeFormatErr) } src = splitVol[0] @@ -143,13 +144,13 @@ func GenVolumeMounts(volumeFlag []string) (map[string]spec.Mount, map[string]*Na // relative values as lowerdir for overlay mounts source, err := filepath.Abs(src) if err != nil { - return nil, nil, nil, errors.Wrapf(err, "failed while resolving absolute path for source %v for overlay mount", src) + return nil, nil, nil, fmt.Errorf("failed while resolving absolute path for source %v for overlay mount: %w", src, err) } newOverlayVol.Source = source newOverlayVol.Options = options if _, ok := overlayVolumes[newOverlayVol.Destination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, newOverlayVol.Destination) + return nil, nil, nil, fmt.Errorf("%v: %w", newOverlayVol.Destination, errDuplicateDest) } overlayVolumes[newOverlayVol.Destination] = newOverlayVol } else { @@ -160,7 +161,7 @@ func GenVolumeMounts(volumeFlag []string) (map[string]spec.Mount, map[string]*Na Options: options, } if _, ok := mounts[newMount.Destination]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, newMount.Destination) + return nil, nil, nil, fmt.Errorf("%v: %w", newMount.Destination, errDuplicateDest) } mounts[newMount.Destination] = newMount } @@ -172,7 +173,7 @@ func GenVolumeMounts(volumeFlag []string) (map[string]spec.Mount, map[string]*Na newNamedVol.Options = options if _, ok := volumes[newNamedVol.Dest]; ok { - return nil, nil, nil, errors.Wrapf(errDuplicateDest, newNamedVol.Dest) + return nil, nil, nil, fmt.Errorf("%v: %w", newNamedVol.Dest, errDuplicateDest) } volumes[newNamedVol.Dest] = newNamedVol } diff --git a/pkg/specgen/winpath.go b/pkg/specgen/winpath.go index 0df4ebdd7..5c19aeb4b 100644 --- a/pkg/specgen/winpath.go +++ b/pkg/specgen/winpath.go @@ -1,11 +1,10 @@ package specgen import ( + "errors" "fmt" "strings" "unicode" - - "github.com/pkg/errors" ) func isHostWinPath(path string) bool { |