fix a number of errcheck issues

Numerous issues remain, especially in tests/e2e.

Signed-off-by: Valentin Rothberg <vrothberg@redhat.com>
This commit is contained in:
Valentin Rothberg
2022-03-21 15:47:01 +01:00
parent 6c030cd573
commit 06dd9136a2
32 changed files with 77 additions and 59 deletions

View File

@ -267,7 +267,9 @@ func saveToRemote(image, localFile string, tag string, uri *urlP.URL, iden strin
return err return err
} }
n, err := scpD.CopyFrom(dial, remoteFile, localFile) n, err := scpD.CopyFrom(dial, remoteFile, localFile)
connection.ExecRemoteCommand(dial, "rm "+remoteFile) if _, conErr := connection.ExecRemoteCommand(dial, "rm "+remoteFile); conErr != nil {
logrus.Errorf("Error removing file on endpoint: %v", conErr)
}
if err != nil { if err != nil {
errOut := strconv.Itoa(int(n)) + " Bytes copied before error" errOut := strconv.Itoa(int(n)) + " Bytes copied before error"
return errors.Wrapf(err, errOut) return errors.Wrapf(err, errOut)

View File

@ -83,7 +83,7 @@ func init() {
"reexec", false, "reexec", false,
"process was rexeced", "process was rexeced",
) )
flags.MarkHidden("reexec") _ = flags.MarkHidden("reexec")
ImagePathFlagName := "image-path" ImagePathFlagName := "image-path"
flags.StringVar(&initOpts.ImagePath, ImagePathFlagName, cfg.Machine.Image, "Path to qcow image") flags.StringVar(&initOpts.ImagePath, ImagePathFlagName, cfg.Machine.Image, "Path to qcow image")

View File

@ -60,7 +60,7 @@ func networkCreateFlags(cmd *cobra.Command) {
macvlanFlagName := "macvlan" macvlanFlagName := "macvlan"
flags.StringVar(&networkCreateOptions.MacVLAN, macvlanFlagName, "", "create a Macvlan connection based on this device") flags.StringVar(&networkCreateOptions.MacVLAN, macvlanFlagName, "", "create a Macvlan connection based on this device")
// This option is deprecated // This option is deprecated
flags.MarkHidden(macvlanFlagName) _ = flags.MarkHidden(macvlanFlagName)
labelFlagName := "label" labelFlagName := "label"
flags.StringArrayVar(&labels, labelFlagName, nil, "set metadata on a network") flags.StringArrayVar(&labels, labelFlagName, nil, "set metadata on a network")

View File

@ -402,7 +402,7 @@ func rootFlags(cmd *cobra.Command, opts *entities.PodmanConfig) {
networkBackendFlagName := "network-backend" networkBackendFlagName := "network-backend"
pFlags.StringVar(&cfg.Network.NetworkBackend, networkBackendFlagName, cfg.Network.NetworkBackend, `Network backend to use ("cni"|"netavark")`) pFlags.StringVar(&cfg.Network.NetworkBackend, networkBackendFlagName, cfg.Network.NetworkBackend, `Network backend to use ("cni"|"netavark")`)
_ = cmd.RegisterFlagCompletionFunc(networkBackendFlagName, common.AutocompleteNetworkBackend) _ = cmd.RegisterFlagCompletionFunc(networkBackendFlagName, common.AutocompleteNetworkBackend)
pFlags.MarkHidden(networkBackendFlagName) _ = pFlags.MarkHidden(networkBackendFlagName)
rootFlagName := "root" rootFlagName := "root"
pFlags.StringVar(&cfg.Engine.StaticDir, rootFlagName, "", "Path to the root directory in which data, including images, is stored") pFlags.StringVar(&cfg.Engine.StaticDir, rootFlagName, "", "Path to the root directory in which data, including images, is stored")

View File

@ -67,7 +67,7 @@ func init() {
flags.StringVarP(&srvArgs.PProfAddr, "pprof-address", "", "", flags.StringVarP(&srvArgs.PProfAddr, "pprof-address", "", "",
"Binding network address for pprof profile endpoints, default: do not expose endpoints") "Binding network address for pprof profile endpoints, default: do not expose endpoints")
flags.MarkHidden("pprof-address") _ = flags.MarkHidden("pprof-address")
} }
func aliasTimeoutFlag(_ *pflag.FlagSet, name string) pflag.NormalizedName { func aliasTimeoutFlag(_ *pflag.FlagSet, name string) pflag.NormalizedName {

View File

@ -27,7 +27,7 @@ func SubCommandExists(cmd *cobra.Command, args []string) error {
} }
return errors.Errorf("unrecognized command `%[1]s %[2]s`\n\nDid you mean this?\n\t%[3]s\n\nTry '%[1]s --help' for more information.", cmd.CommandPath(), args[0], strings.Join(suggestions, "\n\t")) return errors.Errorf("unrecognized command `%[1]s %[2]s`\n\nDid you mean this?\n\t%[3]s\n\nTry '%[1]s --help' for more information.", cmd.CommandPath(), args[0], strings.Join(suggestions, "\n\t"))
} }
cmd.Help() cmd.Help() // nolint: errcheck
return errors.Errorf("missing command '%[1]s COMMAND'", cmd.CommandPath()) return errors.Errorf("missing command '%[1]s COMMAND'", cmd.CommandPath())
} }

View File

@ -253,9 +253,9 @@ func serve(listener net.Listener, pm rkport.Manager) {
ctx := context.TODO() ctx := context.TODO()
err = handler(ctx, conn, pm) err = handler(ctx, conn, pm)
if err != nil { if err != nil {
conn.Write([]byte(err.Error())) _, _ = conn.Write([]byte(err.Error()))
} else { } else {
conn.Write([]byte("OK")) _, _ = conn.Write([]byte("OK"))
} }
conn.Close() conn.Close()
} }

View File

@ -366,8 +366,7 @@ func (s *BoltState) GetDBConfig() (*DBConfig, error) {
err = db.View(func(tx *bolt.Tx) error { err = db.View(func(tx *bolt.Tx) error {
configBucket, err := getRuntimeConfigBucket(tx) configBucket, err := getRuntimeConfigBucket(tx)
if err != nil { if err != nil {
// FIXME: this error should probably be returned return err
return nil // nolint: nilerr
} }
// Some of these may be nil // Some of these may be nil

View File

@ -921,7 +921,11 @@ func (c *Container) Stat(ctx context.Context, containerPath string) (*define.Fil
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer c.unmount(false) defer func() {
if err := c.unmount(false); err != nil {
logrus.Errorf("Unmounting container %s: %v", c.ID(), err)
}
}()
} }
info, _, _, err := c.stat(ctx, mountPoint, containerPath) info, _, _, err := c.stat(ctx, mountPoint, containerPath)

View File

@ -2740,7 +2740,6 @@ func (c *Container) generateUserPasswdEntry(addedUID int) (string, int, int, err
// If a non numeric User, then don't generate passwd // If a non numeric User, then don't generate passwd
uid, err := strconv.ParseUint(userspec, 10, 32) uid, err := strconv.ParseUint(userspec, 10, 32)
if err != nil { if err != nil {
// FIXME: this error should probably be returned
return "", 0, 0, nil // nolint: nilerr return "", 0, 0, nil // nolint: nilerr
} }

View File

@ -9,6 +9,7 @@ import (
"github.com/containers/podman/v4/pkg/util" "github.com/containers/podman/v4/pkg/util"
"github.com/containers/storage/pkg/lockfile" "github.com/containers/storage/pkg/lockfile"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// EventLogFile is the structure for event writing to a logfile. It contains the eventer // EventLogFile is the structure for event writing to a logfile. It contains the eventer
@ -59,7 +60,9 @@ func (e EventLogFile) Read(ctx context.Context, options ReadOptions) error {
} }
go func() { go func() {
time.Sleep(time.Until(untilTime)) time.Sleep(time.Until(untilTime))
t.Stop() if err := t.Stop(); err != nil {
logrus.Errorf("Stopping logger: %v", err)
}
}() }()
} }
funcDone := make(chan bool) funcDone := make(chan bool)

View File

@ -44,7 +44,8 @@ var _ = Describe("Podman containers attach", func() {
timeout := uint(5) timeout := uint(5)
err := containers.Stop(bt.conn, id, new(containers.StopOptions).WithTimeout(timeout)) err := containers.Stop(bt.conn, id, new(containers.StopOptions).WithTimeout(timeout))
if err != nil { if err != nil {
GinkgoWriter.Write([]byte(err.Error())) _, writeErr := GinkgoWriter.Write([]byte(err.Error()))
Expect(writeErr).ShouldNot(HaveOccurred())
} }
}() }()

View File

@ -40,7 +40,8 @@ var _ = Describe("Podman images", func() {
AfterEach(func() { AfterEach(func() {
s.Kill() s.Kill()
bt.cleanup() bt.cleanup()
registry.Stop() err := registry.Stop()
Expect(err).To(BeNil())
}) })
// Test using credentials. // Test using credentials.

View File

@ -322,7 +322,8 @@ var _ = Describe("Podman containers ", func() {
// a container that has no healthcheck should be a 409 // a container that has no healthcheck should be a 409
var name = "top" var name = "top"
bt.RunTopContainer(&name, nil) _, err = bt.RunTopContainer(&name, nil)
Expect(err).To(BeNil())
_, err = containers.RunHealthCheck(bt.conn, name, nil) _, err = containers.RunHealthCheck(bt.conn, name, nil)
Expect(err).ToNot(BeNil()) Expect(err).ToNot(BeNil())
code, _ = bindings.CheckResponseCode(err) code, _ = bindings.CheckResponseCode(err)

View File

@ -102,7 +102,7 @@ func CRApplyRootFsDiffTar(baseDirectory, containerRootDirectory string) error {
// Only do this if a rootfs-diff.tar actually exists // Only do this if a rootfs-diff.tar actually exists
rootfsDiffFile, err := os.Open(rootfsDiffPath) rootfsDiffFile, err := os.Open(rootfsDiffPath)
if err != nil { if err != nil {
if os.IsNotExist(err) { if errors.Is(err, os.ErrNotExist) {
return nil return nil
} }
return errors.Wrap(err, "failed to open root file-system diff file") return errors.Wrap(err, "failed to open root file-system diff file")

View File

@ -213,7 +213,7 @@ func GenerateContainerFilterFuncs(filter string, filterValues []string, r *libpo
for _, val := range filterValues { for _, val := range filterValues {
net, err := r.Network().NetworkInspect(val) net, err := r.Network().NetworkInspect(val)
if err != nil { if err != nil {
if errors.Cause(err) == define.ErrNoSuchNetwork { if errors.Is(err, define.ErrNoSuchNetwork) {
continue continue
} }
return nil, err return nil, err

View File

@ -131,7 +131,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti
for _, val := range filterValues { for _, val := range filterValues {
net, err := r.Network().NetworkInspect(val) net, err := r.Network().NetworkInspect(val)
if err != nil { if err != nil {
if errors.Cause(err) == define.ErrNoSuchNetwork { if errors.Is(err, define.ErrNoSuchNetwork) {
continue continue
} }
return nil, err return nil, err

View File

@ -848,13 +848,12 @@ func execPodman(execUser *user.User, command []string) error {
if err != nil { if err != nil {
return err return err
} }
defer func() error {
err := cmdLogin.Process.Kill() defer func() {
if err != nil { _ = cmdLogin.Process.Kill()
return err _ = cmdLogin.Wait()
}
return cmdLogin.Wait()
}() }()
cmd := exec.Command(command[0], command[1:]...) cmd := exec.Command(command[0], command[1:]...)
cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "TERM=" + os.Getenv("TERM")} cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "TERM=" + os.Getenv("TERM")}
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr

View File

@ -215,7 +215,7 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY
// FIXME This is very hard to support properly with a good ux // FIXME This is very hard to support properly with a good ux
if len(options.StaticIPs) > *ipIndex { if len(options.StaticIPs) > *ipIndex {
if !podOpt.Net.Network.IsBridge() { if !podOpt.Net.Network.IsBridge() {
errors.Wrap(define.ErrInvalidArg, "static ip addresses can only be set when the network mode is bridge") return nil, errors.Wrap(define.ErrInvalidArg, "static ip addresses can only be set when the network mode is bridge")
} }
if len(podOpt.Net.Networks) != 1 { if len(podOpt.Net.Networks) != 1 {
return nil, errors.Wrap(define.ErrInvalidArg, "cannot set static ip addresses for more than network, use netname:ip=<ip> syntax to specify ips for more than network") return nil, errors.Wrap(define.ErrInvalidArg, "cannot set static ip addresses for more than network, use netname:ip=<ip> syntax to specify ips for more than network")
@ -230,7 +230,7 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY
} }
if len(options.StaticMACs) > *ipIndex { if len(options.StaticMACs) > *ipIndex {
if !podOpt.Net.Network.IsBridge() { if !podOpt.Net.Network.IsBridge() {
errors.Wrap(define.ErrInvalidArg, "static mac address can only be set when the network mode is bridge") return nil, errors.Wrap(define.ErrInvalidArg, "static mac address can only be set when the network mode is bridge")
} }
if len(podOpt.Net.Networks) != 1 { if len(podOpt.Net.Networks) != 1 {
return nil, errors.Wrap(define.ErrInvalidArg, "cannot set static mac address for more than network, use netname:mac=<mac> syntax to specify mac for more than network") return nil, errors.Wrap(define.ErrInvalidArg, "cannot set static mac address for more than network, use netname:mac=<mac> syntax to specify mac for more than network")

View File

@ -20,7 +20,7 @@ const signalBufferSize = 2048
func ProxySignals(ctr *libpod.Container) { func ProxySignals(ctr *libpod.Container) {
// Stop catching the shutdown signals (SIGINT, SIGTERM) - they're going // Stop catching the shutdown signals (SIGINT, SIGTERM) - they're going
// to the container now. // to the container now.
shutdown.Stop() shutdown.Stop() // nolint: errcheck
sigBuffer := make(chan os.Signal, signalBufferSize) sigBuffer := make(chan os.Signal, signalBufferSize)
signal.CatchAll(sigBuffer) signal.CatchAll(sigBuffer)

View File

@ -59,7 +59,7 @@ func (f FedoraDownload) Get() *Download {
func (f FedoraDownload) HasUsableCache() (bool, error) { func (f FedoraDownload) HasUsableCache() (bool, error) {
info, err := os.Stat(f.LocalPath) info, err := os.Stat(f.LocalPath)
if err != nil { if err != nil {
if os.IsNotExist(err) { if errors.Is(err, os.ErrNotExist) {
return false, nil return false, nil
} }
return false, err return false, err

View File

@ -278,7 +278,9 @@ func (v *MachineVM) Init(opts machine.InitOptions) (bool, error) {
fmt.Println("An ignition path was provided. No SSH connection was added to Podman") fmt.Println("An ignition path was provided. No SSH connection was added to Podman")
} }
// Write the JSON file // Write the JSON file
v.writeConfig() if err := v.writeConfig(); err != nil {
return false, fmt.Errorf("writing JSON file: %w", err)
}
// User has provided ignition file so keygen // User has provided ignition file so keygen
// will be skipped. // will be skipped.
@ -1099,10 +1101,13 @@ func waitAndPingAPI(sock string) {
Transport: &http.Transport{ Transport: &http.Transport{
DialContext: func(context.Context, string, string) (net.Conn, error) { DialContext: func(context.Context, string, string) (net.Conn, error) {
con, err := net.DialTimeout("unix", sock, apiUpTimeout) con, err := net.DialTimeout("unix", sock, apiUpTimeout)
if err == nil { if err != nil {
con.SetDeadline(time.Now().Add(apiUpTimeout)) return nil, err
} }
return con, err if err := con.SetDeadline(time.Now().Add(apiUpTimeout)); err != nil {
return nil, err
}
return con, nil
}, },
}, },
} }

View File

@ -1,6 +1,8 @@
package rootless package rootless
import ( import (
"errors"
"fmt"
"os" "os"
"sort" "sort"
"sync" "sync"
@ -8,7 +10,6 @@ import (
"github.com/containers/storage/pkg/lockfile" "github.com/containers/storage/pkg/lockfile"
"github.com/opencontainers/runc/libcontainer/user" "github.com/opencontainers/runc/libcontainer/user"
spec "github.com/opencontainers/runtime-spec/specs-go" spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
) )
// TryJoinPauseProcess attempts to join the namespaces of the pause PID via // TryJoinPauseProcess attempts to join the namespaces of the pause PID via
@ -16,7 +17,7 @@ import (
// file. // file.
func TryJoinPauseProcess(pausePidPath string) (bool, int, error) { func TryJoinPauseProcess(pausePidPath string) (bool, int, error) {
if _, err := os.Stat(pausePidPath); err != nil { if _, err := os.Stat(pausePidPath); err != nil {
if os.IsNotExist(err) { if errors.Is(err, os.ErrNotExist) {
return false, -1, nil return false, -1, nil
} }
return false, -1, err return false, -1, err
@ -34,7 +35,7 @@ func TryJoinPauseProcess(pausePidPath string) (bool, int, error) {
if os.IsNotExist(err) { if os.IsNotExist(err) {
return false, -1, nil return false, -1, nil
} }
return false, -1, errors.Wrapf(err, "error acquiring lock on %s", pausePidPath) return false, -1, fmt.Errorf("error acquiring lock on %s: %w", pausePidPath, err)
} }
pidFileLock.Lock() pidFileLock.Lock()

View File

@ -9,7 +9,7 @@ import (
func benchmarkParsePortMapping(b *testing.B, ports []types.PortMapping) { func benchmarkParsePortMapping(b *testing.B, ports []types.PortMapping) {
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
ParsePortMapping(ports, nil) _, _ = ParsePortMapping(ports, nil)
} }
} }

View File

@ -362,7 +362,9 @@ func executeContainerTemplate(info *containerInfo, options entities.GenerateSyst
fs.StringArrayP("env", "e", nil, "") fs.StringArrayP("env", "e", nil, "")
fs.String("sdnotify", "", "") fs.String("sdnotify", "", "")
fs.String("restart", "", "") fs.String("restart", "", "")
fs.Parse(remainingCmd) if err := fs.Parse(remainingCmd); err != nil {
return "", fmt.Errorf("parsing remaining command-line arguments: %w", err)
}
remainingCmd = filterCommonContainerFlags(remainingCmd, fs.NArg()) remainingCmd = filterCommonContainerFlags(remainingCmd, fs.NArg())
// If the container is in a pod, make sure that the // If the container is in a pod, make sure that the

View File

@ -335,7 +335,9 @@ func executePodTemplate(info *podInfo, options entities.GenerateSystemdOptions)
fs.SetInterspersed(false) fs.SetInterspersed(false)
fs.String("name", "", "") fs.String("name", "", "")
fs.Bool("replace", false, "") fs.Bool("replace", false, "")
fs.Parse(podCreateArgs) if err := fs.Parse(podCreateArgs); err != nil {
return "", fmt.Errorf("parsing remaining command-line arguments: %w", err)
}
hasNameParam := fs.Lookup("name").Changed hasNameParam := fs.Lookup("name").Changed
hasReplaceParam, err := fs.GetBool("replace") hasReplaceParam, err := fs.GetBool("replace")

View File

@ -1,7 +1,6 @@
package integration package integration
import ( import (
"os"
"syscall" "syscall"
"time" "time"
@ -20,12 +19,11 @@ var _ = Describe("Podman attach", func() {
BeforeEach(func() { BeforeEach(func() {
tempdir, err = CreateTempDirInTempDir() tempdir, err = CreateTempDirInTempDir()
if err != nil { Expect(err).To(BeNil())
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir) podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup() podmanTest.Setup()
podmanTest.SeedImages() err = podmanTest.SeedImages()
Expect(err).To(BeNil())
}) })
AfterEach(func() { AfterEach(func() {

View File

@ -37,12 +37,12 @@ var _ = Describe("Podman checkpoint", func() {
BeforeEach(func() { BeforeEach(func() {
SkipIfRootless("checkpoint not supported in rootless mode") SkipIfRootless("checkpoint not supported in rootless mode")
tempdir, err = CreateTempDirInTempDir() tempdir, err = CreateTempDirInTempDir()
if err != nil { Expect(err).To(BeNil())
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir) podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup() podmanTest.Setup()
podmanTest.SeedImages() err = podmanTest.SeedImages()
Expect(err).To(BeNil())
// Check if the runtime implements checkpointing. Currently only // Check if the runtime implements checkpointing. Currently only
// runc's checkpoint/restore implementation is supported. // runc's checkpoint/restore implementation is supported.
cmd := exec.Command(podmanTest.OCIRuntime, "checkpoint", "--help") cmd := exec.Command(podmanTest.OCIRuntime, "checkpoint", "--help")

View File

@ -21,12 +21,11 @@ var _ = Describe("Podman commit", func() {
BeforeEach(func() { BeforeEach(func() {
tempdir, err = CreateTempDirInTempDir() tempdir, err = CreateTempDirInTempDir()
if err != nil { Expect(err).To(BeNil())
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir) podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup() podmanTest.Setup()
podmanTest.SeedImages() err = podmanTest.SeedImages()
Expect(err).To(BeNil())
}) })
AfterEach(func() { AfterEach(func() {

View File

@ -809,7 +809,8 @@ func (p *PodmanTestIntegration) RestoreArtifactToCache(image string) error {
func populateCache(podman *PodmanTestIntegration) { func populateCache(podman *PodmanTestIntegration) {
for _, image := range CACHE_IMAGES { for _, image := range CACHE_IMAGES {
podman.RestoreArtifactToCache(image) err := podman.RestoreArtifactToCache(image)
Expect(err).To(BeNil())
} }
// logformatter uses this to recognize the first test // logformatter uses this to recognize the first test
fmt.Printf("-----------------------------\n") fmt.Printf("-----------------------------\n")

View File

@ -24,12 +24,11 @@ var _ = Describe("Podman create", func() {
BeforeEach(func() { BeforeEach(func() {
tempdir, err = CreateTempDirInTempDir() tempdir, err = CreateTempDirInTempDir()
if err != nil { Expect(err).To(BeNil())
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir) podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup() podmanTest.Setup()
podmanTest.SeedImages() err = podmanTest.SeedImages()
Expect(err).To(BeNil())
}) })
AfterEach(func() { AfterEach(func() {

View File

@ -51,7 +51,8 @@ var _ = Describe("Common functions test", func() {
txt := fmt.Sprintf("ID=%s\nVERSION_ID=%s", id, ver) txt := fmt.Sprintf("ID=%s\nVERSION_ID=%s", id, ver)
if !empty { if !empty {
f, _ := os.Create(path) f, _ := os.Create(path)
f.WriteString(txt) _, err := f.WriteString(txt)
Expect(err).To(BeNil(), "Failed to write data.")
f.Close() f.Close()
} }
@ -136,7 +137,8 @@ var _ = Describe("Common functions test", func() {
} }
if createFile { if createFile {
f, _ := os.Create(path) f, _ := os.Create(path)
f.WriteString(txt) _, err := f.WriteString(txt)
Expect(err).To(BeNil(), "Failed to write data.")
f.Close() f.Close()
} }
ProcessOneCgroupPath = path ProcessOneCgroupPath = path