diff --git a/.golangci.yml b/.golangci.yml index c8a7656290..592c3f3b02 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,6 +20,7 @@ linters: - dogsled - durationcheck - errchkjson + - errorlint - exptostd - fatcontext - forbidigo diff --git a/cmd/podman-mac-helper/uninstall.go b/cmd/podman-mac-helper/uninstall.go index 012b15729a..2fb050499e 100644 --- a/cmd/podman-mac-helper/uninstall.go +++ b/cmd/podman-mac-helper/uninstall.go @@ -40,7 +40,8 @@ func uninstall(_ *cobra.Command, _ []string) error { // Try removing the service by label in case the service is half uninstalled if rerr := runDetectErr("launchctl", "remove", labelName); rerr != nil { // Exit code 3 = no service to remove - if exitErr, ok := rerr.(*exec.ExitError); !ok || exitErr.ExitCode() != 3 { + var exitErr *exec.ExitError + if !errors.As(rerr, &exitErr) || exitErr.ExitCode() != 3 { fmt.Fprintf(os.Stderr, "Warning: service unloading failed: %s\n", err.Error()) fmt.Fprintf(os.Stderr, "Warning: remove also failed: %s\n", rerr.Error()) } @@ -65,11 +66,11 @@ func uninstall(_ *cobra.Command, _ []string) error { return nil } // Return an error if unable to get the file information - return fmt.Errorf("could not stat dockerSock: %v", err) + return fmt.Errorf("could not stat dockerSock: %w", err) } if target, err := os.Readlink(dockerSock); err != nil { // Return an error if unable to read the symlink - return fmt.Errorf("could not read dockerSock symlink: %v", err) + return fmt.Errorf("could not read dockerSock symlink: %w", err) } else { // Check if the target of the symlink matches the expected target expectedTarget := filepath.Join(homeDir, ".local", "share", "containers", "podman", "machine", "podman.sock") @@ -82,7 +83,7 @@ func uninstall(_ *cobra.Command, _ []string) error { // Attempt to remove dockerSock if err := os.Remove(dockerSock); err != nil { if !errors.Is(err, fs.ErrNotExist) { - return fmt.Errorf("could not remove dockerSock file: %s", err) + return fmt.Errorf("could not remove dockerSock file: %w", err) } } } diff --git a/cmd/podman/compose.go b/cmd/podman/compose.go index 9333c73cb4..c3e709263d 100644 --- a/cmd/podman/compose.go +++ b/cmd/podman/compose.go @@ -92,7 +92,7 @@ func composeProvider() (string, error) { lookupErrors = append(lookupErrors, err) } - return "", fmt.Errorf("looking up compose provider failed\n%v", errorhandling.JoinErrors(lookupErrors)) + return "", fmt.Errorf("looking up compose provider failed\n%w", errorhandling.JoinErrors(lookupErrors)) } // composeDockerHost returns the value to be set in the DOCKER_HOST environment @@ -219,7 +219,8 @@ func composeProviderExec(args []string, stdout io.Writer, stderr io.Writer, warn if err := cmd.Run(); err != nil { // Make sure podman returns with the same exit code as the compose provider. - if exitErr, isExit := err.(*exec.ExitError); isExit { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { registry.SetExitCode(exitErr.ExitCode()) } // Format the error to make it explicit that error did not come diff --git a/cmd/podman/images/import.go b/cmd/podman/images/import.go index 7e585e14b0..27010ea24c 100644 --- a/cmd/podman/images/import.go +++ b/cmd/podman/images/import.go @@ -115,14 +115,14 @@ func importCon(_ *cobra.Command, args []string) error { if source == "-" { outFile, err := os.CreateTemp("", "podman") if err != nil { - return fmt.Errorf("creating file %v", err) + return fmt.Errorf("creating file %w", err) } defer os.Remove(outFile.Name()) defer outFile.Close() _, err = io.Copy(outFile, os.Stdin) if err != nil { - return fmt.Errorf("copying file %v", err) + return fmt.Errorf("copying file %w", err) } source = outFile.Name() } diff --git a/cmd/podman/images/load.go b/cmd/podman/images/load.go index daf7bacf67..9c848e1c33 100644 --- a/cmd/podman/images/load.go +++ b/cmd/podman/images/load.go @@ -93,14 +93,14 @@ func load(_ *cobra.Command, _ []string) error { } outFile, err := os.CreateTemp(util.Tmpdir(), "podman") if err != nil { - return fmt.Errorf("creating file %v", err) + return fmt.Errorf("creating file %w", err) } defer os.Remove(outFile.Name()) defer outFile.Close() _, err = io.Copy(outFile, os.Stdin) if err != nil { - return fmt.Errorf("copying file %v", err) + return fmt.Errorf("copying file %w", err) } loadOpts.Input = outFile.Name() } diff --git a/cmd/podman/kube/play.go b/cmd/podman/kube/play.go index 22c515146c..a740f28f7a 100644 --- a/cmd/podman/kube/play.go +++ b/cmd/podman/kube/play.go @@ -316,7 +316,7 @@ func play(cmd *cobra.Command, args []string) error { var teardownErr error if playOptions.Wait { // Stop the shutdown signal handler so we can actually clean up after a SIGTERM or interrupt - if err := shutdown.Stop(); err != nil && err != shutdown.ErrNotStarted { + if err := shutdown.Stop(); err != nil && !errors.Is(err, shutdown.ErrNotStarted) { return err } // Create a channel to catch an interrupt or SIGTERM signal @@ -337,7 +337,7 @@ func play(cmd *cobra.Command, args []string) error { // clean up any volumes that were created as well fmt.Println("\nCleaning up containers, pods, and volumes...") if err := teardown(teardownReader, entities.PlayKubeDownOptions{Force: true}); err != nil && !errorhandling.Contains(err, define.ErrNoSuchPod) { - teardownErr = fmt.Errorf("error during cleanup: %v", err) + teardownErr = fmt.Errorf("error during cleanup: %w", err) } }) } diff --git a/cmd/podman/manifest/add.go b/cmd/podman/manifest/add.go index 17281b827e..ebed5a7154 100644 --- a/cmd/podman/manifest/add.go +++ b/cmd/podman/manifest/add.go @@ -179,7 +179,7 @@ func add(cmd *cobra.Command, args []string) error { if manifestAddOpts.artifactConfigFile != "" { configBytes, err := os.ReadFile(manifestAddOpts.artifactConfigFile) if err != nil { - return fmt.Errorf("%v", err) + return err } manifestAddOpts.artifactOptions.Config = string(configBytes) } diff --git a/cmd/podman/quadlet/install.go b/cmd/podman/quadlet/install.go index c4ec2b7e1d..c2c6a21101 100644 --- a/cmd/podman/quadlet/install.go +++ b/cmd/podman/quadlet/install.go @@ -56,7 +56,7 @@ func install(_ *cobra.Command, args []string) error { return err } for pathOrURL, err := range installReport.QuadletErrors { - errs = append(errs, fmt.Errorf("quadlet %q failed to install: %v", pathOrURL, err)) + errs = append(errs, fmt.Errorf("quadlet %q failed to install: %w", pathOrURL, err)) } for _, s := range installReport.InstalledQuadlets { fmt.Println(s) diff --git a/cmd/podman/quadlet/remove.go b/cmd/podman/quadlet/remove.go index 9aacdb5829..5e1e9ed7c5 100644 --- a/cmd/podman/quadlet/remove.go +++ b/cmd/podman/quadlet/remove.go @@ -54,7 +54,7 @@ func rm(_ *cobra.Command, args []string) error { var errs utils.OutputErrors removeReport, err := registry.ContainerEngine().QuadletRemove(registry.Context(), args, removeOptions) if err != nil { - errs = append(errs, fmt.Errorf("unable to remove Quadlet: %v", err)) + errs = append(errs, fmt.Errorf("unable to remove Quadlet: %w", err)) } // We can get a report back even if err != nil if systemd reload failed if removeReport != nil { @@ -62,7 +62,7 @@ func rm(_ *cobra.Command, args []string) error { fmt.Println(rq) } for quadlet, quadletErr := range removeReport.Errors { - errs = append(errs, fmt.Errorf("unable to remove Quadlet %s: %v", quadlet, quadletErr)) + errs = append(errs, fmt.Errorf("unable to remove Quadlet %s: %w", quadlet, quadletErr)) } if err == nil && len(removeReport.Errors) > 0 { errs = append(errs, errors.New("some quadlets could not be removed")) diff --git a/cmd/podman/system/service_abi.go b/cmd/podman/system/service_abi.go index 7ad4096294..261a4c2000 100644 --- a/cmd/podman/system/service_abi.go +++ b/cmd/podman/system/service_abi.go @@ -107,7 +107,7 @@ func restService(flags *pflag.FlagSet, cfg *entities.PodmanConfig, opts entities // https://access.redhat.com/solutions/6512011. for _, val := range []string{"LISTEN_FDS", "LISTEN_PID", "LISTEN_FDNAMES"} { if err := os.Unsetenv(val); err != nil { - return fmt.Errorf("unsetting %s: %v", val, err) + return fmt.Errorf("unsetting %s: %w", val, err) } } diff --git a/cmd/quadlet/main.go b/cmd/quadlet/main.go index 74d61f715a..cbf34b016c 100644 --- a/cmd/quadlet/main.go +++ b/cmd/quadlet/main.go @@ -114,7 +114,7 @@ func loadUnitsFromDir(sourcePath string) ([]*parser.UnitFile, error) { if prevError == nil { prevError = err } else { - prevError = fmt.Errorf("%s\n%s", prevError, err) + prevError = fmt.Errorf("%w\n%w", prevError, err) } } else { seen[name] = void @@ -130,7 +130,7 @@ func loadUnitDropins(unit *parser.UnitFile, sourcePaths []string) error { var prevError error reportError := func(err error) { if prevError != nil { - err = fmt.Errorf("%s\n%s", prevError, err) + err = fmt.Errorf("%w\n%w", prevError, err) } prevError = err } diff --git a/libpod/container_exec.go b/libpod/container_exec.go index a82b6cbff8..11026b5f96 100644 --- a/libpod/container_exec.go +++ b/libpod/container_exec.go @@ -1211,13 +1211,13 @@ func (c *Container) execLightweight(config *ExecConfig, streams *define.AttachSt select { case err = <-attachErrChan: if err != nil { - return -1, fmt.Errorf("container %s light exec session with pid: %d error: %v", c.ID(), pid, err) + return -1, fmt.Errorf("container %s light exec session with pid: %d error: %w", c.ID(), pid, err) } case <-time.After(timeout): if err := c.ociRuntime.ExecStopContainer(c, session.ID(), 0); err != nil { return -1, err } - return -1, fmt.Errorf("%v of %s", define.ErrHealthCheckTimeout, timeout.String()) + return -1, fmt.Errorf("%w of %s", define.ErrHealthCheckTimeout, timeout.String()) } } else { // For no-session exec, wait for completion without timeout diff --git a/libpod/container_internal.go b/libpod/container_internal.go index e42840b6e3..6c69ba448d 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -1564,7 +1564,7 @@ func (c *Container) pause() error { if err := c.removeTransientFiles(context.Background(), c.config.StartupHealthCheckConfig != nil && !c.state.StartupHCPassed, c.state.HCUnitName); err != nil { - return fmt.Errorf("failed to remove HealthCheck timer: %v", err) + return fmt.Errorf("failed to remove HealthCheck timer: %w", err) } } @@ -2359,7 +2359,7 @@ func (c *Container) postDeleteHooks(ctx context.Context) error { ) if err != nil { logrus.Warnf("Container %s: poststop hook %d: %v", c.ID(), i, err) - if hookErr != err { + if !errors.Is(hookErr, err) { logrus.Debugf("container %s: poststop hook %d (hook error): %v", c.ID(), i, hookErr) } stdoutString := stdout.String() @@ -2494,7 +2494,7 @@ func (c *Container) setupOCIHooks(ctx context.Context, config *spec.Spec) (map[s ) if err != nil { logrus.Warnf("Container %s: precreate hook: %v", c.ID(), err) - if hookErr != nil && hookErr != err { + if hookErr != nil && !errors.Is(hookErr, err) { logrus.Debugf("container %s: precreate hook (hook error): %v", c.ID(), hookErr) } return nil, err diff --git a/libpod/container_internal_common.go b/libpod/container_internal_common.go index f3ec0c98b6..4ea77ace2e 100644 --- a/libpod/container_internal_common.go +++ b/libpod/container_internal_common.go @@ -1001,12 +1001,12 @@ func (c *Container) addCheckpointImageMetadata(importBuilder *buildah.Builder) e // Get information about host environment hostInfo, err := c.Runtime().hostInfo() if err != nil { - return fmt.Errorf("getting host info: %v", err) + return fmt.Errorf("getting host info: %w", err) } criuVersion, err := criu.GetCriuVersion() if err != nil { - return fmt.Errorf("getting criu version: %v", err) + return fmt.Errorf("getting criu version: %w", err) } rootfsImageID, rootfsImageName := c.Image() @@ -2548,13 +2548,13 @@ func (c *Container) generateCurrentUserGroupEntry() (string, int, error) { // Look up group name to see if it exists in the image. _, err = lookup.GetGroup(c.state.Mountpoint, g.Name) - if err != runcuser.ErrNoGroupEntries { + if !errors.Is(err, runcuser.ErrNoGroupEntries) { return "", 0, err } // Look up GID to see if it exists in the image. _, err = lookup.GetGroup(c.state.Mountpoint, g.Gid) - if err != runcuser.ErrNoGroupEntries { + if !errors.Is(err, runcuser.ErrNoGroupEntries) { return "", 0, err } @@ -2598,7 +2598,7 @@ func (c *Container) generateUserGroupEntry(addedGID int) (string, error) { // Check if the group already exists g, err := lookup.GetGroup(c.state.Mountpoint, group) - if err != runcuser.ErrNoGroupEntries { + if !errors.Is(err, runcuser.ErrNoGroupEntries) { return "", err } @@ -2723,13 +2723,13 @@ func (c *Container) setHomeEnvIfNeeded() error { func (c *Container) userPasswdEntry(u *user.User) (string, error) { // Look up the user to see if it exists in the container image. _, err := lookup.GetUser(c.state.Mountpoint, u.Username) - if err != runcuser.ErrNoPasswdEntries { + if !errors.Is(err, runcuser.ErrNoPasswdEntries) { return "", err } // Look up the UID to see if it exists in the container image. _, err = lookup.GetUser(c.state.Mountpoint, u.Uid) - if err != runcuser.ErrNoPasswdEntries { + if !errors.Is(err, runcuser.ErrNoPasswdEntries) { return "", err } @@ -2788,7 +2788,7 @@ func (c *Container) generateUserPasswdEntry(addedUID int) (string, error) { // Look up the user to see if it exists in the container image _, err = lookup.GetUser(c.state.Mountpoint, userspec) - if err != runcuser.ErrNoPasswdEntries { + if !errors.Is(err, runcuser.ErrNoPasswdEntries) { return "", err } diff --git a/libpod/container_internal_linux.go b/libpod/container_internal_linux.go index b9a575beac..a154c48598 100644 --- a/libpod/container_internal_linux.go +++ b/libpod/container_internal_linux.go @@ -46,7 +46,7 @@ func (c *Container) mountSHM(shmOptions string) error { func (c *Container) unmountSHM(mount string) error { if err := unix.Unmount(mount, unix.MNT_DETACH); err != nil { - if err == syscall.EINVAL || err == syscall.ENOENT { + if errors.Is(err, syscall.EINVAL) || errors.Is(err, syscall.ENOENT) { logrus.Debugf("Container %s failed to unmount %s : %v", c.ID(), mount, err) return nil } diff --git a/libpod/container_top_linux.go b/libpod/container_top_linux.go index 3b498b855a..9aa10ed619 100644 --- a/libpod/container_top_linux.go +++ b/libpod/container_top_linux.go @@ -91,7 +91,7 @@ func podmanTopInner() error { if err := unix.MountSetattr(0, "/", unix.AT_RECURSIVE, &unix.MountAttr{ Attr_set: unix.MOUNT_ATTR_RDONLY, }); err != nil { - if err != unix.ENOSYS { + if !errors.Is(err, unix.ENOSYS) { return fmt.Errorf("mount_setattr / readonly: %w", err) } // old kernel without mount_setattr, i.e. on RHEL 8.8 diff --git a/libpod/events/journal_linux.go b/libpod/events/journal_linux.go index fa3936c9da..5add0d9e39 100644 --- a/libpod/events/journal_linux.go +++ b/libpod/events/journal_linux.go @@ -153,7 +153,7 @@ func (e EventJournalD) Read(ctx context.Context, options ReadOptions) (retErr er }() err = j.SetDataThreshold(0) if err != nil { - return fmt.Errorf("cannot set data threshold for journal: %v", err) + return fmt.Errorf("cannot set data threshold for journal: %w", err) } // match only podman journal entries podmanJournal := sdjournal.Match{Field: "SYSLOG_IDENTIFIER", Value: "podman"} @@ -212,7 +212,7 @@ func (e EventJournalD) Read(ctx context.Context, options ReadOptions) (retErr er // Don't fail hard - that would make events unusable. // Instead, log and continue. if !errors.Is(err, ErrEventTypeBlank) { - options.EventChannel <- ReadResult{Error: fmt.Errorf("unable to decode event: %v", err)} + options.EventChannel <- ReadResult{Error: fmt.Errorf("unable to decode event: %w", err)} } continue } diff --git a/libpod/networking_freebsd.go b/libpod/networking_freebsd.go index 69abc5207d..597a8ff124 100644 --- a/libpod/networking_freebsd.go +++ b/libpod/networking_freebsd.go @@ -90,7 +90,7 @@ func (r *Runtime) createNetNS(ctr *Container) (n string, q map[string]types.Stat b := make([]byte, 16) _, err := rand.Reader.Read(b) if err != nil { - return "", nil, fmt.Errorf("failed to generate random vnet name: %v", err) + return "", nil, fmt.Errorf("failed to generate random vnet name: %w", err) } netns := fmt.Sprintf("vnet-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) @@ -177,7 +177,7 @@ func getContainerNetIO(ctr *Container) (map[string]define.ContainerNetworkStats, out, err = cmd.Output() } if err != nil { - return nil, fmt.Errorf("failed to read network stats: %v", err) + return nil, fmt.Errorf("failed to read network stats: %w", err) } stats := Netstat{} if err := jdec.Unmarshal(out, &stats); err != nil { diff --git a/libpod/oci_conmon_attach_common.go b/libpod/oci_conmon_attach_common.go index 0a92c92564..68ce358166 100644 --- a/libpod/oci_conmon_attach_common.go +++ b/libpod/oci_conmon_attach_common.go @@ -297,7 +297,7 @@ func readStdio(conn *net.UnixConn, streams *define.AttachStreams, receiveStdoutE } return err case err = <-stdinDone: - if err == define.ErrDetach { + if errors.Is(err, define.ErrDetach) { if err := socketCloseWrite(conn); err != nil { logrus.Errorf("Failed to close stdin: %v", err) } diff --git a/libpod/oci_conmon_common.go b/libpod/oci_conmon_common.go index b01291b325..d8882ec6ff 100644 --- a/libpod/oci_conmon_common.go +++ b/libpod/oci_conmon_common.go @@ -321,7 +321,7 @@ func (r *ConmonOCIRuntime) StopContainer(ctr *Container, timeout uint, all bool) // Ping the container to see if it's alive // If it's not, it's already stopped, return err := unix.Kill(ctr.state.PID, 0) - if err == unix.ESRCH { + if errors.Is(err, unix.ESRCH) { return nil } @@ -1559,7 +1559,7 @@ func httpAttachTerminalCopy(container *net.UnixConn, http *bufio.ReadWriter, cid } } if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } return err @@ -1645,7 +1645,7 @@ func httpAttachNonTerminalCopy(container *net.UnixConn, http *bufio.ReadWriter, } } if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } diff --git a/libpod/oci_conmon_exec_common.go b/libpod/oci_conmon_exec_common.go index 8ff2019378..de4c721dbe 100644 --- a/libpod/oci_conmon_exec_common.go +++ b/libpod/oci_conmon_exec_common.go @@ -233,7 +233,7 @@ func (r *ConmonOCIRuntime) ExecStopContainer(ctr *Container, sessionID string, t // Use SIGTERM by default, then SIGSTOP after timeout. logrus.Debugf("Killing exec session %s (PID %d) of container %s with SIGTERM", sessionID, pid, ctr.ID()) if err := pidHandle.Kill(unix.SIGTERM); err != nil { - if err == unix.ESRCH { + if errors.Is(err, unix.ESRCH) { return nil } return fmt.Errorf("killing container %s exec session %s PID %d with SIGTERM: %w", ctr.ID(), sessionID, pid, err) @@ -251,7 +251,7 @@ func (r *ConmonOCIRuntime) ExecStopContainer(ctr *Container, sessionID string, t // SIGTERM did not work. On to SIGKILL. logrus.Debugf("Killing exec session %s (PID %d) of container %s with SIGKILL", sessionID, pid, ctr.ID()) if err := pidHandle.Kill(unix.SIGKILL); err != nil { - if err == unix.ESRCH { + if errors.Is(err, unix.ESRCH) { return nil } return fmt.Errorf("killing container %s exec session %s PID %d with SIGKILL: %w", ctr.ID(), sessionID, pid, err) diff --git a/libpod/runtime_ctr.go b/libpod/runtime_ctr.go index dc3066805b..b83a3c38d7 100644 --- a/libpod/runtime_ctr.go +++ b/libpod/runtime_ctr.go @@ -1195,7 +1195,7 @@ func (r *Runtime) evictContainer(ctx context.Context, idOrName string, removeVol if !volume.Anonymous() { continue } - if err := r.removeVolume(ctx, volume, false, timeout, false); err != nil && err != define.ErrNoSuchVolume && err != define.ErrVolumeBeingUsed { + if err := r.removeVolume(ctx, volume, false, timeout, false); err != nil && !errors.Is(err, define.ErrNoSuchVolume) && !errors.Is(err, define.ErrVolumeBeingUsed) { logrus.Errorf("Cleaning up volume (%s): %v", v.Name, err) } } @@ -1457,7 +1457,7 @@ func (r *Runtime) StorageContainers() ([]storage.Container, error) { retCtrs := []storage.Container{} for _, container := range storeContainers { exists, err := r.state.HasContainer(container.ID) - if err != nil && err != define.ErrNoSuchCtr { + if err != nil && !errors.Is(err, define.ErrNoSuchCtr) { return nil, fmt.Errorf("failed to check if %s container exists in database: %w", container.ID, err) } if exists { diff --git a/libpod/runtime_pod_linux.go b/libpod/runtime_pod_linux.go index 759d82e77d..d7229d27d7 100644 --- a/libpod/runtime_pod_linux.go +++ b/libpod/runtime_pod_linux.go @@ -3,6 +3,7 @@ package libpod import ( + "errors" "fmt" "path" "path/filepath" @@ -122,7 +123,7 @@ func (p *Pod) removePodCgroup() error { // hard - instead, just log errors. conmonCgroupPath := filepath.Join(p.state.CgroupPath, "conmon") conmonCgroup, err := cgroups.Load(conmonCgroupPath) - if err != nil && err != cgroups.ErrCgroupDeleted { + if err != nil && !errors.Is(err, cgroups.ErrCgroupDeleted) { return fmt.Errorf("retrieving pod %s conmon cgroup: %w", p.ID(), err) } if err == nil { @@ -131,7 +132,7 @@ func (p *Pod) removePodCgroup() error { } } cgroup, err := cgroups.Load(p.state.CgroupPath) - if err != nil && err != cgroups.ErrCgroupDeleted { + if err != nil && !errors.Is(err, cgroups.ErrCgroupDeleted) { return fmt.Errorf("retrieving pod %s cgroup: %w", p.ID(), err) } if err == nil { diff --git a/libpod/util_freebsd.go b/libpod/util_freebsd.go index 98af9a6410..4ac8b1e4a3 100644 --- a/libpod/util_freebsd.go +++ b/libpod/util_freebsd.go @@ -3,6 +3,7 @@ package libpod import ( + "errors" "syscall" "github.com/sirupsen/logrus" @@ -17,7 +18,7 @@ func LabelVolumePath(_, _ string) error { // Unmount umounts a target directory func Unmount(mount string) { if err := unix.Unmount(mount, unix.MNT_FORCE); err != nil { - if err != syscall.EINVAL { + if !errors.Is(err, syscall.EINVAL) { logrus.Warnf("Failed to unmount %s : %v", mount, err) } else { logrus.Debugf("failed to unmount %s : %v", mount, err) diff --git a/libpod/util_linux.go b/libpod/util_linux.go index 084a00e10b..779f435278 100644 --- a/libpod/util_linux.go +++ b/libpod/util_linux.go @@ -152,7 +152,7 @@ func LabelVolumePath(path, mountLabel string) error { // Unmount umounts a target directory func Unmount(mount string) { if err := unix.Unmount(mount, unix.MNT_DETACH); err != nil { - if err != syscall.EINVAL { + if !errors.Is(err, syscall.EINVAL) { logrus.Warnf("Failed to unmount %s : %v", mount, err) } else { logrus.Debugf("failed to unmount %s : %v", mount, err) diff --git a/libpod/volume_internal_common.go b/libpod/volume_internal_common.go index d7453b0a0c..45c80c8017 100644 --- a/libpod/volume_internal_common.go +++ b/libpod/volume_internal_common.go @@ -180,7 +180,7 @@ func (v *Volume) unmount(force bool) error { // Unmount the volume if err := detachUnmount(v.config.MountPoint); err != nil { - if err == unix.EINVAL { + if errors.Is(err, unix.EINVAL) { // Ignore EINVAL - the mount no longer exists. return nil } diff --git a/pkg/api/handlers/compat/containers.go b/pkg/api/handlers/compat/containers.go index 78249974d8..28783f1687 100644 --- a/pkg/api/handlers/compat/containers.go +++ b/pkg/api/handlers/compat/containers.go @@ -403,13 +403,13 @@ func LibpodToContainer(l *libpod.Container, sz bool, includeHealth bool) (*handl for _, b := range bindings { hostPortInt, err := strconv.Atoi(b.HostPort) if err != nil { - return nil, fmt.Errorf("invalid HostPort: %v", err) + return nil, fmt.Errorf("invalid HostPort: %w", err) } addr := netip.Addr{} if b.HostIP != "" { addr, err = netip.ParseAddr(b.HostIP) if err != nil { - return nil, fmt.Errorf("invalid HostIP: %v", err) + return nil, fmt.Errorf("invalid HostIP: %w", err) } } diff --git a/pkg/api/handlers/decoder.go b/pkg/api/handlers/decoder.go index 3f46498f0b..c0b6e87511 100644 --- a/pkg/api/handlers/decoder.go +++ b/pkg/api/handlers/decoder.go @@ -4,6 +4,7 @@ package handlers import ( "encoding/json" + "errors" "reflect" "strconv" "strings" @@ -128,7 +129,8 @@ func convertTimeString(query string) reflect.Value { return reflect.ValueOf(t) } - if _, isParseError := err.(*time.ParseError); isParseError { + var parseErr *time.ParseError + if errors.As(err, &parseErr) { // Try next format continue } else { diff --git a/pkg/api/handlers/libpod/images.go b/pkg/api/handlers/libpod/images.go index 3ab226cacd..c4c28041fb 100644 --- a/pkg/api/handlers/libpod/images.go +++ b/pkg/api/handlers/libpod/images.go @@ -361,7 +361,7 @@ func ImagesLoad(w http.ResponseWriter, r *http.Request) { _, err = io.Copy(tmpfile, r.Body) tmpfile.Close() - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { utils.Error(w, http.StatusInternalServerError, fmt.Errorf("unable to write archive to temporary file: %w", err)) return } @@ -451,7 +451,7 @@ func ImagesImport(w http.ResponseWriter, r *http.Request) { } defer os.Remove(tmpfile.Name()) - if _, err := io.Copy(tmpfile, r.Body); err != nil && err != io.EOF { + if _, err := io.Copy(tmpfile, r.Body); err != nil && !errors.Is(err, io.EOF) { utils.Error(w, http.StatusInternalServerError, fmt.Errorf("unable to write archive to temporary file: %w", err)) tmpfile.Close() return diff --git a/pkg/api/handlers/libpod/manifests.go b/pkg/api/handlers/libpod/manifests.go index b753233245..83dd3723b5 100644 --- a/pkg/api/handlers/libpod/manifests.go +++ b/pkg/api/handlers/libpod/manifests.go @@ -103,7 +103,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) { } status := http.StatusOK - if _, err := utils.SupportedVersion(r, "< 4.0.0"); err == apiutil.ErrVersionNotSupported { + if _, err := utils.SupportedVersion(r, "< 4.0.0"); errors.Is(err, apiutil.ErrVersionNotSupported) { status = http.StatusCreated } diff --git a/pkg/api/handlers/libpod/quadlets.go b/pkg/api/handlers/libpod/quadlets.go index e606bcf9bd..0036d43a3e 100644 --- a/pkg/api/handlers/libpod/quadlets.go +++ b/pkg/api/handlers/libpod/quadlets.go @@ -129,7 +129,7 @@ func processMultipartQuadlets(tempDir string, r *http.Request) ([]string, error) var filePaths []string for { part, err := reader.NextPart() - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { diff --git a/pkg/api/handlers/utils/errors.go b/pkg/api/handlers/utils/errors.go index 3f9d3a5700..9e8e129669 100644 --- a/pkg/api/handlers/utils/errors.go +++ b/pkg/api/handlers/utils/errors.go @@ -133,7 +133,8 @@ func GetInternalServerError(err error) *BuildError { } func ProcessBuildError(w http.ResponseWriter, err error) { - if buildErr, ok := err.(*BuildError); ok { + var buildErr *BuildError + if errors.As(err, &buildErr) { Error(w, buildErr.code, buildErr.err) return } diff --git a/pkg/api/handlers/utils/images.go b/pkg/api/handlers/utils/images.go index 0c774234c8..8c029a9e06 100644 --- a/pkg/api/handlers/utils/images.go +++ b/pkg/api/handlers/utils/images.go @@ -47,7 +47,7 @@ func NormalizeToDockerHub(r *http.Request, nameOrID string) (string, error) { img, candidate, err := runtime.LibimageRuntime().LookupImage(nameOrID, nil) if err != nil { if !errors.Is(err, storage.ErrImageUnknown) { - return "", fmt.Errorf("normalizing name for compat API: %v", err) + return "", fmt.Errorf("normalizing name for compat API: %w", err) } // If the image could not be resolved locally, set the // candidate back to the input. @@ -59,7 +59,7 @@ func NormalizeToDockerHub(r *http.Request, nameOrID string) (string, error) { // No ID, so we can normalize. named, err := reference.ParseNormalizedNamed(candidate) if err != nil { - return "", fmt.Errorf("normalizing name %q (orig: %q) for compat API: %v", candidate, nameOrID, err) + return "", fmt.Errorf("normalizing name %q (orig: %q) for compat API: %w", candidate, nameOrID, err) } return named.String(), nil diff --git a/pkg/api/server/server.go b/pkg/api/server/server.go index ea206a1430..de861da32d 100644 --- a/pkg/api/server/server.go +++ b/pkg/api/server/server.go @@ -5,6 +5,7 @@ package server import ( "context" "crypto/tls" + "errors" "fmt" "log" "net" @@ -265,7 +266,7 @@ func (s *APIServer) Serve() error { s.Server.Protocols.SetUnencryptedHTTP2(true) err = s.Server.Serve(s.Listener) } - if err != nil && err != http.ErrServerClosed { + if err != nil && !errors.Is(err, http.ErrServerClosed) { errChan <- fmt.Errorf("failed to start API service: %w", err) return } @@ -329,7 +330,7 @@ func (s *APIServer) Shutdown(halt bool) error { defer cancel() err := s.Server.Shutdown(ctx) - if err != nil && err != context.Canceled && err != http.ErrServerClosed { + if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, http.ErrServerClosed) { logrus.Error("Failed to cleanly shutdown API service: " + err.Error()) } }() diff --git a/pkg/bindings/artifacts/extract.go b/pkg/bindings/artifacts/extract.go index 81a7c7d84f..a8b759ae6f 100644 --- a/pkg/bindings/artifacts/extract.go +++ b/pkg/bindings/artifacts/extract.go @@ -59,7 +59,7 @@ func Extract(ctx context.Context, artifactName string, target string, options *E tr := tar.NewReader(response.Body) for { header, err := tr.Next() - if err == io.EOF { + if errors.Is(err, io.EOF) { break // End of archive } if err != nil { diff --git a/pkg/bindings/containers/attach.go b/pkg/bindings/containers/attach.go index 7962541694..1e0e97b99b 100644 --- a/pkg/bindings/containers/attach.go +++ b/pkg/bindings/containers/attach.go @@ -144,7 +144,7 @@ func Attach(ctx context.Context, nameOrID string, stdin io.Reader, stdout io.Wri // Ignore "closed network connection" as it occurs when the container ends, which is expected. // This avoids noisy logs but does not fix the goroutine leak // https://github.com/containers/podman/issues/25344 - if err != nil && err != define.ErrDetach && !errors.Is(err, net.ErrClosed) { + if err != nil && !errors.Is(err, define.ErrDetach) && !errors.Is(err, net.ErrClosed) { logrus.Errorf("Failed to write input to service: %v", err) } if err == nil { diff --git a/pkg/bindings/errors.go b/pkg/bindings/errors.go index bce1ef75eb..087946f977 100644 --- a/pkg/bindings/errors.go +++ b/pkg/bindings/errors.go @@ -55,14 +55,15 @@ func (h *APIResponse) ProcessWithError(unmarshalInto any, unmarshalErrorInto any } func CheckResponseCode(inError error) (int, error) { - switch e := inError.(type) { - case *errorhandling.ErrorModel: - return e.Code(), nil - case *errorhandling.PodConflictErrorModel: - return e.Code(), nil - default: - return -1, errors.New("is not type ErrorModel") + var errModel *errorhandling.ErrorModel + if errors.As(inError, &errModel) { + return errModel.Code(), nil } + var podConflictModel *errorhandling.PodConflictErrorModel + if errors.As(inError, &podConflictModel) { + return podConflictModel.Code(), nil + } + return -1, errors.New("is not type ErrorModel") } type APIVersionError struct { diff --git a/pkg/bindings/images/build.go b/pkg/bindings/images/build.go index e8c8f1f364..a2f96a1a46 100644 --- a/pkg/bindings/images/build.go +++ b/pkg/bindings/images/build.go @@ -1182,7 +1182,7 @@ func nTar(excludes []string, sources ...string) (io.ReadCloser, error) { if err == nil { return nil // non empty root dir, need to return } - if err != io.EOF { + if !errors.Is(err, io.EOF) { logrus.Errorf("While reading directory %v: %v", path, err) } } diff --git a/pkg/bindings/manifests/manifests.go b/pkg/bindings/manifests/manifests.go index 34d995a5cb..c42d61a818 100644 --- a/pkg/bindings/manifests/manifests.go +++ b/pkg/bindings/manifests/manifests.go @@ -364,11 +364,11 @@ func Modify(ctx context.Context, name string, images []string, options *ModifyOp } requestPartWriter, err := writer.CreatePart(headers) if err != nil { - artifactWriterError = fmt.Errorf("creating form part for request: %v", err) + artifactWriterError = fmt.Errorf("creating form part for request: %w", err) return } if _, err := io.Copy(requestPartWriter, requestBodyReader); err != nil { - artifactWriterError = fmt.Errorf("uploading request as form part: %v", err) + artifactWriterError = fmt.Errorf("uploading request as form part: %w", err) return } // now walk the list of files we're attaching diff --git a/pkg/domain/infra/abi/containers.go b/pkg/domain/infra/abi/containers.go index 6f8025ccfb..e1c511e435 100644 --- a/pkg/domain/infra/abi/containers.go +++ b/pkg/domain/infra/abi/containers.go @@ -804,7 +804,7 @@ func (ic *ContainerEngine) ContainerRestore(ctx context.Context, namesOrIds []st // CRImportCheckpoint is expected to import exactly one container from checkpoint image checkpointImageImportErrors = append( checkpointImageImportErrors, - fmt.Errorf("unable to import checkpoint from image: %q: %v", nameOrID, err), + fmt.Errorf("unable to import checkpoint from image: %q: %w", nameOrID, err), ) } else { ctrs = append(ctrs, importedCtrs[0]) diff --git a/pkg/domain/infra/abi/manifest.go b/pkg/domain/infra/abi/manifest.go index f65ab5d881..e9f61fca51 100644 --- a/pkg/domain/infra/abi/manifest.go +++ b/pkg/domain/infra/abi/manifest.go @@ -134,7 +134,7 @@ func (ir *ImageEngine) remoteManifestInspect(ctx context.Context, name string, o // FIXME should we use multierror package instead? // we want the new line here so ignore the linter - latestErr = fmt.Errorf("tried %v\n: %w", e, latestErr) + latestErr = fmt.Errorf("tried %w\n: %w", e, latestErr) } } @@ -402,7 +402,7 @@ func (ir *ImageEngine) digestFromDigestOrManifestListMember(ctx context.Context, } listData, inspectErr := list.Inspect() if inspectErr != nil { - return "", fmt.Errorf(`inspecting list "%s" for instance list: %v`, list.ID(), err) + return "", fmt.Errorf(`inspecting list "%s" for instance list: %w`, list.ID(), err) } // maybe the name is a file name we previously attached as part of an artifact manifest for _, descriptor := range listData.Manifests { @@ -446,7 +446,7 @@ func (ir *ImageEngine) digestFromDigestOrManifestListMember(ctx context.Context, func (ir *ImageEngine) ManifestRemoveDigest(_ context.Context, name, image string) (string, error) { instanceDigest, err := digest.Parse(image) if err != nil { - return "", fmt.Errorf(`invalid image digest "%s": %v`, image, err) + return "", fmt.Errorf(`invalid image digest "%s": %w`, image, err) } manifestList, err := ir.Libpod.LibimageRuntime().LookupManifestList(name) diff --git a/pkg/domain/infra/abi/play.go b/pkg/domain/infra/abi/play.go index 34e441ad00..b90331d0eb 100644 --- a/pkg/domain/infra/abi/play.go +++ b/pkg/domain/infra/abi/play.go @@ -1632,7 +1632,7 @@ func splitMultiDocYAML(yamlContent []byte) ([][]byte, error) { var o any // read individual document err := d.Decode(&o) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { diff --git a/pkg/domain/infra/abi/play_utils.go b/pkg/domain/infra/abi/play_utils.go index e4e4fd107f..e9e75a3b1a 100644 --- a/pkg/domain/infra/abi/play_utils.go +++ b/pkg/domain/infra/abi/play_utils.go @@ -3,6 +3,7 @@ package abi import ( + "errors" "fmt" "os" "strings" @@ -48,7 +49,7 @@ func openPathSafely(root, unsafeName string) (*os.File, error) { if err == nil { return os.NewFile(uintptr(fd), unsafeName), nil } - if err == unix.ELOOP { + if errors.Is(err, unix.ELOOP) { return openSymlinkPath(fdDir, unsafeName, flags) } return nil, &os.PathError{Op: "openat", Path: unsafeName, Err: err} diff --git a/pkg/domain/infra/tunnel/containers.go b/pkg/domain/infra/tunnel/containers.go index 6e7be5b1f2..fdf5acc353 100644 --- a/pkg/domain/infra/tunnel/containers.go +++ b/pkg/domain/infra/tunnel/containers.go @@ -331,8 +331,8 @@ func (ic *ContainerEngine) ContainerInspect(_ context.Context, namesOrIds []stri for _, name := range namesOrIds { inspect, err := containers.Inspect(ic.ClientCtx, name, options) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { @@ -822,7 +822,7 @@ func (ic *ContainerEngine) ContainerStart(_ context.Context, namesOrIds []string ctrRunning := ctr.State == define.ContainerStateRunning.String() if options.Attach { code, err := startAndAttach(ic, name, &options.DetachKeys, options.SigProxy, options.Stdin, options.Stdout, options.Stderr) - if err == define.ErrDetach { + if errors.Is(err, define.ErrDetach) { // User manually detached // Exit cleanly immediately reports = append(reports, &report) @@ -962,7 +962,7 @@ func (ic *ContainerEngine) ContainerRun(ctx context.Context, opts entities.Conta code, err := startAndAttach(ic, con.ID, &opts.DetachKeys, opts.SigProxy, opts.InputStream, opts.OutputStream, opts.ErrorStream) if err != nil { - if err == define.ErrDetach { + if errors.Is(err, define.ErrDetach) { return &report, nil } diff --git a/pkg/domain/infra/tunnel/images.go b/pkg/domain/infra/tunnel/images.go index 7b34120f8a..49e9eca0ca 100644 --- a/pkg/domain/infra/tunnel/images.go +++ b/pkg/domain/infra/tunnel/images.go @@ -204,8 +204,8 @@ func (ir *ImageEngine) Inspect(_ context.Context, namesOrIDs []string, opts enti for _, i := range namesOrIDs { r, err := images.GetImage(ir.ClientCtx, i, options) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { diff --git a/pkg/domain/infra/tunnel/network.go b/pkg/domain/infra/tunnel/network.go index 0e9646eaf3..2a59446bb7 100644 --- a/pkg/domain/infra/tunnel/network.go +++ b/pkg/domain/infra/tunnel/network.go @@ -31,8 +31,8 @@ func (ic *ContainerEngine) NetworkInspect(_ context.Context, namesOrIds []string for _, name := range namesOrIds { report, err := network.Inspect(ic.ClientCtx, name, options) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { diff --git a/pkg/domain/infra/tunnel/pods.go b/pkg/domain/infra/tunnel/pods.go index f29374ec45..c7fe07487d 100644 --- a/pkg/domain/infra/tunnel/pods.go +++ b/pkg/domain/infra/tunnel/pods.go @@ -233,8 +233,8 @@ func (ic *ContainerEngine) PodInspect(_ context.Context, namesOrIDs []string, _ for _, name := range namesOrIDs { inspect, err := pods.Inspect(ic.ClientCtx, name, nil) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { diff --git a/pkg/domain/infra/tunnel/secrets.go b/pkg/domain/infra/tunnel/secrets.go index 72638ace08..be8691cc28 100644 --- a/pkg/domain/infra/tunnel/secrets.go +++ b/pkg/domain/infra/tunnel/secrets.go @@ -2,6 +2,7 @@ package tunnel import ( "context" + "errors" "fmt" "io" @@ -34,8 +35,8 @@ func (ic *ContainerEngine) SecretInspect(_ context.Context, nameOrIDs []string, for _, name := range nameOrIDs { inspected, err := secrets.Inspect(ic.ClientCtx, name, opts) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { @@ -73,8 +74,8 @@ func (ic *ContainerEngine) SecretRm(_ context.Context, nameOrIDs []string, optio for _, name := range nameOrIDs { secret, err := secrets.Inspect(ic.ClientCtx, name, nil) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, err } if errModel.ResponseCode == 404 { diff --git a/pkg/domain/infra/tunnel/volumes.go b/pkg/domain/infra/tunnel/volumes.go index c8c53d7f4d..1389af1bb8 100644 --- a/pkg/domain/infra/tunnel/volumes.go +++ b/pkg/domain/infra/tunnel/volumes.go @@ -60,8 +60,8 @@ func (ic *ContainerEngine) VolumeInspect(_ context.Context, namesOrIds []string, for _, id := range namesOrIds { data, err := volumes.Inspect(ic.ClientCtx, id, nil) if err != nil { - errModel, ok := err.(*errorhandling.ErrorModel) - if !ok { + var errModel *errorhandling.ErrorModel + if !errors.As(err, &errModel) { return nil, nil, err } if errModel.ResponseCode == 404 { diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go b/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go index b8fc531ad8..53afc0e7d2 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go @@ -134,7 +134,7 @@ const ( func MustParse(str string) Quantity { q, err := ParseQuantity(str) if err != nil { - panic(fmt.Errorf("cannot parse '%v': %v", str, err)) + panic(fmt.Errorf("cannot parse '%v': %w", str, err)) } return q } diff --git a/pkg/machine/define/vmfile.go b/pkg/machine/define/vmfile.go index 7f8bb64f7c..7b27398ca6 100644 --- a/pkg/machine/define/vmfile.go +++ b/pkg/machine/define/vmfile.go @@ -58,7 +58,7 @@ func (m *VMFile) ReadMagicNumber(n int) ([]byte, error) { defer f.Close() b := make([]byte, n) n, err = io.ReadFull(f, b) - if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF { + if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { return b[:n], err } else { return b[:n], nil diff --git a/pkg/machine/hyperv/stubber.go b/pkg/machine/hyperv/stubber.go index 55e347d2db..bc089d6672 100644 --- a/pkg/machine/hyperv/stubber.go +++ b/pkg/machine/hyperv/stubber.go @@ -124,7 +124,7 @@ func (h HyperVStubber) CreateVM(_ define.CreateVMOpts, mc *vmconfigs.MachineConf } if err := vsock.RemoveAllHVSockRegistryEntries(); err != nil { - return fmt.Errorf("unable to remove hvsock registry entries: %q", err) + return fmt.Errorf("unable to remove hvsock registry entries: %w", err) } return nil @@ -796,7 +796,7 @@ func resizeDisk(newSize strongunits.GiB, imagePath *define.VMFile) error { resize.Stderr = os.Stderr resize.Env = append(os.Environ(), "IMAGE_PATH="+imagePath.GetPath()) if err := resize.Run(); err != nil { - return fmt.Errorf("resizing image: %q", err) + return fmt.Errorf("resizing image: %w", err) } return nil } diff --git a/pkg/machine/ignition/ignition.go b/pkg/machine/ignition/ignition.go index 498e56613c..45abb369ce 100644 --- a/pkg/machine/ignition/ignition.go +++ b/pkg/machine/ignition/ignition.go @@ -149,7 +149,7 @@ func (ign *DynamicIgnition) GenerateIgnitionConfig() error { } else { tz, err = getLocalTimeZone() if err != nil { - return fmt.Errorf("error getting local timezone: %q", err) + return fmt.Errorf("error getting local timezone: %w", err) } } } diff --git a/pkg/machine/ocipull/ociartifact.go b/pkg/machine/ocipull/ociartifact.go index 66473fca4d..8b444ee1bf 100644 --- a/pkg/machine/ocipull/ociartifact.go +++ b/pkg/machine/ocipull/ociartifact.go @@ -164,7 +164,7 @@ func (o *OCIArtifactDisk) get() (func(), error) { // check if we have the latest and greatest disk image if _, err = os.Stat(cachedImagePath.GetPath()); err != nil { if !errors.Is(err, os.ErrNotExist) { - return nil, fmt.Errorf("unable to access cached image path %q: %q", cachedImagePath.GetPath(), err) + return nil, fmt.Errorf("unable to access cached image path %q: %w", cachedImagePath.GetPath(), err) } // On cache misses, we clean out the cache @@ -294,7 +294,7 @@ func (o *OCIArtifactDisk) unpack(diskArtifactHash digest.Digest) error { blobInfo, err := GetLocalBlob(o.ctx, blobDir.GetPath()) if err != nil { - return fmt.Errorf("unable to get local manifest for %s: %q", blobDir.GetPath(), err) + return fmt.Errorf("unable to get local manifest for %s: %w", blobDir.GetPath(), err) } diskBlobPath := filepath.Join(blobDir.GetPath(), "blobs", "sha256", blobInfo.Digest.Encoded()) diff --git a/pkg/machine/ocipull/source.go b/pkg/machine/ocipull/source.go index 7d3174f49d..2b15d97082 100644 --- a/pkg/machine/ocipull/source.go +++ b/pkg/machine/ocipull/source.go @@ -54,7 +54,7 @@ func GetDiskArtifactReference(ctx context.Context, imgSrc types.ImageSource, opt mannyFestList, err := manifest.ListFromBlob(rawMannyFest, mannyType) if err != nil { - return "", fmt.Errorf("failed to parse manifest list from blob: %q", err) + return "", fmt.Errorf("failed to parse manifest list from blob: %w", err) } var artifactDigest digest.Digest diff --git a/pkg/machine/qemu/stubber.go b/pkg/machine/qemu/stubber.go index 17b872101e..4c570a661f 100644 --- a/pkg/machine/qemu/stubber.go +++ b/pkg/machine/qemu/stubber.go @@ -147,7 +147,7 @@ func runStartVMCommand(cmd *exec.Cmd) error { func (q *QEMUStubber) StartVM(mc *vmconfigs.MachineConfig) (func() error, func() error, error) { if err := q.setQEMUCommandLine(mc); err != nil { - return nil, nil, fmt.Errorf("unable to generate qemu command line: %q", err) + return nil, nil, fmt.Errorf("unable to generate qemu command line: %w", err) } readySocket, err := mc.ReadySocket() @@ -283,7 +283,7 @@ func (q *QEMUStubber) resizeDisk(newSize strongunits.GiB, diskPath *define.VMFil resize.Stdout = os.Stdout resize.Stderr = os.Stderr if err := resize.Run(); err != nil { - return fmt.Errorf("resizing image: %q", err) + return fmt.Errorf("resizing image: %w", err) } return nil diff --git a/pkg/machine/shim/host.go b/pkg/machine/shim/host.go index 447d120602..c4a21d0497 100644 --- a/pkg/machine/shim/host.go +++ b/pkg/machine/shim/host.go @@ -721,7 +721,7 @@ func startLocked(mc *vmconfigs.MachineConfig, mp vmconfigs.VMProvider, dirs *mac if !connected { msg := "machine did not transition into running state" if sshError != nil { - return fmt.Errorf("%s: ssh error: %v", msg, sshError) + return fmt.Errorf("%s: ssh error: %w", msg, sshError) } return errors.New(msg) } diff --git a/pkg/machine/vmconfigs/machine.go b/pkg/machine/vmconfigs/machine.go index b231d4b40c..102d0b1f39 100644 --- a/pkg/machine/vmconfigs/machine.go +++ b/pkg/machine/vmconfigs/machine.go @@ -342,7 +342,7 @@ func loadMachineFromFQPath(path *define.VMFile) (*MachineConfig, error) { } if err = json.Unmarshal(b, mc); err != nil { - return nil, fmt.Errorf("unable to load machine config file: %q", err) + return nil, fmt.Errorf("unable to load machine config file: %w", err) } lock, err := lock.GetMachineLock(mc.Name, filepath.Dir(path.GetPath())) mc.lock = lock diff --git a/pkg/machine/wsl/machine.go b/pkg/machine/wsl/machine.go index 9690c83443..5eaa7a84f2 100644 --- a/pkg/machine/wsl/machine.go +++ b/pkg/machine/wsl/machine.go @@ -333,7 +333,8 @@ func launchElevate(operation string) error { } err := winutil.RelaunchElevatedWait() if err != nil { - if eerr, ok := err.(*winutil.ExitCodeError); ok { + var eerr *winutil.ExitCodeError + if errors.As(err, &eerr) { if eerr.Code == ErrorSuccessRebootRequired { fmt.Println("Reboot is required to continue installation, please reboot at your convenience") return define.ErrRelaunchSucceeded @@ -374,7 +375,8 @@ func isMsiError(err error) bool { return false } - if eerr, ok := err.(*exec.ExitError); ok { + var eerr *exec.ExitError + if errors.As(err, &eerr) { switch eerr.ExitCode() { case 0: fallthrough diff --git a/pkg/machine/wsl/usermodenet.go b/pkg/machine/wsl/usermodenet.go index ca210106c9..5d4b6d78f7 100644 --- a/pkg/machine/wsl/usermodenet.go +++ b/pkg/machine/wsl/usermodenet.go @@ -153,7 +153,8 @@ func stopUserModeNetworking(mc *vmconfigs.MachineConfig) error { err = wslPipe(stopUserModeNet, userModeDist, "bash") if err != nil { - if exitErr, ok := err.(*exec.ExitError); ok { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { switch exitErr.ExitCode() { case 2: err = fmt.Errorf("startup state was missing") @@ -184,7 +185,8 @@ func launchUserModeNetDist(exeFile string) error { if err := wslPipe(cmdStr, userModeDist, "bash"); err != nil { _ = terminateDist(userModeDist) - if exitErr, ok := err.(*exec.ExitError); ok { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { switch exitErr.ExitCode() { case 2: return fmt.Errorf("another user-mode network is running, only one can be used at a time: shut down all machines and run wsl --shutdown if this is unexpected") diff --git a/pkg/pidhandle/pidhandle.go b/pkg/pidhandle/pidhandle.go index db93dcc6d4..8971c538c1 100644 --- a/pkg/pidhandle/pidhandle.go +++ b/pkg/pidhandle/pidhandle.go @@ -4,6 +4,7 @@ package pidhandle import ( + "errors" "strconv" "strings" @@ -75,7 +76,7 @@ func (h *pidHandle) Kill(signal unix.Signal) error { if found { p, err := process.NewProcess(int32(h.pid)) if err != nil { - if err == process.ErrorProcessNotRunning { + if errors.Is(err, process.ErrorProcessNotRunning) { return unix.ESRCH } return err @@ -98,7 +99,7 @@ func (h *pidHandle) Kill(signal unix.Signal) error { func (h *pidHandle) IsAlive() (bool, error) { err := h.Kill(0) if err != nil { - if err == unix.ESRCH { + if errors.Is(err, unix.ESRCH) { return false, nil } return false, err @@ -117,7 +118,7 @@ func (h *pidHandle) String() (string, error) { // Get the start-time of the process and return it as string. p, err := process.NewProcess(int32(h.pid)) if err != nil { - if err == process.ErrorProcessNotRunning { + if errors.Is(err, process.ErrorProcessNotRunning) { return noSuchProcessID, nil } return "", err diff --git a/pkg/pidhandle/pidhandle_linux.go b/pkg/pidhandle/pidhandle_linux.go index 6e0140069f..af16f64d3c 100644 --- a/pkg/pidhandle/pidhandle_linux.go +++ b/pkg/pidhandle/pidhandle_linux.go @@ -5,6 +5,7 @@ package pidhandle import ( "encoding/hex" + "errors" "fmt" "os" "strconv" @@ -43,18 +44,18 @@ func NewPIDHandle(pid int) (PIDHandle, error) { pidData := "" pidfd, err := pidfdOpen(pid, 0) if err != nil { - switch err { - case unix.ENOSYS: + switch { + case errors.Is(err, unix.ENOSYS): // Do not fail if PidFdOpen is not supported, we will // fallback to process start-time later. - case unix.ESRCH: + case errors.Is(err, unix.ESRCH): // The process does not exist, so any future call of Kill // or IsAlive should return unix.ESRCH, even if the pid is // recycled in the future. Let's note it in the pidData. pidData = noSuchProcessID - case unix.EINVAL: + case errors.Is(err, unix.EINVAL): // The PidfdOpen returns EINVAL if pid is invalid or if it refers // to a thread and not to process. This is not a valid PID for // PIDHandle and it most likely means the pid has been recycled @@ -120,7 +121,7 @@ func NewPIDHandleFromString(pid int, pidData string) (PIDHandle, error) { defer unix.Close(fd) pidfd, err := openByHandleAt(fd, fh, unix.O_CLOEXEC) if err != nil { - if err == unix.ESTALE { + if errors.Is(err, unix.ESTALE) { h.normalHandle.pidData = noSuchProcessID return &h, nil } @@ -163,7 +164,7 @@ func (h *pidfdHandle) Kill(signal unix.Signal) error { func (h *pidfdHandle) IsAlive() (bool, error) { err := h.Kill(0) if err != nil { - if err == unix.ESRCH { + if errors.Is(err, unix.ESRCH) { return false, nil } return false, err @@ -185,7 +186,7 @@ func (h *pidfdHandle) String() (string, error) { if err != nil { // Do not fail if NameToHandleAt is not supported, we will // fallback to process start-time later. - if err == unix.ENOTSUP { + if errors.Is(err, unix.ENOTSUP) { logrus.Debugf("NameToHandleAt(%d) failed: %v", h.pidfd, err) } else { return "", err diff --git a/pkg/rctl/rctl_freebsd.go b/pkg/rctl/rctl_freebsd.go index e7e3671923..37e889a764 100644 --- a/pkg/rctl/rctl_freebsd.go +++ b/pkg/rctl/rctl_freebsd.go @@ -23,7 +23,7 @@ func GetRacct(filter string) (map[string]uint64, error) { uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0, 0) if errno != 0 { - return nil, fmt.Errorf("error calling rctl_get_racct with filter %s: %v", filter, errno) + return nil, fmt.Errorf("error calling rctl_get_racct with filter %s: %w", filter, errno) } len := bytes.IndexByte(buf[:], byte(0)) res := make(map[string]uint64) diff --git a/pkg/specgen/generate/kube/kube.go b/pkg/specgen/generate/kube/kube.go index 7093312079..109000f2ba 100644 --- a/pkg/specgen/generate/kube/kube.go +++ b/pkg/specgen/generate/kube/kube.go @@ -1110,7 +1110,7 @@ func k8sSecretFromSecretManager(name string, secretsManager *secrets.SecretsMana secrets = make(map[string][]byte) var secret v1.Secret if err := yaml.Unmarshal(inputSecret, &secret); err != nil { - return nil, fmt.Errorf("secret %v is not valid JSON/YAML: %v", name, err) + return nil, fmt.Errorf("secret %v is not valid JSON/YAML: %w", name, err) } maps.Copy(secrets, secret.Data) @@ -1193,7 +1193,7 @@ func envVarValue(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error) { err = fmt.Errorf("secret %v has not %v key", secKeyRef.Name, secKeyRef.Key) } if secKeyRef.Optional == nil || !*secKeyRef.Optional { - return nil, fmt.Errorf("cannot set env %v: %v", env.Name, err) + return nil, fmt.Errorf("cannot set env %v: %w", env.Name, err) } return nil, nil } diff --git a/pkg/util/utils_linux.go b/pkg/util/utils_linux.go index ff094bca0f..467b4a2224 100644 --- a/pkg/util/utils_linux.go +++ b/pkg/util/utils_linux.go @@ -214,7 +214,7 @@ func getDevices(path string) ([]spec.LinuxDevice, error) { device, err := DeviceFromPath(filepath.Join(path, f.Name())) if err != nil { - if err == errNotADevice { + if errors.Is(err, errNotADevice) { continue } if errors.Is(err, fs.ErrNotExist) { diff --git a/test/e2e/common_test.go b/test/e2e/common_test.go index 934a287bcc..32fc3e04e7 100644 --- a/test/e2e/common_test.go +++ b/test/e2e/common_test.go @@ -1122,7 +1122,8 @@ func SkipIfSystemdNotRunning(reason string) { cmd := exec.Command("systemctl", "list-units") err := cmd.Run() if err != nil { - if _, ok := err.(*exec.Error); ok { + var execErr *exec.Error + if errors.As(err, &execErr) { Skip("[notSystemd]: not running " + reason) } Expect(err).ToNot(HaveOccurred()) diff --git a/test/e2e/run_networking_test.go b/test/e2e/run_networking_test.go index 928fd82154..ce584f6ae4 100644 --- a/test/e2e/run_networking_test.go +++ b/test/e2e/run_networking_test.go @@ -3,6 +3,7 @@ package integration import ( + "errors" "fmt" "io" "math/rand" @@ -741,7 +742,7 @@ EXPOSE 2004-2005/tcp`, ALPINE) _, ipnet, err := net.ParseCIDR(cidr) Expect(err).ToNot(HaveOccurred()) addr := &netlink.Addr{IPNet: ipnet, Label: ""} - if err := netlink.AddrAdd(containerInterface, addr); err != nil && err != syscall.EEXIST { + if err := netlink.AddrAdd(containerInterface, addr); err != nil && !errors.Is(err, syscall.EEXIST) { return err } return nil diff --git a/utils/utils.go b/utils/utils.go index 527feef812..ed24bacb5d 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -28,7 +28,7 @@ func ExecCmd(name string, args ...string) (string, error) { err := cmd.Run() if err != nil { - return "", fmt.Errorf("`%v %v` failed: %v %v (%v)", name, strings.Join(args, " "), stderr.String(), stdout.String(), err) + return "", fmt.Errorf("`%v %v` failed: %v %v (%w)", name, strings.Join(args, " "), stderr.String(), stdout.String(), err) } return stdout.String(), nil @@ -44,7 +44,7 @@ func ExecCmdWithStdStreams(stdin io.Reader, stdout, stderr io.Writer, env []stri err := cmd.Run() if err != nil { - return fmt.Errorf("`%v %v` failed: %v", name, strings.Join(args, " "), err) + return fmt.Errorf("`%v %v` failed: %w", name, strings.Join(args, " "), err) } return nil