enable staticcheck linter

Fix many problems reported by the staticcheck linter, including many
real bugs!

Signed-off-by: Paul Holzinger <pholzing@redhat.com>
This commit is contained in:
Paul Holzinger
2022-04-22 11:51:53 +02:00
parent 56d6ee0808
commit 2a8e435671
26 changed files with 56 additions and 41 deletions

View File

@ -32,7 +32,6 @@ linters:
- predeclared
- thelper
- ifshort
- staticcheck
- forbidigo
- exhaustive
- unparam

View File

@ -877,7 +877,7 @@ install.tools: .install.goimports .install.gitvalidation .install.md2man .instal
.PHONY: .install.golangci-lint
.install.golangci-lint: .gopathok
VERSION=1.45.0 GOBIN=$(GOBIN) ./hack/install_golangci.sh
VERSION=1.45.2 GOBIN=$(GOBIN) ./hack/install_golangci.sh
.PHONY: .install.bats
.install.bats: .gopathok

View File

@ -286,8 +286,6 @@ func CreateInit(c *cobra.Command, vals entities.ContainerCreateOptions, isInfra
if !isInfra && c.Flag("entrypoint").Changed {
val := c.Flag("entrypoint").Value.String()
vals.Entrypoint = &val
} else if isInfra && c.Flag("infra-command").Changed {
}
// Docker-compatibility: the "-h" flag for run/create is reserved for
@ -297,7 +295,7 @@ func CreateInit(c *cobra.Command, vals entities.ContainerCreateOptions, isInfra
}
func PullImage(imageName string, cliVals entities.ContainerCreateOptions) (string, error) {
pullPolicy, err := config.ValidatePullPolicy(cliVals.Pull)
pullPolicy, err := config.ParsePullPolicy(cliVals.Pull)
if err != nil {
return "", err
}
@ -383,7 +381,7 @@ func createPodIfNecessary(cmd *cobra.Command, s *specgen.SpecGenerator, netOpts
podSpec := entities.PodSpec{}
podGen := specgen.NewPodSpecGenerator()
podSpec.PodSpecGen = *podGen
podGen, err = entities.ToPodSpecGen(*&podSpec.PodSpecGen, &createOptions)
podGen, err = entities.ToPodSpecGen(podSpec.PodSpecGen, &createOptions)
if err != nil {
return nil, err
}

View File

@ -37,7 +37,6 @@ func volumeUnmount(cmd *cobra.Command, args []string) error {
return err
}
for _, r := range reports {
var errs utils.OutputErrors
if r.Err == nil {
fmt.Println(r.Id)
} else {

View File

@ -845,7 +845,7 @@ func (c *Container) generateInspectContainerHostConfig(ctrSpec *spec.Spec, named
// Do not include if privileged - assumed that all devices will be
// included.
var err error
hostConfig.Devices, err = c.GetDevices(*&hostConfig.Privileged, *ctrSpec, deviceNodes)
hostConfig.Devices, err = c.GetDevices(hostConfig.Privileged, *ctrSpec, deviceNodes)
if err != nil {
return nil, err
}

View File

@ -399,6 +399,9 @@ func (c *Container) generateSpec(ctx context.Context) (*spec.Spec, error) {
}
}
// NewFromSpec() is deprecated according to its comment
// however the recommended replace just causes a nil map panic
//nolint:staticcheck
g := generate.NewFromSpec(c.config.Spec)
// If network namespace was requested, add it now
@ -1520,6 +1523,10 @@ func (c *Container) checkpoint(ctx context.Context, options ContainerCheckpointO
func (c *Container) generateContainerSpec() error {
// Make sure the newly created config.json exists on disk
// NewFromSpec() is deprecated according to its comment
// however the recommended replace just causes a nil map panic
//nolint:staticcheck
g := generate.NewFromSpec(c.config.Spec)
if err := c.saveSpec(g.Config); err != nil {

View File

@ -56,7 +56,7 @@ func (c *Container) startTimer() error {
return errors.Wrapf(err, "unable to get systemd connection to start healthchecks")
}
defer conn.Close()
_, err = conn.StartUnit(fmt.Sprintf("%s.service", c.ID()), "fail", nil)
_, err = conn.StartUnitContext(context.Background(), fmt.Sprintf("%s.service", c.ID()), "fail", nil)
return err
}

View File

@ -936,6 +936,9 @@ func WithUserNSFrom(nsCtr *Container) CtrCreateOption {
if err := JSONDeepCopy(nsCtr.IDMappings(), &ctr.config.IDMappings); err != nil {
return err
}
// NewFromSpec() is deprecated according to its comment
// however the recommended replace just causes a nil map panic
//nolint:staticcheck
g := generate.NewFromSpec(ctr.config.Spec)
g.ClearLinuxUIDMappings()

View File

@ -397,6 +397,10 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (_ *Contai
if ctr.restoreFromCheckpoint {
// Remove information about bind mount
// for new container from imported checkpoint
// NewFromSpec() is deprecated according to its comment
// however the recommended replace just causes a nil map panic
//nolint:staticcheck
g := generate.NewFromSpec(ctr.config.Spec)
g.RemoveMount("/dev/shm")
ctr.config.ShmDir = ""

View File

@ -100,10 +100,10 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) {
// gather all images for manifest list
var images []string
if len(query.Images) > 0 {
images = append(query.Images)
images = query.Images
}
if len(body.Images) > 0 {
images = append(body.Images)
images = body.Images
}
id, err := imageEngine.ManifestAdd(r.Context(), query.Name, images, body.ManifestAddOptions)

View File

@ -167,6 +167,7 @@ func (s *APIServer) registerManifestHandlers(r *mux.Router) error {
// $ref: "#/responses/BadParamError"
// 500:
// $ref: "#/responses/InternalError"
//lint:ignore SA1019 We still want to support the V3 endpoints
v3.Handle("/{name:.*}/add", s.APIHandler(libpod.ManifestAdd)).Methods(http.MethodPost)
// swagger:operation DELETE /libpod/manifests/{name} manifests ManifestDeleteV3Libpod
// ---
@ -197,6 +198,7 @@ func (s *APIServer) registerManifestHandlers(r *mux.Router) error {
// $ref: "#/responses/NoSuchManifest"
// 500:
// $ref: "#/responses/InternalError"
//lint:ignore SA1019 We still want to support the V3 endpoints
v3.Handle("/{name:.*}", s.APIHandler(libpod.ManifestRemoveDigest)).Methods(http.MethodDelete)
// swagger:operation DELETE /libpod/manifests/{name} manifests ManifestDeleteLibpod
// ---
@ -255,6 +257,7 @@ func (s *APIServer) registerManifestHandlers(r *mux.Router) error {
// $ref: "#/responses/NoSuchManifest"
// 500:
// $ref: "#/responses/InternalError"
//lint:ignore SA1019 We still want to support the V3 endpoints
v3.Handle("/{name}/push", s.APIHandler(libpod.ManifestPushV3)).Methods(http.MethodPost)
// swagger:operation POST /libpod/manifests/{name}/registry/{destination} manifests ManifestPushLibpod
// ---

View File

@ -103,7 +103,7 @@ var _ = Describe("Podman images", func() {
Expect(len(errs)).To(BeZero())
Expect(inspectData.ID).To(Equal(response.Deleted[0]))
inspectData, err = images.GetImage(bt.conn, busybox.shortName, nil)
_, err = images.GetImage(bt.conn, busybox.shortName, nil)
code, _ := bindings.CheckResponseCode(err)
Expect(code).To(BeNumerically("==", http.StatusNotFound))
@ -118,7 +118,7 @@ var _ = Describe("Podman images", func() {
// try to remove the image "alpine". This should fail since we are not force
// deleting hence image cannot be deleted until the container is deleted.
response, errs = images.Remove(bt.conn, []string{alpine.shortName}, nil)
_, errs = images.Remove(bt.conn, []string{alpine.shortName}, nil)
code, _ = bindings.CheckResponseCode(errs[0])
// FIXME FIXME FIXME: #12441: another invalid error
// FIXME FIXME FIXME: this time msg="Image used by SHA: ..."
@ -126,7 +126,7 @@ var _ = Describe("Podman images", func() {
// Removing the image "alpine" where force = true
options := new(images.RemoveOptions).WithForce(true)
response, errs = images.Remove(bt.conn, []string{alpine.shortName}, options)
_, errs = images.Remove(bt.conn, []string{alpine.shortName}, options)
Expect(errs).To(Or(HaveLen(0), BeNil()))
// To be extra sure, check if the previously created container
// is gone as well.
@ -135,11 +135,11 @@ var _ = Describe("Podman images", func() {
Expect(code).To(BeNumerically("==", http.StatusNotFound))
// Now make sure both images are gone.
inspectData, err = images.GetImage(bt.conn, busybox.shortName, nil)
_, err = images.GetImage(bt.conn, busybox.shortName, nil)
code, _ = bindings.CheckResponseCode(err)
Expect(code).To(BeNumerically("==", http.StatusNotFound))
inspectData, err = images.GetImage(bt.conn, alpine.shortName, nil)
_, err = images.GetImage(bt.conn, alpine.shortName, nil)
code, _ = bindings.CheckResponseCode(err)
Expect(code).To(BeNumerically("==", http.StatusNotFound))
})
@ -230,8 +230,8 @@ var _ = Describe("Podman images", func() {
Expect(err).ToNot(HaveOccurred())
Expect(exists).To(BeFalse())
f, err := os.Open(filepath.Join(ImageCacheDir, alpine.tarballName))
defer f.Close()
Expect(err).ToNot(HaveOccurred())
defer f.Close()
names, err := images.Load(bt.conn, f)
Expect(err).ToNot(HaveOccurred())
Expect(names.Names[0]).To(Equal(alpine.name))
@ -252,8 +252,6 @@ var _ = Describe("Podman images", func() {
Expect(names.Names[0]).To(Equal(alpine.name))
// load with a bad repo name should trigger a 500
f, err = os.Open(filepath.Join(ImageCacheDir, alpine.tarballName))
Expect(err).ToNot(HaveOccurred())
_, errs = images.Remove(bt.conn, []string{alpine.name}, nil)
Expect(len(errs)).To(BeZero())
exists, err = images.Exists(bt.conn, alpine.name, nil)
@ -265,8 +263,8 @@ var _ = Describe("Podman images", func() {
// Export an image
exportPath := filepath.Join(bt.tempDirPath, alpine.tarballName)
w, err := os.Create(filepath.Join(bt.tempDirPath, alpine.tarballName))
defer w.Close()
Expect(err).ToNot(HaveOccurred())
defer w.Close()
err = images.Export(bt.conn, []string{alpine.name}, w, nil)
Expect(err).ToNot(HaveOccurred())
_, err = os.Stat(exportPath)
@ -283,8 +281,8 @@ var _ = Describe("Podman images", func() {
Expect(err).ToNot(HaveOccurred())
Expect(exists).To(BeFalse())
f, err := os.Open(filepath.Join(ImageCacheDir, alpine.tarballName))
defer f.Close()
Expect(err).ToNot(HaveOccurred())
defer f.Close()
changes := []string{"CMD /bin/foobar"}
testMessage := "test_import"
options := new(images.ImportOptions).WithMessage(testMessage).WithChanges(changes).WithReference(alpine.name)

View File

@ -64,7 +64,7 @@ var _ = Describe("Podman secrets", func() {
Expect(data.Spec.Name).To(Equal(name))
// inspecting non-existent secret should fail
data, err = secrets.Inspect(connText, "notasecret", nil)
_, err = secrets.Inspect(connText, "notasecret", nil)
code, _ := bindings.CheckResponseCode(err)
Expect(code).To(BeNumerically("==", http.StatusNotFound))
})

View File

@ -42,14 +42,14 @@ func (ic *ContainerEngine) PodKill(ctx context.Context, namesOrIds []string, opt
return reports, nil
}
func (ic *ContainerEngine) PodLogs(_ context.Context, nameOrIDs string, options entities.PodLogsOptions) error {
func (ic *ContainerEngine) PodLogs(ctx context.Context, nameOrIDs string, options entities.PodLogsOptions) error {
// PodLogsOptions are similar but contains few extra fields like ctrName
// So cast other values as is so we can re-use the code
containerLogsOpts := entities.PodLogsOptionsToContainerLogsOptions(options)
// interface only accepts slice, keep everything consistent
name := []string{options.ContainerName}
return ic.ContainerLogs(nil, name, containerLogsOpts)
return ic.ContainerLogs(ctx, name, containerLogsOpts)
}
func (ic *ContainerEngine) PodPause(ctx context.Context, namesOrIds []string, options entities.PodPauseOptions) ([]*entities.PodPauseReport, error) {

View File

@ -139,7 +139,7 @@ func getStreamURL(streamType string) url2.URL {
// This should get Exported and stay put as it will apply to all fcos downloads
// getFCOS parses fedoraCoreOS's stream and returns the image download URL and the release version
func getFCOSDownload(imageStream string) (*fcosDownloadInfo, error) {
func getFCOSDownload(imageStream string) (*fcosDownloadInfo, error) { // nolint:staticcheck
var (
fcosstable stream.Stream
altMeta release.Release
@ -149,6 +149,8 @@ func getFCOSDownload(imageStream string) (*fcosDownloadInfo, error) {
// This is being hard set to testing. Once podman4 is in the
// fcos trees, we should remove it and re-release at least on
// macs.
// TODO: remove when podman4.0 is in coreos
// nolint:staticcheck
imageStream = "podman-testing"
switch imageStream {

View File

@ -82,7 +82,7 @@ func ToPodOpt(ctx context.Context, podName string, p entities.PodCreateOptions,
}
// dns options
if options := dnsConfig.Options; len(options) > 0 {
dnsOptions := make([]string, 0)
dnsOptions := make([]string, 0, len(options))
for _, opts := range options {
d := opts.Name
if opts.Value != nil {
@ -90,6 +90,7 @@ func ToPodOpt(ctx context.Context, podName string, p entities.PodCreateOptions,
}
dnsOptions = append(dnsOptions, d)
}
p.Net.DNSOptions = dnsOptions
}
}
return p, nil
@ -281,9 +282,6 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
annotations = opts.Annotations
}
if opts.PodInfraID != "" {
if annotations == nil {
}
annotations[ann.SandboxID] = opts.PodInfraID
annotations[ann.ContainerType] = ann.ContainerTypeContainer
}

View File

@ -1,6 +1,7 @@
package systemd
import (
"context"
"fmt"
"os"
"path/filepath"
@ -140,5 +141,5 @@ func ConnectToDBUS() (*dbus.Conn, error) {
if rootless.IsRootless() {
return newRootlessConnection()
}
return dbus.NewSystemdConnection()
return dbus.NewSystemdConnectionContext(context.Background())
}

View File

@ -1061,7 +1061,7 @@ var _ = Describe("Podman checkpoint", func() {
// Open a network connection to the redis server via initial port mapping
// This should fail
conn, err = net.DialTimeout("tcp4", fmt.Sprintf("localhost:%d", randomPort), time.Duration(3)*time.Second)
_, err = net.DialTimeout("tcp4", fmt.Sprintf("localhost:%d", randomPort), time.Duration(3)*time.Second)
Expect(err).ToNot(BeNil())
Expect(err.Error()).To(ContainSubstring("connection refused"))
// Open a network connection to the redis server via new port mapping

View File

@ -880,11 +880,11 @@ func (p *PodmanTestIntegration) makeOptions(args []string, noEvents, noCache boo
func writeConf(conf []byte, confPath string) {
if _, err := os.Stat(filepath.Dir(confPath)); os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(confPath), 777); err != nil {
if err := os.MkdirAll(filepath.Dir(confPath), 0o777); err != nil {
fmt.Println(err)
}
}
if err := ioutil.WriteFile(confPath, conf, 777); err != nil {
if err := ioutil.WriteFile(confPath, conf, 0o777); err != nil {
fmt.Println(err)
}
}

View File

@ -188,6 +188,8 @@ var _ = Describe("Podman login and logout", func() {
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"logout", "--authfile", authFile, server})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman login and logout with --tls-verify", func() {

View File

@ -220,6 +220,7 @@ var _ = Describe("Podman push", func() {
if setup.LineInOutputContains("Active: inactive") {
setup = SystemExec("systemctl", []string{"start", "docker"})
Expect(setup).Should(Exit(0))
defer func() {
stop := SystemExec("systemctl", []string{"stop", "docker"})
Expect(stop).Should(Exit(0))

View File

@ -97,7 +97,7 @@ var _ = Describe("Systemd activate", func() {
// Emulate 'systemd stop podman.service'
activateSession.Signal(syscall.SIGTERM)
time.Sleep(2)
time.Sleep(100 * time.Millisecond)
Eventually(activateSession).Should(Exit(0))
abiSession := podman("inspect", "--format={{.State.Running}}", containerName)

View File

@ -110,9 +110,8 @@ var _ = Describe("Common functions test", func() {
Expect(err).To(BeNil(), "Failed to write JSON to file.")
read, err := os.Open("/tmp/testJSON")
defer read.Close()
Expect(err).To(BeNil(), "Can not find the JSON file after we write it.")
defer read.Close()
bytes, _ := ioutil.ReadAll(read)
json.Unmarshal(bytes, compareData)

View File

@ -439,10 +439,10 @@ func tagOutputToMap(imagesOutput []string) map[string]map[string]bool {
// GetHostDistributionInfo returns a struct with its distribution Name and version
func GetHostDistributionInfo() HostOS {
f, err := os.Open(OSReleasePath)
defer f.Close()
if err != nil {
return HostOS{}
}
defer f.Close()
l := bufio.NewScanner(f)
host := HostOS{}

View File

@ -7,5 +7,5 @@ import (
)
func main() {
fmt.Printf(version.Version.String())
fmt.Print(version.Version.String())
}

View File

@ -6,6 +6,7 @@ package utils
import (
"bufio"
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
@ -32,7 +33,7 @@ func RunUnderSystemdScope(pid int, slice string, unitName string) error {
return err
}
} else {
conn, err = systemdDbus.New()
conn, err = systemdDbus.NewWithContext(context.Background())
if err != nil {
return err
}
@ -43,10 +44,10 @@ func RunUnderSystemdScope(pid int, slice string, unitName string) error {
properties = append(properties, newProp("Delegate", true))
properties = append(properties, newProp("DefaultDependencies", false))
ch := make(chan string)
_, err = conn.StartTransientUnit(unitName, "replace", properties, ch)
_, err = conn.StartTransientUnitContext(context.Background(), unitName, "replace", properties, ch)
if err != nil {
// On errors check if the cgroup already exists, if it does move the process there
if props, err := conn.GetUnitTypeProperties(unitName, "Scope"); err == nil {
if props, err := conn.GetUnitTypePropertiesContext(context.Background(), unitName, "Scope"); err == nil {
if cgroup, ok := props["ControlGroup"].(string); ok && cgroup != "" {
if err := moveUnderCgroup(cgroup, "", []uint32{uint32(pid)}); err == nil {
return nil