diff options
Diffstat (limited to 'pkg')
41 files changed, 196 insertions, 209 deletions
diff --git a/pkg/api/handlers/compat/containers.go b/pkg/api/handlers/compat/containers.go index 4830ef4b7..1c339730e 100644 --- a/pkg/api/handlers/compat/containers.go +++ b/pkg/api/handlers/compat/containers.go @@ -293,9 +293,10 @@ func LibpodToContainer(l *libpod.Container, sz bool) (*handlers.Container, error stateStr = "created" } - if state == define.ContainerStateConfigured || state == define.ContainerStateCreated { + switch state { + case define.ContainerStateConfigured, define.ContainerStateCreated: status = "Created" - } else if state == define.ContainerStateStopped || state == define.ContainerStateExited { + case define.ContainerStateStopped, define.ContainerStateExited: exitCode, _, err := l.ExitCode() if err != nil { return nil, err @@ -305,7 +306,7 @@ func LibpodToContainer(l *libpod.Container, sz bool) (*handlers.Container, error return nil, err } status = fmt.Sprintf("Exited (%d) %s ago", exitCode, units.HumanDuration(time.Since(finishedTime))) - } else if state == define.ContainerStateRunning || state == define.ContainerStatePaused { + case define.ContainerStateRunning, define.ContainerStatePaused: startedTime, err := l.StartedTime() if err != nil { return nil, err @@ -314,11 +315,11 @@ func LibpodToContainer(l *libpod.Container, sz bool) (*handlers.Container, error if state == define.ContainerStatePaused { status += " (Paused)" } - } else if state == define.ContainerStateRemoving { + case define.ContainerStateRemoving: status = "Removal In Progress" - } else if state == define.ContainerStateStopping { + case define.ContainerStateStopping: status = "Stopping" - } else { + default: status = "Unknown" } diff --git a/pkg/api/handlers/compat/images.go b/pkg/api/handlers/compat/images.go index edefce010..a690cdd40 100644 --- a/pkg/api/handlers/compat/images.go +++ b/pkg/api/handlers/compat/images.go @@ -532,7 +532,7 @@ func ExportImages(w http.ResponseWriter, r *http.Request) { utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String())) return } - if len(query.Names) <= 0 { + if len(query.Names) == 0 { utils.Error(w, http.StatusBadRequest, fmt.Errorf("no images to download")) return } diff --git a/pkg/api/handlers/compat/images_build.go b/pkg/api/handlers/compat/images_build.go index 1a24f1ae3..0f85aa717 100644 --- a/pkg/api/handlers/compat/images_build.go +++ b/pkg/api/handlers/compat/images_build.go @@ -286,7 +286,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) { } } } - secrets = append(secrets, strings.Join(modifiedOpt[:], ",")) + secrets = append(secrets, strings.Join(modifiedOpt, ",")) } } } diff --git a/pkg/api/handlers/compat/images_prune.go b/pkg/api/handlers/compat/images_prune.go index c0be9da7d..46524fcff 100644 --- a/pkg/api/handlers/compat/images_prune.go +++ b/pkg/api/handlers/compat/images_prune.go @@ -58,7 +58,7 @@ func PruneImages(w http.ResponseWriter, r *http.Request) { idr = append(idr, types.ImageDeleteResponseItem{ Deleted: p.Id, }) - reclaimedSpace = reclaimedSpace + p.Size + reclaimedSpace += p.Size } if errorMsg.Len() > 0 { utils.InternalServerError(w, errors.New(errorMsg.String())) diff --git a/pkg/api/handlers/utils/handler.go b/pkg/api/handlers/utils/handler.go index a9b6f0659..338d5a84b 100644 --- a/pkg/api/handlers/utils/handler.go +++ b/pkg/api/handlers/utils/handler.go @@ -150,7 +150,7 @@ func MarshalErrorJSONIsEmpty(ptr unsafe.Pointer) bool { } func MarshalErrorSliceJSONIsEmpty(ptr unsafe.Pointer) bool { - return len(*((*[]error)(ptr))) <= 0 + return len(*((*[]error)(ptr))) == 0 } // WriteJSON writes an interface value encoded as JSON to w diff --git a/pkg/bindings/images/build.go b/pkg/bindings/images/build.go index 1729bd922..9e0a0d798 100644 --- a/pkg/bindings/images/build.go +++ b/pkg/bindings/images/build.go @@ -225,10 +225,8 @@ func Build(ctx context.Context, containerFiles []string, options entities.BuildO platform = "linux" } platform += "/" + options.Architecture - } else { - if len(platform) > 0 { - platform += "/" + runtime.GOARCH - } + } else if len(platform) > 0 { + platform += "/" + runtime.GOARCH } if len(platform) > 0 { params.Set("platform", platform) @@ -447,7 +445,7 @@ func Build(ctx context.Context, containerFiles []string, options entities.BuildO } } } - secretsForRemote = append(secretsForRemote, strings.Join(modifiedOpt[:], ",")) + secretsForRemote = append(secretsForRemote, strings.Join(modifiedOpt, ",")) } } @@ -603,8 +601,8 @@ func nTar(excludes []string, sources ...string) (io.ReadCloser, error) { // are required to visit all files. :( return nil } - - if d.Type().IsRegular() { // add file item + switch { + case d.Type().IsRegular(): // add file item info, err := d.Info() if err != nil { return err @@ -644,7 +642,7 @@ func nTar(excludes []string, sources ...string) (io.ReadCloser, error) { seen[di] = name } return err - } else if d.IsDir() { // add folders + case d.IsDir(): // add folders info, err := d.Info() if err != nil { return err @@ -658,7 +656,7 @@ func nTar(excludes []string, sources ...string) (io.ReadCloser, error) { if lerr := tw.WriteHeader(hdr); lerr != nil { return lerr } - } else if d.Type()&os.ModeSymlink != 0 { // add symlinks as it, not content + case d.Type()&os.ModeSymlink != 0: // add symlinks as it, not content link, err := os.Readlink(path) if err != nil { return err diff --git a/pkg/bindings/images/types.go b/pkg/bindings/images/types.go index 75cb38a0a..8e5e7ee92 100644 --- a/pkg/bindings/images/types.go +++ b/pkg/bindings/images/types.go @@ -177,7 +177,7 @@ type PullOptions struct { Variant *string } -//BuildOptions are optional options for building images +// BuildOptions are optional options for building images type BuildOptions struct { buildahDefine.BuildOptions } diff --git a/pkg/bindings/network/network.go b/pkg/bindings/network/network.go index 6c7777fdd..83641f677 100644 --- a/pkg/bindings/network/network.go +++ b/pkg/bindings/network/network.go @@ -101,7 +101,7 @@ func List(ctx context.Context, options *ListOptions) ([]types.Network, error) { } // Disconnect removes a container from a given network -func Disconnect(ctx context.Context, networkName string, ContainerNameOrID string, options *DisconnectOptions) error { +func Disconnect(ctx context.Context, networkName string, containerNameOrID string, options *DisconnectOptions) error { if options == nil { options = new(DisconnectOptions) } @@ -114,7 +114,7 @@ func Disconnect(ctx context.Context, networkName string, ContainerNameOrID strin Container string Force bool }{ - Container: ContainerNameOrID, + Container: containerNameOrID, } if force := options.GetForce(); options.Changed("Force") { disconnect.Force = force diff --git a/pkg/bindings/test/containers_test.go b/pkg/bindings/test/containers_test.go index bf627fdba..090dd294c 100644 --- a/pkg/bindings/test/containers_test.go +++ b/pkg/bindings/test/containers_test.go @@ -104,9 +104,9 @@ var _ = Describe("Podman containers ", func() { // Pause by name err = containers.Pause(bt.conn, name, nil) Expect(err).To(BeNil(), "error from containers.Pause()") - //paused := "paused" - //_, err = containers.Wait(bt.conn, cid, &paused) - //Expect(err).To(BeNil()) + // paused := "paused" + // _, err = containers.Wait(bt.conn, cid, &paused) + // Expect(err).To(BeNil()) err = containers.Unpause(bt.conn, name, nil) Expect(err).To(BeNil()) @@ -332,8 +332,8 @@ var _ = Describe("Podman containers ", func() { // TODO for the life of me, i cannot get this to work. maybe another set // of eyes will // successful healthcheck - //status := define.HealthCheckHealthy - //for i:=0; i < 10; i++ { + // status := define.HealthCheckHealthy + // for i:=0; i < 10; i++ { // result, err := containers.RunHealthCheck(connText, "hc") // Expect(err).To(BeNil()) // if result.Status != define.HealthCheckHealthy { @@ -343,18 +343,18 @@ var _ = Describe("Podman containers ", func() { // } // status = result.Status // break - //} - //Expect(status).To(Equal(define.HealthCheckHealthy)) + // } + // Expect(status).To(Equal(define.HealthCheckHealthy)) // TODO enable this when wait is working // healthcheck on a stopped container should be a 409 - //err = containers.Stop(connText, "hc", nil) - //Expect(err).To(BeNil()) - //_, err = containers.Wait(connText, "hc") - //Expect(err).To(BeNil()) - //_, err = containers.RunHealthCheck(connText, "hc") - //code, _ = bindings.CheckResponseCode(err) - //Expect(code).To(BeNumerically("==", http.StatusConflict)) + // err = containers.Stop(connText, "hc", nil) + // Expect(err).To(BeNil()) + // _, err = containers.Wait(connText, "hc") + // Expect(err).To(BeNil()) + // _, err = containers.RunHealthCheck(connText, "hc") + // code, _ = bindings.CheckResponseCode(err) + // Expect(code).To(BeNumerically("==", http.StatusConflict)) }) It("logging", func() { @@ -490,7 +490,7 @@ var _ = Describe("Podman containers ", func() { }) It("podman kill a running container by bogus signal", func() { - //Killing a running container by bogus signal should fail + // Killing a running container by bogus signal should fail var name = "top" cid, err := bt.RunTopContainer(&name, nil) Expect(err).To(BeNil()) @@ -580,7 +580,7 @@ var _ = Describe("Podman containers ", func() { // Valid filter params container should be pruned now. filters := map[string][]string{ - "until": {"5000000000"}, //Friday, June 11, 2128 + "until": {"5000000000"}, // Friday, June 11, 2128 } pruneResponse, err = containers.Prune(bt.conn, new(containers.PruneOptions).WithFilters(filters)) Expect(err).To(BeNil()) @@ -594,7 +594,7 @@ var _ = Describe("Podman containers ", func() { Expect(err).To(BeNil()) filters := map[string][]string{ - "until": {"5000000000"}, //Friday, June 11, 2128 + "until": {"5000000000"}, // Friday, June 11, 2128 } c, err := containers.List(bt.conn, new(containers.ListOptions).WithFilters(filters).WithAll(true)) Expect(err).To(BeNil()) diff --git a/pkg/bindings/test/pods_test.go b/pkg/bindings/test/pods_test.go index 1c93c5595..d47e9ee0e 100644 --- a/pkg/bindings/test/pods_test.go +++ b/pkg/bindings/test/pods_test.go @@ -43,13 +43,13 @@ var _ = Describe("Podman pods", func() { }) It("inspect pod", func() { - //Inspect an invalid pod name + // Inspect an invalid pod name _, err := pods.Inspect(bt.conn, "dummyname", nil) Expect(err).ToNot(BeNil()) code, _ := bindings.CheckResponseCode(err) Expect(code).To(BeNumerically("==", http.StatusNotFound)) - //Inspect an valid pod name + // Inspect an valid pod name response, err := pods.Inspect(bt.conn, newpod, nil) Expect(err).To(BeNil()) Expect(response.Name).To(Equal(newpod)) @@ -57,7 +57,7 @@ var _ = Describe("Podman pods", func() { // Test validates the list all api returns It("list pod", func() { - //List all the pods in the current instance + // List all the pods in the current instance podSummary, err := pods.List(bt.conn, nil) Expect(err).To(BeNil()) Expect(len(podSummary)).To(Equal(1)) diff --git a/pkg/bindings/test/volumes_test.go b/pkg/bindings/test/volumes_test.go index c0d01439b..8ae93eed9 100644 --- a/pkg/bindings/test/volumes_test.go +++ b/pkg/bindings/test/volumes_test.go @@ -18,9 +18,6 @@ import ( var _ = Describe("Podman volumes", func() { var ( - //tempdir string - //err error - //podmanTest *PodmanTestIntegration bt *bindingTest s *gexec.Session connText context.Context @@ -28,13 +25,6 @@ var _ = Describe("Podman volumes", func() { ) BeforeEach(func() { - //tempdir, err = CreateTempDirInTempDir() - //if err != nil { - // os.Exit(1) - //} - //podmanTest = PodmanTestCreate(tempdir) - //podmanTest.Setup() - //podmanTest.SeedImages() bt = newBindingTest() bt.RestoreImagesFromCache() s = bt.startAPIService() @@ -44,9 +34,6 @@ var _ = Describe("Podman volumes", func() { }) AfterEach(func() { - //podmanTest.Cleanup() - //f := CurrentGinkgoTestDescription() - //processTestResult(f) s.Kill() bt.cleanup() }) diff --git a/pkg/domain/entities/containers.go b/pkg/domain/entities/containers.go index ae60e5b96..1db8b9951 100644 --- a/pkg/domain/entities/containers.go +++ b/pkg/domain/entities/containers.go @@ -385,7 +385,7 @@ type ContainerInitReport struct { Id string //nolint } -//ContainerMountOptions describes the input values for mounting containers +// ContainerMountOptions describes the input values for mounting containers // in the CLI type ContainerMountOptions struct { All bool diff --git a/pkg/domain/entities/network.go b/pkg/domain/entities/network.go index 134ad126a..0f901c7f1 100644 --- a/pkg/domain/entities/network.go +++ b/pkg/domain/entities/network.go @@ -33,7 +33,7 @@ type NetworkRmOptions struct { Timeout *uint } -//NetworkRmReport describes the results of network removal +// NetworkRmReport describes the results of network removal type NetworkRmReport struct { Name string Err error diff --git a/pkg/domain/entities/reports/prune.go b/pkg/domain/entities/reports/prune.go index 219e35b67..497e5d606 100644 --- a/pkg/domain/entities/reports/prune.go +++ b/pkg/domain/entities/reports/prune.go @@ -34,7 +34,7 @@ func PruneReportsSize(r []*PruneReport) uint64 { if v == nil { continue } - size = size + v.Size + size += v.Size } return size } diff --git a/pkg/domain/infra/abi/images.go b/pkg/domain/infra/abi/images.go index 74478b26d..c3ec7dd8a 100644 --- a/pkg/domain/infra/abi/images.go +++ b/pkg/domain/infra/abi/images.go @@ -785,12 +785,19 @@ func transferRootless(source entities.ImageScpOptions, dest entities.ImageScpOpt return cmdLoad.Run() } -// TransferRootful creates new podman processes using exec.Command and a new uid/gid alongside a cleared environment +// transferRootful creates new podman processes using exec.Command and a new uid/gid alongside a cleared environment func transferRootful(source entities.ImageScpOptions, dest entities.ImageScpOptions, podman string, parentFlags []string) error { - basicCommand := []string{podman} + basicCommand := make([]string, 0, len(parentFlags)+1) + basicCommand = append(basicCommand, podman) basicCommand = append(basicCommand, parentFlags...) - saveCommand := append(basicCommand, "save") - loadCommand := append(basicCommand, "load") + + saveCommand := make([]string, 0, len(basicCommand)+4) + saveCommand = append(saveCommand, basicCommand...) + saveCommand = append(saveCommand, "save") + + loadCommand := make([]string, 0, len(basicCommand)+3) + loadCommand = append(loadCommand, basicCommand...) + loadCommand = append(loadCommand, "load") if source.Quiet { saveCommand = append(saveCommand, "-q") loadCommand = append(loadCommand, "-q") diff --git a/pkg/domain/infra/abi/play.go b/pkg/domain/infra/abi/play.go index c5c31c488..0da07bab8 100644 --- a/pkg/domain/infra/abi/play.go +++ b/pkg/domain/infra/abi/play.go @@ -203,18 +203,20 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY return nil, err } - ns, networks, netOpts, err := specgen.ParseNetworkFlag(options.Networks) - if err != nil { - return nil, err - } + if len(options.Networks) > 0 { + ns, networks, netOpts, err := specgen.ParseNetworkFlag(options.Networks) + if err != nil { + return nil, err + } - if (ns.IsBridge() && len(networks) == 0) || ns.IsHost() { - return nil, errors.Errorf("invalid value passed to --network: bridge or host networking must be configured in YAML") - } + if (ns.IsBridge() && len(networks) == 0) || ns.IsHost() { + return nil, errors.Errorf("invalid value passed to --network: bridge or host networking must be configured in YAML") + } - podOpt.Net.Network = ns - podOpt.Net.Networks = networks - podOpt.Net.NetworkOptions = netOpts + podOpt.Net.Network = ns + podOpt.Net.Networks = networks + podOpt.Net.NetworkOptions = netOpts + } // FIXME This is very hard to support properly with a good ux if len(options.StaticIPs) > *ipIndex { @@ -439,53 +441,51 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY initContainers = append(initContainers, ctr) } for _, container := range podYAML.Spec.Containers { - if !strings.Contains("infra", container.Name) { - // Error out if the same name is used for more than one container - if _, ok := ctrNames[container.Name]; ok { - return nil, errors.Errorf("the pod %q is invalid; duplicate container name %q detected", podName, container.Name) - } - ctrNames[container.Name] = "" - pulledImage, labels, err := ic.getImageAndLabelInfo(ctx, cwd, annotations, writer, container, options) - if err != nil { - return nil, err - } + // Error out if the same name is used for more than one container + if _, ok := ctrNames[container.Name]; ok { + return nil, errors.Errorf("the pod %q is invalid; duplicate container name %q detected", podName, container.Name) + } + ctrNames[container.Name] = "" + pulledImage, labels, err := ic.getImageAndLabelInfo(ctx, cwd, annotations, writer, container, options) + if err != nil { + return nil, err + } - for k, v := range podSpec.PodSpecGen.Labels { // add podYAML labels - labels[k] = v - } + for k, v := range podSpec.PodSpecGen.Labels { // add podYAML labels + labels[k] = v + } - specgenOpts := kube.CtrSpecGenOptions{ - Annotations: annotations, - Container: container, - Image: pulledImage, - Volumes: volumes, - PodID: pod.ID(), - PodName: podName, - PodInfraID: podInfraID, - ConfigMaps: configMaps, - SeccompPaths: seccompPaths, - RestartPolicy: ctrRestartPolicy, - NetNSIsHost: p.NetNS.IsHost(), - SecretsManager: secretsManager, - LogDriver: options.LogDriver, - LogOptions: options.LogOptions, - Labels: labels, - } - specGen, err := kube.ToSpecGen(ctx, &specgenOpts) - if err != nil { - return nil, err - } - specGen.RawImageName = container.Image - rtSpec, spec, opts, err := generate.MakeContainer(ctx, ic.Libpod, specGen, false, nil) - if err != nil { - return nil, err - } - ctr, err := generate.ExecuteCreate(ctx, ic.Libpod, rtSpec, spec, false, opts...) - if err != nil { - return nil, err - } - containers = append(containers, ctr) + specgenOpts := kube.CtrSpecGenOptions{ + Annotations: annotations, + Container: container, + Image: pulledImage, + Volumes: volumes, + PodID: pod.ID(), + PodName: podName, + PodInfraID: podInfraID, + ConfigMaps: configMaps, + SeccompPaths: seccompPaths, + RestartPolicy: ctrRestartPolicy, + NetNSIsHost: p.NetNS.IsHost(), + SecretsManager: secretsManager, + LogDriver: options.LogDriver, + LogOptions: options.LogOptions, + Labels: labels, + } + specGen, err := kube.ToSpecGen(ctx, &specgenOpts) + if err != nil { + return nil, err + } + specGen.RawImageName = container.Image + rtSpec, spec, opts, err := generate.MakeContainer(ctx, ic.Libpod, specGen, false, nil) + if err != nil { + return nil, err + } + ctr, err := generate.ExecuteCreate(ctx, ic.Libpod, rtSpec, spec, false, opts...) + if err != nil { + return nil, err } + containers = append(containers, ctr) } if options.Start != types.OptionalBoolFalse { @@ -774,7 +774,7 @@ func getBuildFile(imageName string, cwd string) (string, error) { logrus.Error(err.Error()) } - _, err = os.Stat(filepath.Join(dockerfilePath)) + _, err = os.Stat(dockerfilePath) if err == nil { logrus.Debugf("Building %s with %s", imageName, dockerfilePath) return dockerfilePath, nil diff --git a/pkg/domain/infra/abi/system.go b/pkg/domain/infra/abi/system.go index 4361821d5..8e96e4154 100644 --- a/pkg/domain/infra/abi/system.go +++ b/pkg/domain/infra/abi/system.go @@ -150,7 +150,7 @@ func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.Sys if err != nil { return nil, err } - reclaimedSpace = reclaimedSpace + reports.PruneReportsSize(containerPruneReports) + reclaimedSpace += reports.PruneReportsSize(containerPruneReports) systemPruneReport.ContainerPruneReports = append(systemPruneReport.ContainerPruneReports, containerPruneReports...) imagePruneOptions := entities.ImagePruneOptions{ All: options.All, @@ -158,7 +158,7 @@ func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.Sys } imageEngine := ImageEngine{Libpod: ic.Libpod} imagePruneReports, err := imageEngine.Prune(ctx, imagePruneOptions) - reclaimedSpace = reclaimedSpace + reports.PruneReportsSize(imagePruneReports) + reclaimedSpace += reports.PruneReportsSize(imagePruneReports) if err != nil { return nil, err @@ -178,7 +178,7 @@ func (ic *ContainerEngine) SystemPrune(ctx context.Context, options entities.Sys if len(volumePruneReport) > 0 { found = true } - reclaimedSpace = reclaimedSpace + reports.PruneReportsSize(volumePruneReport) + reclaimedSpace += reports.PruneReportsSize(volumePruneReport) systemPruneReport.VolumePruneReports = append(systemPruneReport.VolumePruneReports, volumePruneReport...) } } diff --git a/pkg/domain/infra/abi/trust.go b/pkg/domain/infra/abi/trust.go index d53fe16d1..58f099bb6 100644 --- a/pkg/domain/infra/abi/trust.go +++ b/pkg/domain/infra/abi/trust.go @@ -142,15 +142,15 @@ func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistri Type: trustTypeDescription(repoval[0].Type), } // TODO - keyarr is not used and I don't know its intent; commenting out for now for someone to fix later - //keyarr := []string{} + // keyarr := []string{} uids := []string{} for _, repoele := range repoval { if len(repoele.KeyPath) > 0 { - //keyarr = append(keyarr, repoele.KeyPath) + // keyarr = append(keyarr, repoele.KeyPath) uids = append(uids, trust.GetGPGIdFromKeyPath(repoele.KeyPath)...) } if len(repoele.KeyData) > 0 { - //keyarr = append(keyarr, string(repoele.KeyData)) + // keyarr = append(keyarr, string(repoele.KeyData)) uids = append(uids, trust.GetGPGIdFromKeyData(repoele.KeyData)...) } } diff --git a/pkg/hooks/monitor_test.go b/pkg/hooks/monitor_test.go index dc67eaf83..eed02e033 100644 --- a/pkg/hooks/monitor_test.go +++ b/pkg/hooks/monitor_test.go @@ -226,7 +226,7 @@ func TestMonitorTwoDirGood(t *testing.T) { assert.Equal(t, primaryInjected, config.Hooks) // masked by primary }) - primaryPath2 := filepath.Join(primaryDir, "0a.json") //0a because it will be before a.json alphabetically + primaryPath2 := filepath.Join(primaryDir, "0a.json") // 0a because it will be before a.json alphabetically t.Run("bad-primary-new-addition", func(t *testing.T) { err = ioutil.WriteFile(primaryPath2, []byte("{\"version\": \"-1\"}"), 0644) diff --git a/pkg/k8s.io/api/core/v1/types.go b/pkg/k8s.io/api/core/v1/types.go index a488e5f28..48f353cc6 100644 --- a/pkg/k8s.io/api/core/v1/types.go +++ b/pkg/k8s.io/api/core/v1/types.go @@ -1514,7 +1514,7 @@ const ( // by the node selector terms. // +structType=atomic type NodeSelector struct { - //Required. A list of node selector terms. The terms are ORed. + // Required. A list of node selector terms. The terms are ORed. NodeSelectorTerms []NodeSelectorTerm `json:"nodeSelectorTerms"` } @@ -3040,7 +3040,7 @@ type ServiceSpec struct { SessionAffinityConfig *SessionAffinityConfig `json:"sessionAffinityConfig,omitempty"` // TopologyKeys is tombstoned to show why 16 is reserved protobuf tag. - //TopologyKeys []string `json:"topologyKeys,omitempty"` + // TopologyKeys []string `json:"topologyKeys,omitempty"` // IPFamily is tombstoned to show why 15 is a reserved protobuf tag. // IPFamily *IPFamily `json:"ipFamily,omitempty"` diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/amount.go b/pkg/k8s.io/apimachinery/pkg/api/resource/amount.go index a8866a43e..9f76f9154 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/amount.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/amount.go @@ -231,13 +231,13 @@ func (a int64Amount) AsCanonicalBytes(out []byte) (result []byte, exponent int32 if !ok { return infDecAmount{a.AsDec()}.AsCanonicalBytes(out) } - exponent = exponent - 1 + exponent-- case 2, -1: amount, ok = int64MultiplyScale100(amount) if !ok { return infDecAmount{a.AsDec()}.AsCanonicalBytes(out) } - exponent = exponent - 2 + exponent -= 2 } return strconv.AppendInt(out, amount, 10), exponent } diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/math.go b/pkg/k8s.io/apimachinery/pkg/api/resource/math.go index 7b4fa5a36..9d03f5c05 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/math.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/math.go @@ -171,7 +171,7 @@ func negativeScaleInt64(base int64, scale Scale) (result int64, exact bool) { if !fraction && value%10 != 0 { fraction = true } - value = value / 10 + value /= 10 if value == 0 { if fraction { if base > 0 { @@ -265,18 +265,18 @@ func removeInt64Factors(value int64, base int64) (result int64, times int32) { case 10: for result >= 10 && result%10 == 0 { times++ - result = result / 10 + result /= 10 } // allow the compiler to optimize the common cases case 1024: for result >= 1024 && result%1024 == 0 { times++ - result = result / 1024 + result /= 1024 } default: for result >= base && result%base == 0 { times++ - result = result / base + result /= base } } if negative { diff --git a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go index 697817774..39073c06b 100644 --- a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go +++ b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go @@ -1156,7 +1156,7 @@ type ManagedFieldsEntry struct { Time *Time `json:"time,omitempty"` // Fields is tombstoned to show why 5 is a reserved protobuf tag. - //Fields *Fields `json:"fields,omitempty"` + // Fields *Fields `json:"fields,omitempty"` // FieldsType is the discriminator for the different fields format and version. // There is currently only one possible value: "FieldsV1" diff --git a/pkg/lookup/lookup.go b/pkg/lookup/lookup.go index 0601e829d..b8ac3046e 100644 --- a/pkg/lookup/lookup.go +++ b/pkg/lookup/lookup.go @@ -61,7 +61,7 @@ func GetUserGroupInfo(containerMount, containerUser string, override *Overrides) defaultExecUser = override.DefaultUser } else { // Define a default container user - //defaultExecUser = &user.ExecUser{ + // defaultExecUser = &user.ExecUser{ // Uid: 0, // Gid: 0, // Home: "/", diff --git a/pkg/machine/config.go b/pkg/machine/config.go index 1103933cd..5bbaf8c51 100644 --- a/pkg/machine/config.go +++ b/pkg/machine/config.go @@ -135,7 +135,7 @@ type InspectInfo struct { } func (rc RemoteConnectionType) MakeSSHURL(host, path, port, userName string) url.URL { - //TODO Should this function have input verification? + // TODO Should this function have input verification? userInfo := url.User(userName) uri := url.URL{ Scheme: "ssh", diff --git a/pkg/machine/fedora.go b/pkg/machine/fedora.go index bed45c6da..14a173da6 100644 --- a/pkg/machine/fedora.go +++ b/pkg/machine/fedora.go @@ -21,6 +21,8 @@ const ( githubURL = "http://github.com/fedora-cloud/docker-brew-fedora/" ) +var fedoraxzRegex = regexp.MustCompile(`fedora[^\"]+xz`) + type FedoraDownload struct { Download } @@ -96,12 +98,8 @@ func getFedoraDownload(releaseStream string) (string, *url.URL, int64, error) { return "", nil, -1, err } - rx, err := regexp.Compile(`fedora[^\"]+xz`) - if err != nil { - return "", nil, -1, err - } - file := rx.FindString(string(body)) - if len(file) <= 0 { + file := fedoraxzRegex.FindString(string(body)) + if len(file) == 0 { return "", nil, -1, fmt.Errorf("could not locate Fedora download at %s", dirURL) } diff --git a/pkg/machine/qemu/machine.go b/pkg/machine/qemu/machine.go index 969acb760..5481bad29 100644 --- a/pkg/machine/qemu/machine.go +++ b/pkg/machine/qemu/machine.go @@ -332,8 +332,7 @@ func (v *MachineVM) Init(opts machine.InitOptions) (bool, error) { } } } - switch volumeType { - case VolumeTypeVirtfs: + if volumeType == VolumeTypeVirtfs { virtfsOptions := fmt.Sprintf("local,path=%s,mount_tag=%s,security_model=mapped-xattr", source, tag) if readonly { virtfsOptions += ",readonly" @@ -783,7 +782,7 @@ func (v *MachineVM) Stop(_ string, _ machine.StopOptions) error { break } time.Sleep(waitInternal) - waitInternal = waitInternal * 2 + waitInternal *= 2 } return v.ReadySocket.Delete() @@ -799,8 +798,7 @@ func NewQMPMonitor(network, name string, timeout time.Duration) (Monitor, error) rtDir = "/run" } rtDir = filepath.Join(rtDir, "podman") - if _, err := os.Stat(filepath.Join(rtDir)); os.IsNotExist(err) { - // TODO 0644 is fine on linux but macos is weird + if _, err := os.Stat(rtDir); os.IsNotExist(err) { if err := os.MkdirAll(rtDir, 0755); err != nil { return Monitor{}, err } @@ -872,7 +870,7 @@ func (v *MachineVM) Remove(_ string, opts machine.RemoveOptions) (string, func() confirmationMessage += msg + "\n" } - //remove socket and pid file if any: warn at low priority if things fail + // remove socket and pid file if any: warn at low priority if things fail // Remove the pidfile if err := v.PidFilePath.Delete(); err != nil { logrus.Debugf("Error while removing pidfile: %v", err) diff --git a/pkg/namespaces/namespaces.go b/pkg/namespaces/namespaces.go index bdea7c310..c95f8e275 100644 --- a/pkg/namespaces/namespaces.go +++ b/pkg/namespaces/namespaces.go @@ -375,7 +375,7 @@ func (n NetworkMode) Container() string { return "" } -//UserDefined indicates user-created network +// UserDefined indicates user-created network func (n NetworkMode) UserDefined() string { if n.IsUserDefined() { return string(n) diff --git a/pkg/specgen/container_validate.go b/pkg/specgen/container_validate.go index e06cd9a29..355fbc368 100644 --- a/pkg/specgen/container_validate.go +++ b/pkg/specgen/container_validate.go @@ -122,19 +122,19 @@ func (s *SpecGenerator) Validate() error { } // TODO the specgen does not appear to handle this? Should it - //switch config.Cgroup.Cgroups { - //case "disabled": + // switch config.Cgroup.Cgroups { + // case "disabled": // if addedResources { // return errors.New("cannot specify resource limits when cgroups are disabled is specified") // } // configSpec.Linux.Resources = &spec.LinuxResources{} - //case "enabled", "no-conmon", "": + // case "enabled", "no-conmon", "": // // Do nothing - //default: + // default: // return errors.New("unrecognized option for cgroups; supported are 'default', 'disabled', 'no-conmon'") - //} + // } invalidUlimitFormatError := errors.New("invalid default ulimit definition must be form of type=soft:hard") - //set ulimits if not rootless + // set ulimits if not rootless if len(s.ContainerResourceConfig.Rlimits) < 1 && !rootless.IsRootless() { // Containers common defines this as something like nproc=4194304:4194304 tmpnproc := containerConfig.Ulimits() diff --git a/pkg/specgen/generate/container.go b/pkg/specgen/generate/container.go index 81286b962..831c1d7b9 100644 --- a/pkg/specgen/generate/container.go +++ b/pkg/specgen/generate/container.go @@ -395,7 +395,7 @@ func ConfigToSpec(rt *libpod.Runtime, specg *specgen.SpecGenerator, contaierID s } else { switch nameSpaces[i] { case "pid": - specg.PidNS = specgen.Namespace{NSMode: specgen.Default} //default + specg.PidNS = specgen.Namespace{NSMode: specgen.Default} // default case "net": switch { case conf.NetMode.IsBridge(): @@ -435,7 +435,7 @@ func ConfigToSpec(rt *libpod.Runtime, specg *specgen.SpecGenerator, contaierID s specg.NetNS = specgen.Namespace{NSMode: specgen.FromPod, Value: strings.Split(string(conf.NetMode), ":")[1]} } case "cgroup": - specg.CgroupNS = specgen.Namespace{NSMode: specgen.Default} //default + specg.CgroupNS = specgen.Namespace{NSMode: specgen.Default} // default case "ipc": switch conf.ShmDir { case "/dev/shm": @@ -443,15 +443,15 @@ func ConfigToSpec(rt *libpod.Runtime, specg *specgen.SpecGenerator, contaierID s case "": specg.IpcNS = specgen.Namespace{NSMode: specgen.None} default: - specg.IpcNS = specgen.Namespace{NSMode: specgen.Default} //default + specg.IpcNS = specgen.Namespace{NSMode: specgen.Default} // default } case "uts": - specg.UtsNS = specgen.Namespace{NSMode: specgen.Default} //default + specg.UtsNS = specgen.Namespace{NSMode: specgen.Default} // default case "user": if conf.AddCurrentUserPasswdEntry { specg.UserNS = specgen.Namespace{NSMode: specgen.KeepID} } else { - specg.UserNS = specgen.Namespace{NSMode: specgen.Default} //default + specg.UserNS = specgen.Namespace{NSMode: specgen.Default} // default } } } diff --git a/pkg/specgen/generate/container_create.go b/pkg/specgen/generate/container_create.go index 50454cbab..8b9ed8ffe 100644 --- a/pkg/specgen/generate/container_create.go +++ b/pkg/specgen/generate/container_create.go @@ -434,20 +434,18 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l // Security options if len(s.SelinuxOpts) > 0 { options = append(options, libpod.WithSecLabels(s.SelinuxOpts)) - } else { - if pod != nil && len(compatibleOptions.SelinuxOpts) == 0 { - // duplicate the security options from the pod - processLabel, err := pod.ProcessLabel() + } else if pod != nil && len(compatibleOptions.SelinuxOpts) == 0 { + // duplicate the security options from the pod + processLabel, err := pod.ProcessLabel() + if err != nil { + return nil, err + } + if processLabel != "" { + selinuxOpts, err := label.DupSecOpt(processLabel) if err != nil { return nil, err } - if processLabel != "" { - selinuxOpts, err := label.DupSecOpt(processLabel) - if err != nil { - return nil, err - } - options = append(options, libpod.WithSecLabels(selinuxOpts)) - } + options = append(options, libpod.WithSecLabels(selinuxOpts)) } } options = append(options, libpod.WithPrivileged(s.Privileged)) diff --git a/pkg/specgen/generate/kube/kube.go b/pkg/specgen/generate/kube/kube.go index 51f9fa535..4c11e4bff 100644 --- a/pkg/specgen/generate/kube/kube.go +++ b/pkg/specgen/generate/kube/kube.go @@ -449,12 +449,13 @@ func setupLivenessProbe(s *specgen.SpecGenerator, containerYAML v1.Container, re } // configure healthcheck on the basis of Handler Actions. - if probeHandler.Exec != nil { + switch { + case probeHandler.Exec != nil: execString := strings.Join(probeHandler.Exec.Command, " ") commandString = fmt.Sprintf("%s || %s", execString, failureCmd) - } else if probeHandler.HTTPGet != nil { + case probeHandler.HTTPGet != nil: commandString = fmt.Sprintf("curl %s://%s:%d/%s || %s", probeHandler.HTTPGet.Scheme, probeHandler.HTTPGet.Host, probeHandler.HTTPGet.Port.IntValue(), probeHandler.HTTPGet.Path, failureCmd) - } else if probeHandler.TCPSocket != nil { + case probeHandler.TCPSocket != nil: commandString = fmt.Sprintf("nc -z -v %s %d || %s", probeHandler.TCPSocket.Host, probeHandler.TCPSocket.Port.IntValue(), failureCmd) } s.HealthConfig, err = makeHealthCheck(commandString, probe.PeriodSeconds, probe.FailureThreshold, probe.TimeoutSeconds, probe.InitialDelaySeconds) @@ -490,17 +491,17 @@ func makeHealthCheck(inCmd string, interval int32, retries int32, timeout int32, } if interval < 1 { - //kubernetes interval defaults to 10 sec and cannot be less than 1 + // kubernetes interval defaults to 10 sec and cannot be less than 1 interval = 10 } hc.Interval = (time.Duration(interval) * time.Second) if retries < 1 { - //kubernetes retries defaults to 3 + // kubernetes retries defaults to 3 retries = 3 } hc.Retries = int(retries) if timeout < 1 { - //kubernetes timeout defaults to 1 + // kubernetes timeout defaults to 1 timeout = 1 } timeoutDuration := (time.Duration(timeout) * time.Second) diff --git a/pkg/specgen/generate/kube/kube_test.go b/pkg/specgen/generate/kube/kube_test.go index 0898d427d..9c52c03bb 100644 --- a/pkg/specgen/generate/kube/kube_test.go +++ b/pkg/specgen/generate/kube/kube_test.go @@ -5,7 +5,6 @@ import ( v1 "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1" "github.com/stretchr/testify/assert" - //"github.com/stretchr/testify/require" ) func testPropagation(t *testing.T, propagation v1.MountPropagationMode, expected string) { diff --git a/pkg/specgen/generate/namespaces.go b/pkg/specgen/generate/namespaces.go index 2362f61c4..37d561ec2 100644 --- a/pkg/specgen/generate/namespaces.go +++ b/pkg/specgen/generate/namespaces.go @@ -202,10 +202,8 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod. if s.IDMappings != nil { if pod == nil { toReturn = append(toReturn, libpod.WithIDMappings(*s.IDMappings)) - } else { - if pod.HasInfraContainer() && (len(s.IDMappings.UIDMap) > 0 || len(s.IDMappings.GIDMap) > 0) { - return nil, errors.Wrapf(define.ErrInvalidArg, "cannot specify a new uid/gid map when entering a pod with an infra container") - } + } else if pod.HasInfraContainer() && (len(s.IDMappings.UIDMap) > 0 || len(s.IDMappings.GIDMap) > 0) { + return nil, errors.Wrapf(define.ErrInvalidArg, "cannot specify a new uid/gid map when entering a pod with an infra container") } } if s.User != "" { @@ -482,7 +480,7 @@ func GetNamespaceOptions(ns []string, netnsIsHost bool) ([]libpod.PodCreateOptio var options []libpod.PodCreateOption var erroredOptions []libpod.PodCreateOption if ns == nil { - //set the default namespaces + // set the default namespaces ns = strings.Split(specgen.DefaultKernelNamespaces, ",") } for _, toShare := range ns { diff --git a/pkg/specgen/generate/oci.go b/pkg/specgen/generate/oci.go index 95bcea8f0..b77c00f50 100644 --- a/pkg/specgen/generate/oci.go +++ b/pkg/specgen/generate/oci.go @@ -298,7 +298,8 @@ func SpecGenToOCI(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runt g.AddAnnotation(key, val) } - if compatibleOptions.InfraResources == nil && s.ResourceLimits != nil { + switch { + case compatibleOptions.InfraResources == nil && s.ResourceLimits != nil: out, err := json.Marshal(s.ResourceLimits) if err != nil { return nil, err @@ -307,7 +308,7 @@ func SpecGenToOCI(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runt if err != nil { return nil, err } - } else if s.ResourceLimits != nil { // if we have predefined resource limits we need to make sure we keep the infra and container limits + case s.ResourceLimits != nil: // if we have predefined resource limits we need to make sure we keep the infra and container limits originalResources, err := json.Marshal(s.ResourceLimits) if err != nil { return nil, err @@ -325,7 +326,7 @@ func SpecGenToOCI(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runt return nil, err } g.Config.Linux.Resources = s.ResourceLimits - } else { + default: g.Config.Linux.Resources = compatibleOptions.InfraResources } // Devices diff --git a/pkg/specgen/generate/validate.go b/pkg/specgen/generate/validate.go index 8da3f2936..44c7818e7 100644 --- a/pkg/specgen/generate/validate.go +++ b/pkg/specgen/generate/validate.go @@ -47,10 +47,8 @@ func verifyContainerResourcesCgroupV1(s *specgen.SpecGenerator) ([]string, error if !sysInfo.MemorySwappiness { warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.") memory.Swappiness = nil - } else { - if *memory.Swappiness > 100 { - return warnings, errors.Errorf("invalid value: %v, valid memory swappiness range is 0-100", *memory.Swappiness) - } + } else if *memory.Swappiness > 100 { + return warnings, errors.Errorf("invalid value: %v, valid memory swappiness range is 0-100", *memory.Swappiness) } } if memory.Reservation != nil && !sysInfo.MemoryReservation { diff --git a/pkg/specgen/winpath.go b/pkg/specgen/winpath.go index f4249fab1..0df4ebdd7 100644 --- a/pkg/specgen/winpath.go +++ b/pkg/specgen/winpath.go @@ -47,11 +47,12 @@ func ConvertWinMountPath(path string) (string, error) { path = strings.TrimPrefix(path, `\\?\`) // Drive installed via wsl --mount - if strings.HasPrefix(path, `\\.\`) { + switch { + case strings.HasPrefix(path, `\\.\`): path = "/mnt/wsl/" + path[4:] - } else if len(path) > 1 && path[1] == ':' { + case len(path) > 1 && path[1] == ':': path = "/mnt/" + strings.ToLower(path[0:1]) + path[2:] - } else { + default: return path, errors.New("unsupported UNC path") } diff --git a/pkg/specgenutil/createparse.go b/pkg/specgenutil/createparse.go index a51396227..fb5f9c351 100644 --- a/pkg/specgenutil/createparse.go +++ b/pkg/specgenutil/createparse.go @@ -24,11 +24,12 @@ func validate(c *entities.ContainerCreateOptions) error { "ignore": "", } if _, ok := imageVolType[c.ImageVolume]; !ok { - if c.IsInfra { + switch { + case c.IsInfra: c.ImageVolume = "bind" - } else if c.IsClone { // the image volume type will be deduced later from the container we are cloning + case c.IsClone: // the image volume type will be deduced later from the container we are cloning return nil - } else { + default: return errors.Errorf("invalid image-volume type %q. Pick one of bind, tmpfs, or ignore", c.ImageVolume) } } diff --git a/pkg/specgenutil/specgen.go b/pkg/specgenutil/specgen.go index f0dfcac1a..9cb2f200b 100644 --- a/pkg/specgenutil/specgen.go +++ b/pkg/specgenutil/specgen.go @@ -1098,9 +1098,9 @@ var cgroupDeviceType = map[string]bool{ } var cgroupDeviceAccess = map[string]bool{ - "r": true, //read - "w": true, //write - "m": true, //mknod + "r": true, // read + "w": true, // write + "m": true, // mknod } // parseLinuxResourcesDeviceAccess parses the raw string passed with the --device-access-add flag diff --git a/pkg/systemd/dbus.go b/pkg/systemd/dbus.go index b35f778ab..6887a466e 100644 --- a/pkg/systemd/dbus.go +++ b/pkg/systemd/dbus.go @@ -26,39 +26,39 @@ func IsSystemdSessionValid(uid int) bool { if rootless.IsRootless() { conn, err = GetLogindConnection(rootless.GetRootlessUID()) if err != nil { - //unable to fetch systemd object for logind + // unable to fetch systemd object for logind logrus.Debugf("systemd-logind: %s", err) return false } object = conn.Object(dbusDest, godbus.ObjectPath(dbusPath)) if err := object.Call(dbusInterface+".GetSeat", 0, "seat0").Store(&seat0Path); err != nil { - //unable to get seat0 path. + // unable to get seat0 path. logrus.Debugf("systemd-logind: %s", err) return false } seat0Obj := conn.Object(dbusDest, seat0Path) activeSession, err := seat0Obj.GetProperty(dbusDest + ".Seat.ActiveSession") if err != nil { - //unable to get active sessions. + // unable to get active sessions. logrus.Debugf("systemd-logind: %s", err) return false } activeSessionMap, ok := activeSession.Value().([]interface{}) if !ok || len(activeSessionMap) < 2 { - //unable to get active session map. + // unable to get active session map. logrus.Debugf("systemd-logind: %s", err) return false } activeSessionPath, ok := activeSessionMap[1].(godbus.ObjectPath) if !ok { - //unable to fetch active session path. + // unable to fetch active session path. logrus.Debugf("systemd-logind: %s", err) return false } activeSessionObj := conn.Object(dbusDest, activeSessionPath) sessionUser, err := activeSessionObj.GetProperty(dbusDest + ".Session.User") if err != nil { - //unable to fetch session user from activeSession path. + // unable to fetch session user from activeSession path. logrus.Debugf("systemd-logind: %s", err) return false } @@ -75,7 +75,7 @@ func IsSystemdSessionValid(uid int) bool { if !ok { return false } - //active session found which belongs to following rootless user + // active session found which belongs to following rootless user if activeUID == uint32(uid) { return true } diff --git a/pkg/timetype/timestamp.go b/pkg/timetype/timestamp.go index 2de1a005f..5e9c6a159 100644 --- a/pkg/timetype/timestamp.go +++ b/pkg/timetype/timestamp.go @@ -34,13 +34,14 @@ func GetTimestamp(value string, reference time.Time) (string, error) { // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) - if strings.Contains(value, ".") { // nolint(gocritic) + switch { + case strings.Contains(value, "."): if parseInLocation { format = rFC3339NanoLocal } else { format = time.RFC3339Nano } - } else if strings.Contains(value, "T") { + case strings.Contains(value, "T"): // we want the number of colons in the T portion of the timestamp tcolons := strings.Count(value, ":") // if parseInLocation is off and we have a +/- zone offset (not Z) then @@ -68,9 +69,9 @@ func GetTimestamp(value string, reference time.Time) (string, error) { format = time.RFC3339 } } - } else if parseInLocation { + case parseInLocation: format = dateLocal - } else { + default: format = dateWithZone } |