From 979c4254eb31bd1b85f51c7779573964f28c033b Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 14:46:12 -0400 Subject: [PATCH 01/40] Fix integer division --- test/e2e/apimachinery/garbage_collector.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/apimachinery/garbage_collector.go b/test/e2e/apimachinery/garbage_collector.go index e337a46d60a..493013b6f1c 100644 --- a/test/e2e/apimachinery/garbage_collector.go +++ b/test/e2e/apimachinery/garbage_collector.go @@ -68,7 +68,7 @@ func estimateMaximumPods(c clientset.Interface, min, max int32) int32 { availablePods += 10 } //avoid creating exactly max pods - availablePods *= 8 / 10 + availablePods = int32(float32(availablePods) * 8.0 / 10.0) // bound the top and bottom if availablePods > max { availablePods = max From 0f3836dcc5bca62c21128236994c8358bfeb6345 Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 14:51:31 -0400 Subject: [PATCH 02/40] Ignore deprecation warnings with //nolint:staticcheck --- cmd/kube-proxy/app/server.go | 1 + cmd/kube-scheduler/app/config/config.go | 1 + pkg/kubelet/dockershim/docker_container.go | 1 + pkg/kubelet/server/server.go | 1 + pkg/registry/core/namespace/storage/storage.go | 3 +++ 5 files changed, 7 insertions(+) diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index 5975731b171..fa3b0906289 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -624,6 +624,7 @@ func serveMetrics(bindAddress, proxyMode string, enableProfiling bool, errCh cha }) //lint:ignore SA1019 See the Metrics Stability Migration KEP + //nolint:staticcheck proxyMux.Handle("/metrics", legacyregistry.Handler()) if enableProfiling { diff --git a/cmd/kube-scheduler/app/config/config.go b/cmd/kube-scheduler/app/config/config.go index 1448ff8cf49..91fbf44164e 100644 --- a/cmd/kube-scheduler/app/config/config.go +++ b/cmd/kube-scheduler/app/config/config.go @@ -45,6 +45,7 @@ type Config struct { DynInformerFactory dynamicinformer.DynamicSharedInformerFactory //lint:ignore SA1019 this deprecated field still needs to be used for now. It will be removed once the migration is done. + //nolint:staticcheck EventBroadcaster events.EventBroadcasterAdapter // LeaderElection is optional. diff --git a/pkg/kubelet/dockershim/docker_container.go b/pkg/kubelet/dockershim/docker_container.go index 898931a3733..7f5fb7c79c5 100644 --- a/pkg/kubelet/dockershim/docker_container.go +++ b/pkg/kubelet/dockershim/docker_container.go @@ -182,6 +182,7 @@ func (ds *dockerService) CreateContainer(_ context.Context, r *runtimeapi.Create hc.Resources.Devices = devices //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck securityOpts, err := ds.getSecurityOpts(config.GetLinux().GetSecurityContext().GetSeccompProfilePath(), securityOptSeparator) if err != nil { return nil, fmt.Errorf("failed to generate security options for container %q: %v", config.Metadata.Name, err) diff --git a/pkg/kubelet/server/server.go b/pkg/kubelet/server/server.go index 5d230755ab8..9312dfd49c6 100644 --- a/pkg/kubelet/server/server.go +++ b/pkg/kubelet/server/server.go @@ -354,6 +354,7 @@ func (s *Server) InstallDefaultHandlers() { s.addMetricsBucketMatcher("metrics/probes") s.addMetricsBucketMatcher("metrics/resource") //lint:ignore SA1019 https://github.com/kubernetes/enhancements/issues/1206 + //nolint:staticcheck s.restfulCont.Handle(metricsPath, legacyregistry.Handler()) // cAdvisor metrics are exposed under the secured handler as well diff --git a/pkg/registry/core/namespace/storage/storage.go b/pkg/registry/core/namespace/storage/storage.go index 375445e3a0f..55bcbcc7dd1 100644 --- a/pkg/registry/core/namespace/storage/storage.go +++ b/pkg/registry/core/namespace/storage/storage.go @@ -254,8 +254,10 @@ func ShouldDeleteNamespaceDuringUpdate(ctx context.Context, key string, obj, exi func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalizer bool) bool { //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck if options.OrphanDependents != nil { //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck return *options.OrphanDependents } if options.PropagationPolicy != nil { @@ -266,6 +268,7 @@ func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalize func shouldHaveDeleteDependentsFinalizer(options *metav1.DeleteOptions, haveDeleteDependentsFinalizer bool) bool { //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck if options.OrphanDependents != nil { //lint:ignore SA1019 backwards compatibility return *options.OrphanDependents == false From 30ea05ae7b8f5cd92f5e563177091b36f0cfe08e Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 15:15:26 -0400 Subject: [PATCH 03/40] Update IPVar and IPPortVar functions to have pointer receivers to fix 'ineffective assignment' --- cmd/kube-proxy/app/server.go | 6 +++--- cmd/kubelet/app/options/options.go | 2 +- pkg/util/flag/flags.go | 12 ++++++------ pkg/util/flag/flags_test.go | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index fa3b0906289..a0a920f3e0d 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -165,9 +165,9 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) { fs.BoolVar(&o.CleanupAndExit, "cleanup", o.CleanupAndExit, "If true cleanup iptables and ipvs rules and exit.") - fs.Var(utilflag.IPVar{Val: &o.config.BindAddress}, "bind-address", "The IP address for the proxy server to serve on (set to '0.0.0.0' for all IPv4 interfaces and '::' for all IPv6 interfaces)") - fs.Var(utilflag.IPPortVar{Val: &o.config.HealthzBindAddress}, "healthz-bind-address", "The IP address with port for the health check server to serve on (set to '0.0.0.0:10256' for all IPv4 interfaces and '[::]:10256' for all IPv6 interfaces). Set empty to disable.") - fs.Var(utilflag.IPPortVar{Val: &o.config.MetricsBindAddress}, "metrics-bind-address", "The IP address with port for the metrics server to serve on (set to '0.0.0.0:10249' for all IPv4 interfaces and '[::]:10249' for all IPv6 interfaces). Set empty to disable.") + fs.Var(&utilflag.IPVar{Val: &o.config.BindAddress}, "bind-address", "The IP address for the proxy server to serve on (set to '0.0.0.0' for all IPv4 interfaces and '::' for all IPv6 interfaces)") + fs.Var(&utilflag.IPPortVar{Val: &o.config.HealthzBindAddress}, "healthz-bind-address", "The IP address with port for the health check server to serve on (set to '0.0.0.0:10256' for all IPv4 interfaces and '[::]:10256' for all IPv6 interfaces). Set empty to disable.") + fs.Var(&utilflag.IPPortVar{Val: &o.config.MetricsBindAddress}, "metrics-bind-address", "The IP address with port for the metrics server to serve on (set to '0.0.0.0:10249' for all IPv4 interfaces and '[::]:10249' for all IPv6 interfaces). Set empty to disable.") fs.BoolVar(&o.config.BindAddressHardFail, "bind-address-hard-fail", o.config.BindAddressHardFail, "If true kube-proxy will treat failure to bind to a port as fatal and exit") fs.Var(utilflag.PortRangeVar{Val: &o.config.PortRange}, "proxy-port-range", "Range of host ports (beginPort-endPort, single port or beginPort+offset, inclusive) that may be consumed in order to proxy service traffic. If (unspecified, 0, or 0-0) then ports will be randomly chosen.") fs.Var(&o.config.Mode, "proxy-mode", "Which proxy mode to use: 'userspace' (older) or 'iptables' (faster) or 'ipvs' or 'kernelspace' (windows). If blank, use the best-available proxy (currently iptables). If the iptables proxy is selected, regardless of how, but the system's kernel or iptables versions are insufficient, this always falls back to the userspace proxy.") diff --git a/cmd/kubelet/app/options/options.go b/cmd/kubelet/app/options/options.go index 8f096e4f277..5e2b5b7640e 100644 --- a/cmd/kubelet/app/options/options.go +++ b/cmd/kubelet/app/options/options.go @@ -405,7 +405,7 @@ func AddKubeletConfigFlags(mainfs *pflag.FlagSet, c *kubeletconfig.KubeletConfig fs.DurationVar(&c.HTTPCheckFrequency.Duration, "http-check-frequency", c.HTTPCheckFrequency.Duration, "Duration between checking http for new data") fs.StringVar(&c.StaticPodURL, "manifest-url", c.StaticPodURL, "URL for accessing additional Pod specifications to run") fs.Var(cliflag.NewColonSeparatedMultimapStringString(&c.StaticPodURLHeader), "manifest-url-header", "Comma-separated list of HTTP headers to use when accessing the url provided to --manifest-url. Multiple headers with the same name will be added in the same order provided. This flag can be repeatedly invoked. For example: --manifest-url-header 'a:hello,b:again,c:world' --manifest-url-header 'b:beautiful'") - fs.Var(utilflag.IPVar{Val: &c.Address}, "address", "The IP address for the Kubelet to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)") + fs.Var(&utilflag.IPVar{Val: &c.Address}, "address", "The IP address for the Kubelet to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)") fs.Int32Var(&c.Port, "port", c.Port, "The port for the Kubelet to serve on.") fs.Int32Var(&c.ReadOnlyPort, "read-only-port", c.ReadOnlyPort, "The read-only port for the Kubelet to serve on with no authentication/authorization (set to 0 to disable)") diff --git a/pkg/util/flag/flags.go b/pkg/util/flag/flags.go index 5ecc283974e..63c48e413d6 100644 --- a/pkg/util/flag/flags.go +++ b/pkg/util/flag/flags.go @@ -50,7 +50,7 @@ type IPVar struct { } // Set sets the flag value -func (v IPVar) Set(s string) error { +func (v *IPVar) Set(s string) error { if len(s) == 0 { v.Val = nil return nil @@ -67,7 +67,7 @@ func (v IPVar) Set(s string) error { } // String returns the flag value -func (v IPVar) String() string { +func (v *IPVar) String() string { if v.Val == nil { return "" } @@ -75,7 +75,7 @@ func (v IPVar) String() string { } // Type gets the flag type -func (v IPVar) Type() string { +func (v *IPVar) Type() string { return "ip" } @@ -85,7 +85,7 @@ type IPPortVar struct { } // Set sets the flag value -func (v IPPortVar) Set(s string) error { +func (v *IPPortVar) Set(s string) error { if len(s) == 0 { v.Val = nil return nil @@ -119,7 +119,7 @@ func (v IPPortVar) Set(s string) error { } // String returns the flag value -func (v IPPortVar) String() string { +func (v *IPPortVar) String() string { if v.Val == nil { return "" } @@ -127,7 +127,7 @@ func (v IPPortVar) String() string { } // Type gets the flag type -func (v IPPortVar) Type() string { +func (v *IPPortVar) Type() string { return "ipport" } diff --git a/pkg/util/flag/flags_test.go b/pkg/util/flag/flags_test.go index 04daa8ddb2f..938715b3537 100644 --- a/pkg/util/flag/flags_test.go +++ b/pkg/util/flag/flags_test.go @@ -51,7 +51,7 @@ func TestIPVar(t *testing.T) { for _, tc := range testCases { fs := pflag.NewFlagSet("blah", pflag.PanicOnError) ip := defaultIP - fs.Var(IPVar{&ip}, "ip", "the ip") + fs.Var(&IPVar{&ip}, "ip", "the ip") var err error func() { @@ -145,7 +145,7 @@ func TestIPPortVar(t *testing.T) { for _, tc := range testCases { fs := pflag.NewFlagSet("blah", pflag.PanicOnError) ipport := defaultIPPort - fs.Var(IPPortVar{&ipport}, "ipport", "the ip:port") + fs.Var(&IPPortVar{&ipport}, "ipport", "the ip:port") var err error func() { From 1fbf06f5ad2da7aa870dba82af6c3669c530c04f Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 15:27:44 -0400 Subject: [PATCH 04/40] Use time.NewTicker instead of time.Tick to avoid leaking --- pkg/kubelet/status/status_manager.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pkg/kubelet/status/status_manager.go b/pkg/kubelet/status/status_manager.go index 9c93a746b58..7ec6d2b51a8 100644 --- a/pkg/kubelet/status/status_manager.go +++ b/pkg/kubelet/status/status_manager.go @@ -157,8 +157,7 @@ func (m *manager) Start() { } klog.InfoS("Starting to sync pod status with apiserver") - //lint:ignore SA1015 Ticker can link since this is only called once and doesn't handle termination. - syncTicker := time.Tick(syncPeriod) + syncTicker := time.NewTicker(syncPeriod).C // syncPod and syncBatch share the same go routine to avoid sync races. go wait.Forever(func() { for { From 04fadd8b03a4e44edc01e1aadd74e946d01a898b Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 16:15:05 -0400 Subject: [PATCH 05/40] Fix SA5011 errors by making control flow abort obvious to linter --- test/e2e/framework/log.go | 1 + test/e2e/framework/skipper/skipper.go | 1 + 2 files changed, 2 insertions(+) diff --git a/test/e2e/framework/log.go b/test/e2e/framework/log.go index 43927b2f0e7..e398817aef6 100644 --- a/test/e2e/framework/log.go +++ b/test/e2e/framework/log.go @@ -49,6 +49,7 @@ func Failf(format string, args ...interface{}) { skip := 2 log("FAIL", "%s\n\nFull Stack Trace\n%s", msg, PrunedStack(skip)) e2eginkgowrapper.Fail(nowStamp()+": "+msg, skip) + panic("unreachable") } // Fail is a replacement for ginkgo.Fail which logs the problem as it occurs diff --git a/test/e2e/framework/skipper/skipper.go b/test/e2e/framework/skipper/skipper.go index c9434908eaa..8e4d9a879e8 100644 --- a/test/e2e/framework/skipper/skipper.go +++ b/test/e2e/framework/skipper/skipper.go @@ -118,6 +118,7 @@ func pruneStack(skip int) string { // Skipf skips with information about why the test is being skipped. func Skipf(format string, args ...interface{}) { skipInternalf(1, format, args...) + panic("unreachable") } // SkipUnlessAtLeast skips if the value is less than the minValue. From 7ea01c0bdb6f3efbc7dbf2b65f37c039e8a33a4c Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 15:59:11 -0400 Subject: [PATCH 06/40] Add staticcheck to verify-golangci-lint.sh --- hack/verify-golangci-lint.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hack/verify-golangci-lint.sh b/hack/verify-golangci-lint.sh index 1e0bc1192ed..237352b678f 100755 --- a/hack/verify-golangci-lint.sh +++ b/hack/verify-golangci-lint.sh @@ -50,4 +50,5 @@ golangci-lint run \ -E deadcode \ -E unused \ -E varcheck \ - -E ineffassign + -E ineffassign \ + -E staticcheck From a7daeb37affa7b883f229cd8e228f8f7328e10f3 Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 16:42:34 -0400 Subject: [PATCH 07/40] Convert one more utilflag.IPVar to &utilflag.IPVar --- cmd/kubelet/app/options/options.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/kubelet/app/options/options.go b/cmd/kubelet/app/options/options.go index 5e2b5b7640e..f407c9439e3 100644 --- a/cmd/kubelet/app/options/options.go +++ b/cmd/kubelet/app/options/options.go @@ -459,7 +459,7 @@ func AddKubeletConfigFlags(mainfs *pflag.FlagSet, c *kubeletconfig.KubeletConfig fs.BoolVar(&c.EnableDebuggingHandlers, "enable-debugging-handlers", c.EnableDebuggingHandlers, "Enables server endpoints for log collection and local running of containers and commands") fs.BoolVar(&c.EnableContentionProfiling, "contention-profiling", c.EnableContentionProfiling, "Enable lock contention profiling, if profiling is enabled") fs.Int32Var(&c.HealthzPort, "healthz-port", c.HealthzPort, "The port of the localhost healthz endpoint (set to 0 to disable)") - fs.Var(utilflag.IPVar{Val: &c.HealthzBindAddress}, "healthz-bind-address", "The IP address for the healthz server to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)") + fs.Var(&utilflag.IPVar{Val: &c.HealthzBindAddress}, "healthz-bind-address", "The IP address for the healthz server to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)") fs.Int32Var(&c.OOMScoreAdj, "oom-score-adj", c.OOMScoreAdj, "The oom-score-adj value for kubelet process. Values must be within the range [-1000, 1000]") fs.StringVar(&c.ClusterDomain, "cluster-domain", c.ClusterDomain, "Domain for this cluster. If set, kubelet will configure all containers to search this domain in addition to the host's search domains") From c862d7c0e93c086f9d35e20ae5fccd9a4f5b8207 Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Thu, 15 Jul 2021 17:38:43 -0400 Subject: [PATCH 08/40] Fix last remaining SA5011 error by removing unnecessary r != nil check --- cmd/kubeadm/app/preflight/checks.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cmd/kubeadm/app/preflight/checks.go b/cmd/kubeadm/app/preflight/checks.go index 56ead258588..dc4ac9f17b3 100644 --- a/cmd/kubeadm/app/preflight/checks.go +++ b/cmd/kubeadm/app/preflight/checks.go @@ -808,10 +808,9 @@ func getEtcdVersionResponse(client *http.Client, url string, target interface{}) loopCount-- return false, err } - //lint:ignore SA5011 If err != nil we are already returning. defer r.Body.Close() - if r != nil && r.StatusCode >= 500 && r.StatusCode <= 599 { + if r.StatusCode >= 500 && r.StatusCode <= 599 { loopCount-- return false, errors.Errorf("server responded with non-successful status: %s", r.Status) } From c8fde197f5ef7f232a790798e98063bcebd9635f Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Sun, 18 Jul 2021 14:48:32 -0400 Subject: [PATCH 09/40] Add more //nolint:staticcheck for failures caught in PR tests --- pkg/volume/util/fsquota/quota_linux.go | 4 ++-- test/integration/garbagecollector/garbage_collector_test.go | 6 +++--- .../scheduler_perf/scheduler_perf_legacy_test.go | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/volume/util/fsquota/quota_linux.go b/pkg/volume/util/fsquota/quota_linux.go index 2da7d263997..68e9c9e1a8a 100644 --- a/pkg/volume/util/fsquota/quota_linux.go +++ b/pkg/volume/util/fsquota/quota_linux.go @@ -305,7 +305,7 @@ func SupportsQuotas(m mount.Interface, path string) (bool, error) { // If the pod UID is identical to another one known, it may (but presently // doesn't) choose the same quota ID as other volumes in the pod. //lint:ignore SA4009 poduid is overwritten by design, see comment below -func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { +func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { //nolint:staticcheck if bytes == nil { return fmt.Errorf("attempting to assign null quota to %s", path) } @@ -320,7 +320,7 @@ func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resour // volumes in a pod, we can simply remove this line of code. // If and when we decide permanently that we're going to adopt // one quota per volume, we can rip all of the pod code out. - poduid = types.UID(uuid.NewUUID()) + poduid = types.UID(uuid.NewUUID()) //nolint:staticcheck if pod, ok := dirPodMap[path]; ok && pod != poduid { return fmt.Errorf("requesting quota on existing directory %s but different pod %s %s", path, pod, poduid) } diff --git a/test/integration/garbagecollector/garbage_collector_test.go b/test/integration/garbagecollector/garbage_collector_test.go index ed0385aca5d..12f432d8846 100644 --- a/test/integration/garbagecollector/garbage_collector_test.go +++ b/test/integration/garbagecollector/garbage_collector_test.go @@ -599,12 +599,12 @@ func setupRCsPods(t *testing.T, gc *garbagecollector.GarbageCollector, clientSet orphan := false switch { //lint:file-ignore SA1019 Keep testing deprecated OrphanDependents option until it's being removed - case options.OrphanDependents == nil && options.PropagationPolicy == nil && len(initialFinalizers) == 0: + case options.OrphanDependents == nil && options.PropagationPolicy == nil && len(initialFinalizers) == 0: //nolint:staticcheck // if there are no deletion options, the default policy for replication controllers is orphan orphan = true - case options.OrphanDependents != nil: + case options.OrphanDependents != nil: //nolint:staticcheck // if the deletion options explicitly specify whether to orphan, that controls - orphan = *options.OrphanDependents + orphan = *options.OrphanDependents //nolint:staticcheck case options.PropagationPolicy != nil: // if the deletion options explicitly specify whether to orphan, that controls orphan = *options.PropagationPolicy == metav1.DeletePropagationOrphan diff --git a/test/integration/scheduler_perf/scheduler_perf_legacy_test.go b/test/integration/scheduler_perf/scheduler_perf_legacy_test.go index 42267238c35..2ee024bb162 100644 --- a/test/integration/scheduler_perf/scheduler_perf_legacy_test.go +++ b/test/integration/scheduler_perf/scheduler_perf_legacy_test.go @@ -440,7 +440,7 @@ func benchmarkScheduling(numExistingPods, minPods int, b *testing.B) { if b.N < minPods { //lint:ignore SA3001 Set a minimum for b.N to get more meaningful results - b.N = minPods + b.N = minPods //nolint:staticcheck } finalFunc, podInformer, clientset, _ := mustSetupScheduler(nil) defer finalFunc() From 2933df36454124e75be7bcace0b3ee7f2d7060d9 Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Mon, 19 Jul 2021 19:00:14 -0400 Subject: [PATCH 10/40] Fix order of operations --- test/e2e/apimachinery/garbage_collector.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/apimachinery/garbage_collector.go b/test/e2e/apimachinery/garbage_collector.go index 493013b6f1c..344ffb0d81b 100644 --- a/test/e2e/apimachinery/garbage_collector.go +++ b/test/e2e/apimachinery/garbage_collector.go @@ -68,7 +68,7 @@ func estimateMaximumPods(c clientset.Interface, min, max int32) int32 { availablePods += 10 } //avoid creating exactly max pods - availablePods = int32(float32(availablePods) * 8.0 / 10.0) + availablePods = int32(float32(availablePods) * (8.0 / 10.0)) // bound the top and bottom if availablePods > max { availablePods = max From a707061828849b7565b40ec4c018ba3b77ec7fee Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Mon, 19 Jul 2021 19:21:00 -0400 Subject: [PATCH 11/40] Simplify multiplication --- test/e2e/apimachinery/garbage_collector.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/e2e/apimachinery/garbage_collector.go b/test/e2e/apimachinery/garbage_collector.go index 344ffb0d81b..c608878a92b 100644 --- a/test/e2e/apimachinery/garbage_collector.go +++ b/test/e2e/apimachinery/garbage_collector.go @@ -68,7 +68,7 @@ func estimateMaximumPods(c clientset.Interface, min, max int32) int32 { availablePods += 10 } //avoid creating exactly max pods - availablePods = int32(float32(availablePods) * (8.0 / 10.0)) + availablePods = int32(float32(availablePods) * 0.8) // bound the top and bottom if availablePods > max { availablePods = max From 07a883d8e62b7359c7b36313747ace45ed8a847b Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Tue, 20 Jul 2021 22:30:50 -0400 Subject: [PATCH 12/40] Remove //lint:ignore pragmas that aren't being used anymore --- cmd/kube-proxy/app/server.go | 3 +-- cmd/kube-scheduler/app/config/config.go | 3 +-- pkg/kubelet/dockershim/docker_container.go | 3 +-- pkg/kubelet/server/server.go | 3 +-- pkg/registry/core/namespace/storage/storage.go | 9 ++------- pkg/volume/util/fsquota/quota_linux.go | 5 ++--- .../garbagecollector/garbage_collector_test.go | 7 +++---- .../scheduler_perf/scheduler_perf_legacy_test.go | 3 +-- 8 files changed, 12 insertions(+), 24 deletions(-) diff --git a/cmd/kube-proxy/app/server.go b/cmd/kube-proxy/app/server.go index a0a920f3e0d..8241898fe66 100644 --- a/cmd/kube-proxy/app/server.go +++ b/cmd/kube-proxy/app/server.go @@ -623,8 +623,7 @@ func serveMetrics(bindAddress, proxyMode string, enableProfiling bool, errCh cha fmt.Fprintf(w, "%s", proxyMode) }) - //lint:ignore SA1019 See the Metrics Stability Migration KEP - //nolint:staticcheck + //nolint:staticcheck // SA1019 See the Metrics Stability Migration KEP proxyMux.Handle("/metrics", legacyregistry.Handler()) if enableProfiling { diff --git a/cmd/kube-scheduler/app/config/config.go b/cmd/kube-scheduler/app/config/config.go index 91fbf44164e..927a71b21b9 100644 --- a/cmd/kube-scheduler/app/config/config.go +++ b/cmd/kube-scheduler/app/config/config.go @@ -44,8 +44,7 @@ type Config struct { InformerFactory informers.SharedInformerFactory DynInformerFactory dynamicinformer.DynamicSharedInformerFactory - //lint:ignore SA1019 this deprecated field still needs to be used for now. It will be removed once the migration is done. - //nolint:staticcheck + //nolint:staticcheck // SA1019 this deprecated field still needs to be used for now. It will be removed once the migration is done. EventBroadcaster events.EventBroadcasterAdapter // LeaderElection is optional. diff --git a/pkg/kubelet/dockershim/docker_container.go b/pkg/kubelet/dockershim/docker_container.go index 7f5fb7c79c5..8cc686d9885 100644 --- a/pkg/kubelet/dockershim/docker_container.go +++ b/pkg/kubelet/dockershim/docker_container.go @@ -181,8 +181,7 @@ func (ds *dockerService) CreateContainer(_ context.Context, r *runtimeapi.Create } hc.Resources.Devices = devices - //lint:ignore SA1019 backwards compatibility - //nolint:staticcheck + //nolint:staticcheck // SA1019 backwards compatibility securityOpts, err := ds.getSecurityOpts(config.GetLinux().GetSecurityContext().GetSeccompProfilePath(), securityOptSeparator) if err != nil { return nil, fmt.Errorf("failed to generate security options for container %q: %v", config.Metadata.Name, err) diff --git a/pkg/kubelet/server/server.go b/pkg/kubelet/server/server.go index 9312dfd49c6..28dfc44977c 100644 --- a/pkg/kubelet/server/server.go +++ b/pkg/kubelet/server/server.go @@ -353,8 +353,7 @@ func (s *Server) InstallDefaultHandlers() { s.addMetricsBucketMatcher("metrics/cadvisor") s.addMetricsBucketMatcher("metrics/probes") s.addMetricsBucketMatcher("metrics/resource") - //lint:ignore SA1019 https://github.com/kubernetes/enhancements/issues/1206 - //nolint:staticcheck + //nolint:staticcheck // SA1019 https://github.com/kubernetes/enhancements/issues/1206 s.restfulCont.Handle(metricsPath, legacyregistry.Handler()) // cAdvisor metrics are exposed under the secured handler as well diff --git a/pkg/registry/core/namespace/storage/storage.go b/pkg/registry/core/namespace/storage/storage.go index 55bcbcc7dd1..a453d43f75e 100644 --- a/pkg/registry/core/namespace/storage/storage.go +++ b/pkg/registry/core/namespace/storage/storage.go @@ -253,11 +253,8 @@ func ShouldDeleteNamespaceDuringUpdate(ctx context.Context, key string, obj, exi } func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalizer bool) bool { - //lint:ignore SA1019 backwards compatibility - //nolint:staticcheck + //nolint:staticcheck // SA1019 backwards compatibility if options.OrphanDependents != nil { - //lint:ignore SA1019 backwards compatibility - //nolint:staticcheck return *options.OrphanDependents } if options.PropagationPolicy != nil { @@ -267,10 +264,8 @@ func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalize } func shouldHaveDeleteDependentsFinalizer(options *metav1.DeleteOptions, haveDeleteDependentsFinalizer bool) bool { - //lint:ignore SA1019 backwards compatibility - //nolint:staticcheck + //nolint:staticcheck // SA1019 backwards compatibility if options.OrphanDependents != nil { - //lint:ignore SA1019 backwards compatibility return *options.OrphanDependents == false } if options.PropagationPolicy != nil { diff --git a/pkg/volume/util/fsquota/quota_linux.go b/pkg/volume/util/fsquota/quota_linux.go index 68e9c9e1a8a..85784204aa1 100644 --- a/pkg/volume/util/fsquota/quota_linux.go +++ b/pkg/volume/util/fsquota/quota_linux.go @@ -304,8 +304,7 @@ func SupportsQuotas(m mount.Interface, path string) (bool, error) { // AssignQuota chooses the quota ID based on the pod UID and path. // If the pod UID is identical to another one known, it may (but presently // doesn't) choose the same quota ID as other volumes in the pod. -//lint:ignore SA4009 poduid is overwritten by design, see comment below -func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { //nolint:staticcheck +func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { //nolint:staticcheck // SA4009 poduid is overwritten by design, see comment below if bytes == nil { return fmt.Errorf("attempting to assign null quota to %s", path) } @@ -320,7 +319,7 @@ func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resour // volumes in a pod, we can simply remove this line of code. // If and when we decide permanently that we're going to adopt // one quota per volume, we can rip all of the pod code out. - poduid = types.UID(uuid.NewUUID()) //nolint:staticcheck + poduid = types.UID(uuid.NewUUID()) //nolint:staticcheck // SA4009 poduid is overwritten by design, see comment above if pod, ok := dirPodMap[path]; ok && pod != poduid { return fmt.Errorf("requesting quota on existing directory %s but different pod %s %s", path, pod, poduid) } diff --git a/test/integration/garbagecollector/garbage_collector_test.go b/test/integration/garbagecollector/garbage_collector_test.go index 12f432d8846..1b633da03a2 100644 --- a/test/integration/garbagecollector/garbage_collector_test.go +++ b/test/integration/garbagecollector/garbage_collector_test.go @@ -598,13 +598,12 @@ func setupRCsPods(t *testing.T, gc *garbagecollector.GarbageCollector, clientSet } orphan := false switch { - //lint:file-ignore SA1019 Keep testing deprecated OrphanDependents option until it's being removed - case options.OrphanDependents == nil && options.PropagationPolicy == nil && len(initialFinalizers) == 0: //nolint:staticcheck + case options.OrphanDependents == nil && options.PropagationPolicy == nil && len(initialFinalizers) == 0: //nolint:staticcheck // SA1019 Keep testing deprecated OrphanDependents option until it's being removed // if there are no deletion options, the default policy for replication controllers is orphan orphan = true - case options.OrphanDependents != nil: //nolint:staticcheck + case options.OrphanDependents != nil: //nolint:staticcheck // SA1019 Keep testing deprecated OrphanDependents option until it's being removed // if the deletion options explicitly specify whether to orphan, that controls - orphan = *options.OrphanDependents //nolint:staticcheck + orphan = *options.OrphanDependents //nolint:staticcheck // SA1019 Keep testing deprecated OrphanDependents option until it's being removed case options.PropagationPolicy != nil: // if the deletion options explicitly specify whether to orphan, that controls orphan = *options.PropagationPolicy == metav1.DeletePropagationOrphan diff --git a/test/integration/scheduler_perf/scheduler_perf_legacy_test.go b/test/integration/scheduler_perf/scheduler_perf_legacy_test.go index 2ee024bb162..7a8a2810cce 100644 --- a/test/integration/scheduler_perf/scheduler_perf_legacy_test.go +++ b/test/integration/scheduler_perf/scheduler_perf_legacy_test.go @@ -439,8 +439,7 @@ func benchmarkScheduling(numExistingPods, minPods int, testPodStrategy testutils.TestPodCreateStrategy, b *testing.B) { if b.N < minPods { - //lint:ignore SA3001 Set a minimum for b.N to get more meaningful results - b.N = minPods //nolint:staticcheck + b.N = minPods //nolint:staticcheck // SA3001 Set a minimum for b.N to get more meaningful results } finalFunc, podInformer, clientset, _ := mustSetupScheduler(nil) defer finalFunc() From 69d029bddbd046d1ce79a99a6d6d39d03d137cde Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Tue, 20 Jul 2021 22:36:17 -0400 Subject: [PATCH 13/40] Add syncTicker.Stop() --- pkg/kubelet/status/status_manager.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pkg/kubelet/status/status_manager.go b/pkg/kubelet/status/status_manager.go index 7ec6d2b51a8..bd3b58b1c36 100644 --- a/pkg/kubelet/status/status_manager.go +++ b/pkg/kubelet/status/status_manager.go @@ -157,9 +157,10 @@ func (m *manager) Start() { } klog.InfoS("Starting to sync pod status with apiserver") - syncTicker := time.NewTicker(syncPeriod).C + syncTicker := time.NewTicker(syncPeriod) // syncPod and syncBatch share the same go routine to avoid sync races. go wait.Forever(func() { + defer syncTicker.Stop() for { select { case syncRequest := <-m.podStatusChannel: @@ -168,7 +169,7 @@ func (m *manager) Start() { "statusVersion", syncRequest.status.version, "status", syncRequest.status.status) m.syncPod(syncRequest.podUID, syncRequest.status) - case <-syncTicker: + case <-syncTicker.C: klog.V(5).InfoS("Status Manager: syncing batch") // remove any entries in the status channel since the batch will handle them for i := len(m.podStatusChannel); i > 0; i-- { From e78b3e8dfed0a03ea83106d5a624e98e7300c3cd Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Wed, 3 Nov 2021 19:41:25 -0400 Subject: [PATCH 14/40] Use nolint directive instead of stopping ticker, per liggit's suggestion --- pkg/kubelet/status/status_manager.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pkg/kubelet/status/status_manager.go b/pkg/kubelet/status/status_manager.go index bd3b58b1c36..051f0edda90 100644 --- a/pkg/kubelet/status/status_manager.go +++ b/pkg/kubelet/status/status_manager.go @@ -157,10 +157,12 @@ func (m *manager) Start() { } klog.InfoS("Starting to sync pod status with apiserver") - syncTicker := time.NewTicker(syncPeriod) + + //nolint:staticcheck // SA1015 Ticker can leak since this is only called once and doesn't handle termination. + syncTicker := time.NewTicker(syncPeriod).C + // syncPod and syncBatch share the same go routine to avoid sync races. go wait.Forever(func() { - defer syncTicker.Stop() for { select { case syncRequest := <-m.podStatusChannel: @@ -169,7 +171,7 @@ func (m *manager) Start() { "statusVersion", syncRequest.status.version, "status", syncRequest.status.status) m.syncPod(syncRequest.podUID, syncRequest.status) - case <-syncTicker.C: + case <-syncTicker: klog.V(5).InfoS("Status Manager: syncing batch") // remove any entries in the status channel since the batch will handle them for i := len(m.podStatusChannel); i > 0; i-- { From 3bca4e6d6776a0f325afb746a9143744c984b62b Mon Sep 17 00:00:00 2001 From: Tim Hockin Date: Wed, 10 Nov 2021 12:09:52 -0800 Subject: [PATCH 15/40] Move golangci-lint config to a file Make verify-golangci-lint.sh work across modules and take an optional argument for a package. --- .golangci.yaml | 18 ++++++++++++++++++ hack/verify-golangci-lint.sh | 19 +++++++++++-------- 2 files changed, 29 insertions(+), 8 deletions(-) create mode 100644 .golangci.yaml diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 00000000000..208f72be982 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,18 @@ +run: + timeout: 30m + skip-files: + - "^zz_generated.*" + +issues: + max-same-issues: 0 + +linters: + disable-all: true + enable: # please keep this alphabetized + - deadcode + - ineffassign + - unused + - varcheck +linters-settings: # please keep this alphabetized + unused: + go: "1.17" diff --git a/hack/verify-golangci-lint.sh b/hack/verify-golangci-lint.sh index 237352b678f..decaca0d56b 100755 --- a/hack/verify-golangci-lint.sh +++ b/hack/verify-golangci-lint.sh @@ -43,12 +43,15 @@ popd >/dev/null cd "${KUBE_ROOT}" +# The config is in ${KUBE_ROOT}/.golangci.yaml echo 'running golangci-lint ' -golangci-lint run \ - --timeout 30m \ - --disable-all \ - -E deadcode \ - -E unused \ - -E varcheck \ - -E ineffassign \ - -E staticcheck +if [[ "$#" > 0 ]]; then + golangci-lint run "$@" +else + golangci-lint run ./... + for d in staging/src/k8s.io/*; do + pushd ./vendor/k8s.io/$(basename "$d") >/dev/null + golangci-lint run ./... + popd >/dev/null + done +fi From e986d725754e6a1a8ae15b9978bd1ccb2fabcf20 Mon Sep 17 00:00:00 2001 From: Tim Hockin Date: Wed, 10 Nov 2021 12:13:53 -0800 Subject: [PATCH 16/40] Add staticcheck to .golangci.yaml TODO: port options from verify-staticcheck.sh and delete it --- .golangci.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.golangci.yaml b/.golangci.yaml index 208f72be982..9a119d1ef00 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -11,8 +11,12 @@ linters: enable: # please keep this alphabetized - deadcode - ineffassign + - staticcheck - unused - varcheck linters-settings: # please keep this alphabetized + staticcheck: + go: "1.17" + checks: [ "all" ] unused: go: "1.17" From ca7cfb75d001e7f86ceef7720a6b11855e10439b Mon Sep 17 00:00:00 2001 From: Hanna Lee Date: Wed, 10 Nov 2021 21:17:25 -0500 Subject: [PATCH 17/40] Copy in options from now-deleted hack/verify-staticcheck.sh script --- .golangci.yaml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.golangci.yaml b/.golangci.yaml index 9a119d1ef00..831312a45c8 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -17,6 +17,15 @@ linters: linters-settings: # please keep this alphabetized staticcheck: go: "1.17" - checks: [ "all" ] + checks: [ + "all", + "-S1*", # Omit code simplifications for now. + "-ST1*", # Mostly stylistic, redundant w/ golint + "-SA5011" # Possible nil pointer dereference + ] + ignore_pattern: [ + "vendor/k8s.io/kubectl/pkg/cmd/edit/testdata", # golang/go#24854, dominikh/go-tools#565 + "cluster/addons/fluentd-elasticsearch/es-image" # cannot traverse go modules + ] unused: go: "1.17" From 86e197991acc1159f591e3d31da6bab5d34fcde6 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 16:56:41 +0100 Subject: [PATCH 18/40] fix golangci-lint config file using exclude-rules golangci configuration file disable soon to be deprecated golangci linters remove useless comments on golangci config --- .golangci.yaml | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 831312a45c8..b47dc9da4f2 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -5,27 +5,35 @@ run: issues: max-same-issues: 0 + # Excluding configuration per-path, per-linter, per-text and per-source + exclude-rules: + # exclude ineffassing linter for generated files for conversion + - path: conversion\.go + linters: + - ineffassign linters: disable-all: true enable: # please keep this alphabetized - - deadcode + # Don't use soon to deprecated[1] linters that lead to false + # https://github.com/golangci/golangci-lint/issues/1841 + # - deadcode + # - structcheck + # - varcheck - ineffassign - staticcheck - unused - - varcheck + linters-settings: # please keep this alphabetized staticcheck: go: "1.17" checks: [ "all", - "-S1*", # Omit code simplifications for now. - "-ST1*", # Mostly stylistic, redundant w/ golint - "-SA5011" # Possible nil pointer dereference - ] - ignore_pattern: [ - "vendor/k8s.io/kubectl/pkg/cmd/edit/testdata", # golang/go#24854, dominikh/go-tools#565 - "cluster/addons/fluentd-elasticsearch/es-image" # cannot traverse go modules + "-S1*", # TODO(fix) Omit code simplifications for now. + "-ST1*", # Mostly stylistic, redundant w/ golint + "-SA5011", # TODO(fix) Possible nil pointer dereference + "-SA1019", # TODO(fix) Using a deprecated function, variable, constant or field + "-SA2002" # TODO(fix) Called testing.T.FailNow or SkipNow in a goroutine, which isn’t allowed ] unused: go: "1.17" From 272b31da508b39c1cfdbf0398c43ec4d69dceec7 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 16:57:21 +0100 Subject: [PATCH 19/40] use golangci-lint and remove legacy verify-staticcheck.sh --- hack/verify-golangci-lint.sh | 35 +++++-- hack/verify-staticcheck.sh | 177 ----------------------------------- 2 files changed, 29 insertions(+), 183 deletions(-) delete mode 100755 hack/verify-staticcheck.sh diff --git a/hack/verify-golangci-lint.sh b/hack/verify-golangci-lint.sh index decaca0d56b..19fc66d2603 100755 --- a/hack/verify-golangci-lint.sh +++ b/hack/verify-golangci-lint.sh @@ -44,14 +44,37 @@ popd >/dev/null cd "${KUBE_ROOT}" # The config is in ${KUBE_ROOT}/.golangci.yaml -echo 'running golangci-lint ' -if [[ "$#" > 0 ]]; then - golangci-lint run "$@" +echo 'running golangci-lint ' >&2 +res=0 +if [[ "$#" -gt 0 ]]; then + golangci-lint run "$@" >&2 || res=$? else - golangci-lint run ./... + golangci-lint run ./... >&2 || res=$? for d in staging/src/k8s.io/*; do - pushd ./vendor/k8s.io/$(basename "$d") >/dev/null - golangci-lint run ./... + MODPATH="staging/src/k8s.io/$(basename "${d}")" + echo "running golangci-lint for ${KUBE_ROOT}/${MODPATH}" + pushd "${KUBE_ROOT}/${MODPATH}" >/dev/null + golangci-lint --path-prefix "${MODPATH}" run ./... >&2 || res=$? popd >/dev/null done fi + +# print a message based on the result +if [ "$res" -eq 0 ]; then + echo 'Congratulations! All files are passing lint :-)' +else + { + echo + echo 'Please review the above warnings. You can test via "./hack/verify-golangci-lint.sh"' + echo 'If the above warnings do not make sense, you can exempt this warning with a comment' + echo ' (if your reviewer is okay with it).' + echo 'In general please prefer to fix the error, we have already disabled specific lints' + echo ' that the project chooses to ignore.' + echo 'See: https://golangci-lint.run/usage/false-positives/' + echo + } >&2 + exit 1 +fi + +# preserve the result +exit "$res" diff --git a/hack/verify-staticcheck.sh b/hack/verify-staticcheck.sh deleted file mode 100755 index 4839f8029d1..00000000000 --- a/hack/verify-staticcheck.sh +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2014 The Kubernetes Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This script lints each package by `staticcheck`. -# Usage: `hack/verify-staticcheck.sh`. -# NOTE: To ignore issues detected a package, add it to the -# `.staticcheck_failures` blacklist. - -set -o errexit -set -o nounset -set -o pipefail - -KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/.. -source "${KUBE_ROOT}/hack/lib/init.sh" -source "${KUBE_ROOT}/hack/lib/util.sh" - -kube::golang::verify_go_version - -FOCUS="${1:-}" -FOCUS="${FOCUS%/}" # Remove the ending "/" - -# See https://staticcheck.io/docs/checks -CHECKS=( - "all" - "-S1*" # Omit code simplifications for now. - "-ST1*" # Mostly stylistic, redundant w/ golint - "-SA5011" # Possible nil pointer dereference -) -export IFS=','; checks="${CHECKS[*]}"; unset IFS - -# Packages to ignore due to bugs in staticcheck -# NOTE: To ignore issues detected a package, add it to the .staticcheck_failures blacklist -IGNORE=( - "vendor/k8s.io/kubectl/pkg/cmd/edit/testdata" # golang/go#24854, dominikh/go-tools#565 - "cluster/addons/fluentd-elasticsearch/es-image" # cannot traverse go modules -) -export IFS='|'; ignore_pattern="^(${IGNORE[*]})\$"; unset IFS - -# Ensure that we find the binaries we build before anything else. -export GOBIN="${KUBE_OUTPUT_BINPATH}" -PATH="${GOBIN}:${PATH}" - -# Install staticcheck -pushd "${KUBE_ROOT}/hack/tools" >/dev/null - GO111MODULE=on go install honnef.co/go/tools/cmd/staticcheck -popd >/dev/null - -cd "${KUBE_ROOT}" - -# Check that the file is in alphabetical order -failure_file="${KUBE_ROOT}/hack/.staticcheck_failures" -kube::util::check-file-in-alphabetical-order "${failure_file}" - -function normalize_package() { - pkg="${1}" - if [[ "${pkg}" == "vendor/"* || "${pkg}" == "k8s.io/"* ]]; then - # Treat this as a full package path (stripping vendor prefix if needed) - echo "${pkg#"vendor/"}" - else - # Treat this as a relative package path to k8s.io/kubernetes - echo "./${pkg}" - fi -} - -all_packages=() -while IFS='' read -r line; do - line=$(normalize_package "${line}") - all_packages+=("${line}") -done < <( hack/make-rules/helpers/cache_go_dirs.sh "${KUBE_ROOT}/_tmp/all_go_dirs" | - grep "^${FOCUS:-.}" | - grep -vE "(third_party|generated|clientset_generated|hack|testdata|/_)" | - grep -vE "$ignore_pattern" ) - -failing_packages=() -if [[ -z $FOCUS ]]; then # Ignore failing_packages in FOCUS mode - while IFS='' read -r line; do failing_packages+=("$line"); done < <(cat "$failure_file") -fi -errors=() -not_failing=() - -while read -r error; do - # Ignore compile errors caused by lack of files due to build tags. - # TODO: Add verification for these directories. - ignore_no_files="^-: build constraints exclude all Go files in .* \(compile\)" - if [[ $error =~ $ignore_no_files ]]; then - continue - fi - - # Ignore the errors caused by the generated files - ignore_gen_files=".*/zz_generated\.[a-z]+\.go:.*" - if [[ $error =~ $ignore_gen_files ]]; then - continue - fi - - file="${error%%:*}" - pkg="$(dirname "$file")" - kube::util::array_contains "$pkg" "${failing_packages[@]}" && in_failing=$? || in_failing=$? - if [[ "${in_failing}" -ne "0" ]]; then - errors+=( "${error}" ) - elif [[ "${in_failing}" -eq "0" ]]; then - really_failing+=( "$pkg" ) - fi -done < <(GO111MODULE=on GOOS=linux staticcheck -checks "${checks}" "${all_packages[@]}" 2>/dev/null || true) - -export IFS=$'\n' # Expand ${really_failing[*]} to separate lines -kube::util::read-array really_failing < <(sort -u <<<"${really_failing[*]}") -unset IFS -for pkg in "${failing_packages[@]}"; do - if ! kube::util::array_contains "$pkg" "${really_failing[@]}"; then - not_failing+=( "$pkg" ) - fi -done - -# Check that all failing_packages actually still exist -gone=() -for p in "${failing_packages[@]}"; do - p=$(normalize_package "${p}") - if ! kube::util::array_contains "${p}" "${all_packages[@]}"; then - gone+=( "${p}" ) - fi -done - -# Check to be sure all the packages that should pass check are. -if [ ${#errors[@]} -eq 0 ]; then - echo 'Congratulations! All Go source files have passed staticcheck.' -else - { - echo "Errors from staticcheck:" - for err in "${errors[@]}"; do - echo "$err" - done - echo - echo 'Please review the above warnings. You can test via:' - echo ' hack/verify-staticcheck.sh ' - echo 'If the above warnings do not make sense, you can exempt the line or file. See:' - echo ' https://staticcheck.io/docs/#ignoring-problems' - echo - } >&2 - exit 1 -fi - -if [[ ${#not_failing[@]} -gt 0 ]]; then - { - echo "Some packages in hack/.staticcheck_failures are passing staticcheck. Please remove them." - echo - for p in "${not_failing[@]}"; do - echo " $p" - done - echo - } >&2 - exit 1 -fi - -if [[ ${#gone[@]} -gt 0 ]]; then - { - echo "Some packages in hack/.staticcheck_failures do not exist anymore. Please remove them." - echo - for p in "${gone[@]}"; do - echo " $p" - done - echo - } >&2 - exit 1 -fi From d126b1483840b5ea7c0891d3e7a693bd50fae7f8 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 16:57:58 +0100 Subject: [PATCH 20/40] migrate nolint coments to golangci-lint --- pkg/kubelet/cm/cpumanager/state/checkpoint.go | 2 +- pkg/kubelet/cm/cpumanager/state/state_checkpoint.go | 2 +- pkg/kubelet/cm/memorymanager/state/checkpoint.go | 2 +- pkg/kubelet/cm/memorymanager/state/state_checkpoint.go | 2 +- pkg/kubelet/stats/cri_stats_provider.go | 3 +-- pkg/registry/batch/job/storage/storage.go | 6 +++--- pkg/util/coverage/fake_test_deps.go | 10 +++++++++- .../pkg/apiserver/schema/pruning/algorithm_test.go | 2 +- .../pkg/api/apitesting/roundtrip/roundtrip.go | 2 +- .../k8s.io/apimachinery/pkg/labels/selector_test.go | 2 +- .../src/k8s.io/apimachinery/pkg/util/framer/framer.go | 6 +++--- .../pkg/util/httpstream/spdy/roundtripper.go | 4 ++-- .../k8s.io/apiserver/pkg/endpoints/handlers/delete.go | 2 +- .../handlers/fieldmanager/fieldmanager_test.go | 2 +- .../endpoints/handlers/responsewriters/errors_test.go | 2 +- .../apiserver/pkg/endpoints/responsewriter/wrapper.go | 2 +- .../pkg/endpoints/responsewriter/wrapper_test.go | 8 ++++---- .../apiserver/pkg/registry/generic/registry/store.go | 6 +++--- .../src/k8s.io/client-go/discovery/discovery_client.go | 2 +- .../component-base/metrics/legacyregistry/registry.go | 4 ++-- staging/src/k8s.io/controller-manager/app/serve.go | 2 +- test/images/agnhost/net/nat/closewait.go | 2 +- 22 files changed, 41 insertions(+), 34 deletions(-) diff --git a/pkg/kubelet/cm/cpumanager/state/checkpoint.go b/pkg/kubelet/cm/cpumanager/state/checkpoint.go index e7df594efc5..ca6d2fc90a3 100644 --- a/pkg/kubelet/cm/cpumanager/state/checkpoint.go +++ b/pkg/kubelet/cm/cpumanager/state/checkpoint.go @@ -53,7 +53,7 @@ type CPUManagerCheckpointV2 = CPUManagerCheckpoint // NewCPUManagerCheckpoint returns an instance of Checkpoint func NewCPUManagerCheckpoint() *CPUManagerCheckpoint { - //lint:ignore unexported-type-in-api user-facing error message + //nolint:staticcheck // unexported-type-in-api user-facing error message return newCPUManagerCheckpointV2() } diff --git a/pkg/kubelet/cm/cpumanager/state/state_checkpoint.go b/pkg/kubelet/cm/cpumanager/state/state_checkpoint.go index f501c2bea30..c9aacd19051 100644 --- a/pkg/kubelet/cm/cpumanager/state/state_checkpoint.go +++ b/pkg/kubelet/cm/cpumanager/state/state_checkpoint.go @@ -54,7 +54,7 @@ func NewCheckpointState(stateDir, checkpointName, policyName string, initialCont } if err := stateCheckpoint.restoreState(); err != nil { - //lint:ignore ST1005 user-facing error message + //nolint:staticcheck // ST1005 user-facing error message return nil, fmt.Errorf("could not restore state from checkpoint: %v, please drain this node and delete the CPU manager checkpoint file %q before restarting Kubelet", err, path.Join(stateDir, checkpointName)) } diff --git a/pkg/kubelet/cm/memorymanager/state/checkpoint.go b/pkg/kubelet/cm/memorymanager/state/checkpoint.go index a43b40272e0..93b1302baa1 100644 --- a/pkg/kubelet/cm/memorymanager/state/checkpoint.go +++ b/pkg/kubelet/cm/memorymanager/state/checkpoint.go @@ -35,7 +35,7 @@ type MemoryManagerCheckpoint struct { // NewMemoryManagerCheckpoint returns an instance of Checkpoint func NewMemoryManagerCheckpoint() *MemoryManagerCheckpoint { - //lint:ignore unexported-type-in-api user-facing error message + //nolint:staticcheck // unexported-type-in-api user-facing error message return &MemoryManagerCheckpoint{ Entries: ContainerMemoryAssignments{}, MachineState: NUMANodeMap{}, diff --git a/pkg/kubelet/cm/memorymanager/state/state_checkpoint.go b/pkg/kubelet/cm/memorymanager/state/state_checkpoint.go index 3607234094b..286b9fda819 100644 --- a/pkg/kubelet/cm/memorymanager/state/state_checkpoint.go +++ b/pkg/kubelet/cm/memorymanager/state/state_checkpoint.go @@ -50,7 +50,7 @@ func NewCheckpointState(stateDir, checkpointName, policyName string) (State, err } if err := stateCheckpoint.restoreState(); err != nil { - //lint:ignore ST1005 user-facing error message + //nolint:staticcheck // ST1005 user-facing error message return nil, fmt.Errorf("could not restore state from checkpoint: %v, please drain this node and delete the memory manager checkpoint file %q before restarting Kubelet", err, path.Join(stateDir, checkpointName)) } diff --git a/pkg/kubelet/stats/cri_stats_provider.go b/pkg/kubelet/stats/cri_stats_provider.go index 10fe4d55b33..3690e0c09af 100644 --- a/pkg/kubelet/stats/cri_stats_provider.go +++ b/pkg/kubelet/stats/cri_stats_provider.go @@ -68,9 +68,8 @@ type criStatsProvider struct { imageService internalapi.ImageManagerService // hostStatsProvider is used to get the status of the host filesystem consumed by pods. hostStatsProvider HostStatsProvider - //lint:ignore U1000 We can't import hcsshim due to Build constraints in hcsshim // windowsNetworkStatsProvider is used by kubelet to gather networking stats on Windows - windowsNetworkStatsProvider interface{} + windowsNetworkStatsProvider interface{} //nolint:unused // U1000 We can't import hcsshim due to Build constraints in hcsshim // clock is used report current time clock clock.Clock diff --git a/pkg/registry/batch/job/storage/storage.go b/pkg/registry/batch/job/storage/storage.go index 2fdb108158f..e87b1bc0a8e 100644 --- a/pkg/registry/batch/job/storage/storage.go +++ b/pkg/registry/batch/job/storage/storage.go @@ -18,6 +18,7 @@ package storage import ( "context" + "k8s.io/apimachinery/pkg/apis/meta/internalversion" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -96,7 +97,7 @@ func (r *REST) Categories() []string { } func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility //nolint: staticcheck if options != nil && options.PropagationPolicy == nil && options.OrphanDependents == nil && job.Strategy.DefaultGarbageCollectionPolicy(ctx) == rest.OrphanDependents { @@ -108,8 +109,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va } func (r *REST) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, deleteOptions *metav1.DeleteOptions, listOptions *internalversion.ListOptions) (runtime.Object, error) { - //lint:ignore SA1019 backwards compatibility - //nolint: staticcheck + //nolint:staticcheck // SA1019 backwards compatibility if deleteOptions.PropagationPolicy == nil && deleteOptions.OrphanDependents == nil && job.Strategy.DefaultGarbageCollectionPolicy(ctx) == rest.OrphanDependents { // Throw a warning if delete options are not explicitly set as Job deletion strategy by default is orphaning diff --git a/pkg/util/coverage/fake_test_deps.go b/pkg/util/coverage/fake_test_deps.go index a03fc9171e3..a9506d4c77f 100644 --- a/pkg/util/coverage/fake_test_deps.go +++ b/pkg/util/coverage/fake_test_deps.go @@ -23,33 +23,41 @@ import ( // This is an implementation of testing.testDeps. It doesn't need to do anything, because // no tests are actually run. It does need a concrete implementation of at least ImportPath, // which is called unconditionally when running tests. -//lint:ignore U1000 see comment above, we know it's unused normally. +//nolint:unused // U1000 see comment above, we know it's unused normally. type fakeTestDeps struct{} +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) ImportPath() string { return "" } +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) MatchString(pat, str string) (bool, error) { return false, nil } +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) StartCPUProfile(io.Writer) error { return nil } +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) StopCPUProfile() {} +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) StartTestLog(io.Writer) {} +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) StopTestLog() error { return nil } +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) WriteHeapProfile(io.Writer) error { return nil } +//nolint:unused // U1000 see comment above, we know it's unused normally. func (fakeTestDeps) WriteProfileTo(string, io.Writer, int) error { return nil } diff --git a/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm_test.go b/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm_test.go index b7b5ec7604d..403d25e21a9 100644 --- a/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm_test.go +++ b/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm_test.go @@ -636,7 +636,7 @@ func BenchmarkDeepCopy(b *testing.B) { b.StartTimer() for i := 0; i < b.N; i++ { - //lint:ignore SA4010 the result of append is never used, it's acceptable since in benchmark testing. + //nolint:staticcheck //iccheck // SA4010 the result of append is never used, it's acceptable since in benchmark testing. instances = append(instances, runtime.DeepCopyJSON(obj)) } } diff --git a/staging/src/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go b/staging/src/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go index 0c320e578b9..2502c98b722 100644 --- a/staging/src/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go +++ b/staging/src/k8s.io/apimachinery/pkg/api/apitesting/roundtrip/roundtrip.go @@ -25,7 +25,7 @@ import ( "testing" "github.com/davecgh/go-spew/spew" - //lint:ignore SA1019 Keep using deprecated module; it still seems to be maintained and the api of the recommended replacement differs + //nolint:staticcheck //iccheck // SA1019 Keep using deprecated module; it still seems to be maintained and the api of the recommended replacement differs "github.com/golang/protobuf/proto" fuzz "github.com/google/gofuzz" flag "github.com/spf13/pflag" diff --git a/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go b/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go index 7c061462dd5..37e50345420 100644 --- a/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go @@ -148,7 +148,7 @@ func expectMatchDirect(t *testing.T, selector, ls Set) { } } -//lint:ignore U1000 currently commented out in TODO of TestSetMatches +//nolint:staticcheck //iccheck // U1000 currently commented out in TODO of TestSetMatches //nolint:unused,deadcode func expectNoMatchDirect(t *testing.T, selector, ls Set) { if SelectorFromSet(selector).Matches(ls) { diff --git a/staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go b/staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go index 45aa74bf582..10df0d99cd5 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go @@ -132,14 +132,14 @@ func (r *jsonFrameReader) Read(data []byte) (int, error) { // Return whatever remaining data exists from an in progress frame if n := len(r.remaining); n > 0 { if n <= len(data) { - //lint:ignore SA4006,SA4010 underlying array of data is modified here. + //nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here. data = append(data[0:0], r.remaining...) r.remaining = nil return n, nil } n = len(data) - //lint:ignore SA4006,SA4010 underlying array of data is modified here. + //nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here. data = append(data[0:0], r.remaining[:n]...) r.remaining = r.remaining[n:] return n, io.ErrShortBuffer @@ -157,7 +157,7 @@ func (r *jsonFrameReader) Read(data []byte) (int, error) { // and set m to it, which means we need to copy the partial result back into data and preserve // the remaining result for subsequent reads. if len(m) > n { - //lint:ignore SA4006,SA4010 underlying array of data is modified here. + //nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here. data = append(data[0:0], m[:n]...) r.remaining = m[n:] return n, io.ErrShortBuffer diff --git a/staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go b/staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go index b8e329571ee..086e4bcf0b9 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go @@ -183,10 +183,10 @@ func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { return nil, err } - //lint:ignore SA1019 ignore deprecated httputil.NewProxyClientConn + //nolint:staticcheck // SA1019 ignore deprecated httputil.NewProxyClientConn proxyClientConn := httputil.NewProxyClientConn(proxyDialConn, nil) _, err = proxyClientConn.Do(&proxyReq) - //lint:ignore SA1019 ignore deprecated httputil.ErrPersistEOF: it might be + //nolint:staticcheck // SA1019 ignore deprecated httputil.ErrPersistEOF: it might be // returned from the invocation of proxyClientConn.Do if err != nil && err != httputil.ErrPersistEOF { return nil, err diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go index e58495bed27..05ccd393087 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go @@ -143,7 +143,7 @@ func DeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope *RequestSc // that will break existing clients. // Other cases where resource is not instantly deleted are: namespace deletion // and pod graceful deletion. - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility //nolint: staticcheck if !wasDeleted && options.OrphanDependents != nil && !*options.OrphanDependents { status = http.StatusAccepted diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go index aaf86cec0ac..a627a25a4d2 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go @@ -55,7 +55,7 @@ type fakeObjectConvertor struct { apiVersion fieldpath.APIVersion } -//lint:ignore SA4009 backwards compatibility +//nolint:staticcheck // SA4009 backwards compatibility func (c *fakeObjectConvertor) Convert(in, out, context interface{}) error { if typedValue, ok := in.(*typed.TypedValue); ok { var err error diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors_test.go index a772a136ee5..33231bd5e6b 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors_test.go @@ -83,7 +83,7 @@ func TestForbidden(t *testing.T) { if result != test.expected { t.Errorf("Forbidden response body(%#v...)\n expected: %v\ngot: %v", test.attributes, test.expected, result) } - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility resultType := observer.HeaderMap.Get("Content-Type") if resultType != test.contentType { t.Errorf("Forbidden content type(%#v...) != %#v, got %#v", test.attributes, test.expected, result) diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go b/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go index 46af09f7180..758e7addd28 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go @@ -120,7 +120,7 @@ func GetOriginal(w http.ResponseWriter) http.ResponseWriter { return GetOriginal(inner) } -//lint:ignore SA1019 backward compatibility +//nolint:staticcheck // SA1019 var _ http.CloseNotifier = outerWithCloseNotifyAndFlush{} var _ http.Flusher = outerWithCloseNotifyAndFlush{} var _ http.ResponseWriter = outerWithCloseNotifyAndFlush{} diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper_test.go index 9fd08c60d42..3c52e06cf23 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper_test.go @@ -61,7 +61,7 @@ func TestWithHTTP1(t *testing.T) { // so each decorator is expected to tick the count by one for each method. defer counterGot.assert(t, &counter{FlushInvoked: 3, CloseNotifyInvoked: 3, HijackInvoked: 3}) - //lint:ignore SA1019 backward compatibility + //nolint:staticcheck // SA1019 w.(http.CloseNotifier).CloseNotify() w.(http.Flusher).Flush() @@ -116,7 +116,7 @@ func TestWithHTTP2(t *testing.T) { // so each decorator is expected to tick the count by one for each method. defer counterGot.assert(t, &counter{FlushInvoked: 3, CloseNotifyInvoked: 3, HijackInvoked: 0}) - //lint:ignore SA1019 backward compatibility + //nolint:staticcheck // SA1019 w.(http.CloseNotifier).CloseNotify() w.(http.Flusher).Flush() @@ -242,7 +242,7 @@ func assertCloseNotifierFlusherHijacker(t *testing.T, hijackableExpected bool, w t.Errorf("Expected the http.ResponseWriter object to implement http.Flusher") } - //lint:ignore SA1019 backward compatibility + //nolint:staticcheck // SA1019 if _, ok := w.(http.CloseNotifier); !ok { t.Errorf("Expected the http.ResponseWriter object to implement http.CloseNotifier") } @@ -293,6 +293,6 @@ func (fw *fakeResponseWriterDecorator) CloseNotify() <-chan bool { if fw.counter != nil { fw.counter.CloseNotifyInvoked++ } - //lint:ignore SA1019 backward compatibility + //nolint:staticcheck // SA1019 return fw.ResponseWriter.(http.CloseNotifier).CloseNotify() } diff --git a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go index eead4e568d4..9897a295240 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go @@ -753,9 +753,9 @@ func shouldOrphanDependents(ctx context.Context, e *Store, accessor metav1.Objec } // An explicit policy was set at deletion time, that overrides everything - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility if options != nil && options.OrphanDependents != nil { - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility return *options.OrphanDependents } if options != nil && options.PropagationPolicy != nil { @@ -796,7 +796,7 @@ func shouldDeleteDependents(ctx context.Context, e *Store, accessor metav1.Objec } // If an explicit policy was set at deletion time, that overrides both - //lint:ignore SA1019 backwards compatibility + //nolint:staticcheck // SA1019 backwards compatibility if options != nil && options.OrphanDependents != nil { return false } diff --git a/staging/src/k8s.io/client-go/discovery/discovery_client.go b/staging/src/k8s.io/client-go/discovery/discovery_client.go index 96159ab7ab2..50e59c5d85c 100644 --- a/staging/src/k8s.io/client-go/discovery/discovery_client.go +++ b/staging/src/k8s.io/client-go/discovery/discovery_client.go @@ -27,7 +27,7 @@ import ( "sync" "time" - //lint:ignore SA1019 Keep using module since it's still being maintained and the api of google.golang.org/protobuf/proto differs + //nolint:staticcheck // SA1019 Keep using module since it's still being maintained and the api of google.golang.org/protobuf/proto differs "github.com/golang/protobuf/proto" openapi_v2 "github.com/googleapis/gnostic/openapiv2" diff --git a/staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go b/staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go index ff38953ba36..56a9dcae58b 100644 --- a/staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go +++ b/staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go @@ -44,9 +44,9 @@ var ( ) func init() { - //lint:ignore SA1019 - replacement function still calls prometheus.NewProcessCollector(). + //nolint:staticcheck // SA1019 - replacement function still calls prometheus.NewProcessCollector(). RawMustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{})) - //lint:ignore SA1019 - replacement function still calls prometheus.NewGoCollector(). + //nolint:staticcheck // SA1019 - replacement function still calls prometheus.NewGoCollector(). RawMustRegister(prometheus.NewGoCollector()) } diff --git a/staging/src/k8s.io/controller-manager/app/serve.go b/staging/src/k8s.io/controller-manager/app/serve.go index 2f0e995b605..ba1f465368c 100644 --- a/staging/src/k8s.io/controller-manager/app/serve.go +++ b/staging/src/k8s.io/controller-manager/app/serve.go @@ -66,7 +66,7 @@ func NewBaseHandler(c *componentbaseconfig.DebuggingConfiguration, healthzHandle routes.DebugFlags{}.Install(mux, "v", routes.StringFlagPutHandler(logs.GlogSetter)) } configz.InstallHandler(mux) - //lint:ignore SA1019 See the Metrics Stability Migration KEP + //nolint:staticcheck // SA1019 See the Metrics Stability Migration KEP mux.Handle("/metrics", legacyregistry.Handler()) return mux diff --git a/test/images/agnhost/net/nat/closewait.go b/test/images/agnhost/net/nat/closewait.go index 6bd1c7c93d2..5a344956e5c 100644 --- a/test/images/agnhost/net/nat/closewait.go +++ b/test/images/agnhost/net/nat/closewait.go @@ -38,7 +38,7 @@ import ( // leakedConnection is a global variable that should leak the active // connection assigned here. -//lint:ignore U1000 intentional unused variable +//nolint:unused // U1000 intentional unused variable var leakedConnection *net.TCPConn // CloseWaitServerOptions holds server JSON options. From 01a0fba3620c433f49120d82f908069281482a17 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 16:58:52 +0100 Subject: [PATCH 21/40] fix unassigned error on client-go test --- .../k8s.io/client-go/tools/clientcmd/loader_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/staging/src/k8s.io/client-go/tools/clientcmd/loader_test.go b/staging/src/k8s.io/client-go/tools/clientcmd/loader_test.go index 1e770e6767b..bebc7fea513 100644 --- a/staging/src/k8s.io/client-go/tools/clientcmd/loader_test.go +++ b/staging/src/k8s.io/client-go/tools/clientcmd/loader_test.go @@ -669,7 +669,9 @@ func Example_noMergingOnExplicitPaths() { } mergedConfig, err := loadingRules.Load() - + if err != nil { + fmt.Printf("Unexpected error: %v", err) + } json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) if err != nil { fmt.Printf("Unexpected error: %v", err) @@ -715,7 +717,9 @@ func Example_mergingSomeWithConflict() { } mergedConfig, err := loadingRules.Load() - + if err != nil { + fmt.Printf("Unexpected error: %v", err) + } json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) if err != nil { fmt.Printf("Unexpected error: %v", err) @@ -774,7 +778,9 @@ func Example_mergingEverythingNoConflicts() { } mergedConfig, err := loadingRules.Load() - + if err != nil { + fmt.Printf("Unexpected error: %v", err) + } json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) if err != nil { fmt.Printf("Unexpected error: %v", err) From fa3c4b953fb8192c60dcc3874bff8f9c12ffd54d Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 17:05:50 +0100 Subject: [PATCH 22/40] fix SA4005: ineffective assignment to field PatchMeta.patchStrategies (staticcheck) --- .../k8s.io/apimachinery/pkg/util/strategicpatch/meta.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go b/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go index c31de15e7aa..d49a56536c3 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go @@ -31,22 +31,22 @@ type PatchMeta struct { patchMergeKey string } -func (pm PatchMeta) GetPatchStrategies() []string { +func (pm *PatchMeta) GetPatchStrategies() []string { if pm.patchStrategies == nil { return []string{} } return pm.patchStrategies } -func (pm PatchMeta) SetPatchStrategies(ps []string) { +func (pm *PatchMeta) SetPatchStrategies(ps []string) { pm.patchStrategies = ps } -func (pm PatchMeta) GetPatchMergeKey() string { +func (pm *PatchMeta) GetPatchMergeKey() string { return pm.patchMergeKey } -func (pm PatchMeta) SetPatchMergeKey(pmk string) { +func (pm *PatchMeta) SetPatchMergeKey(pmk string) { pm.patchMergeKey = pmk } From d55af19c1b66d439e818533c5141ff2256b8e9d5 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 17:07:51 +0100 Subject: [PATCH 23/40] fix ineffectual assignment to diskName --- .../src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go index 99c0fb82122..834e3c200c1 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go @@ -268,7 +268,7 @@ func TestCreateDisk_MultiZone(t *testing.T) { nodeInformerSynced: func() bool { return true }, } - diskName := "disk" + var diskName string diskType := DiskTypeStandard const sizeGb int64 = 128 @@ -420,7 +420,7 @@ func TestDeleteDisk_DiffDiskMultiZone(t *testing.T) { nodeZones: createNodeZones(zonesWithNodes), nodeInformerSynced: func() bool { return true }, } - diskName := "disk" + var diskName string diskType := DiskTypeSSD const sizeGb int64 = 128 From a36517f9e79cff25f65fe9b60e1e897f79a2b501 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 17:09:05 +0100 Subject: [PATCH 24/40] nolint unused errLeaseFailed --- .../legacy-cloud-providers/azure/azure_controller_common.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go index 072c262a66e..6cce0139bfc 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go +++ b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go @@ -49,8 +49,8 @@ const ( // https://docs.microsoft.com/en-us/azure/virtual-machines/premium-storage-performance#disk-caching diskCachingLimit = 4096 // GiB - maxLUN = 64 // max number of LUNs per VM - errLeaseFailed = "AcquireDiskLeaseFailed" + maxLUN = 64 // max number of LUNs per VM + errLeaseFailed = "AcquireDiskLeaseFailed" //nolint:unused errLeaseIDMissing = "LeaseIdMissing" errContainerNotFound = "ContainerNotFound" errStatusCode400 = "statuscode=400" From b2971e74970f241e138c93f5e755aa2980ab13ed Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:08:27 +0100 Subject: [PATCH 25/40] fix ineffectual assignment to i (ineffassign) --- staging/src/k8s.io/kubectl/pkg/describe/describe.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/staging/src/k8s.io/kubectl/pkg/describe/describe.go b/staging/src/k8s.io/kubectl/pkg/describe/describe.go index 85da6819415..4469958507f 100644 --- a/staging/src/k8s.io/kubectl/pkg/describe/describe.go +++ b/staging/src/k8s.io/kubectl/pkg/describe/describe.go @@ -1415,7 +1415,6 @@ func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIn } else { w.Write(LEVEL_2, "%s\n", line) } - i++ } } @@ -5111,7 +5110,6 @@ func printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerI w.Write(LEVEL_0, "%s", innerIndent) } w.Write(LEVEL_0, "%s=%s\n", key, labels[key]) - i++ } } @@ -5345,7 +5343,6 @@ func printAnnotationsMultiline(w PrefixWriter, title string, annotations map[str } else { w.Write(LEVEL_0, "%s: %s\n", key, value) } - i++ } } From 31d45d000b83f982476d175a4e8a13d97cf95def Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:08:58 +0100 Subject: [PATCH 26/40] fix ineffectual assignment to base var --- .../apimachinery/pkg/runtime/serializer/streaming/streaming.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go b/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go index a60a7c04156..bdcbd91c016 100644 --- a/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go +++ b/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go @@ -90,7 +90,7 @@ func (d *decoder) Decode(defaults *schema.GroupVersionKind, into runtime.Object) } // must read the rest of the frame (until we stop getting ErrShortBuffer) d.resetRead = true - base = 0 + base = 0 //nolint:ineffassign return nil, nil, ErrObjectTooLarge } if err != nil { From 52c69ba7446c45910c0e083c793eea382b53a694 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:10:38 +0100 Subject: [PATCH 27/40] fix ineffectual assignment to name (ineffassign) --- .../code-generator/cmd/go-to-protobuf/protobuf/generator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go b/staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go index 6eff86bf7af..54df66e45e4 100644 --- a/staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go +++ b/staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go @@ -573,7 +573,7 @@ func protobufTagToField(tag string, field *protoField, m types.Member, t *types. switch parts[0] { case "varint", "fixed32", "fixed64", "bytes", "group": default: - name := types.Name{} + var name types.Name if last := strings.LastIndex(parts[0], "."); last != -1 { prefix := parts[0][:last] name = types.Name{ From c4080c2ad1e0af0dbb8fc6871f3310b3c18a7024 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:58:10 +0100 Subject: [PATCH 28/40] nolint unused expectNoMatchDirect function --- staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go b/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go index 37e50345420..9d2730284c0 100644 --- a/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/labels/selector_test.go @@ -148,8 +148,7 @@ func expectMatchDirect(t *testing.T, selector, ls Set) { } } -//nolint:staticcheck //iccheck // U1000 currently commented out in TODO of TestSetMatches -//nolint:unused,deadcode +//nolint:staticcheck,unused //iccheck // U1000 currently commented out in TODO of TestSetMatches func expectNoMatchDirect(t *testing.T, selector, ls Set) { if SelectorFromSet(selector).Matches(ls) { t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) From 35c05a3afa6fc9fee3ab202329ce988faf1dc651 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:58:33 +0100 Subject: [PATCH 29/40] nolint float64(-0.0), //nolint:staticcheck // SA4026: --- staging/src/k8s.io/apimachinery/pkg/util/json/json_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/util/json/json_test.go b/staging/src/k8s.io/apimachinery/pkg/util/json/json_test.go index 2d9b6f0d3f9..cc5e24b86dd 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/json/json_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/json/json_test.go @@ -122,7 +122,7 @@ func TestEvaluateTypes(t *testing.T) { }, { In: `-0.0`, - Data: float64(-0.0), + Data: float64(-0.0), //nolint:staticcheck // SA4026: in Go, the floating-point literal '-0.0' is the same as '0.0' Out: `-0`, }, { From 4bf93f318ac2cbf2f2d24da1991a5e5a4ded6143 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 18:59:09 +0100 Subject: [PATCH 30/40] nolint:staticcheck,ineffassign Convert function --- .../pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go index a627a25a4d2..137e08fe716 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go @@ -55,7 +55,7 @@ type fakeObjectConvertor struct { apiVersion fieldpath.APIVersion } -//nolint:staticcheck // SA4009 backwards compatibility +//nolint:staticcheck,ineffassign // SA4009 backwards compatibility func (c *fakeObjectConvertor) Convert(in, out, context interface{}) error { if typedValue, ok := in.(*typed.TypedValue); ok { var err error From 4352768240037a7473b96c84bc432f52ce6e0dc8 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 19:00:02 +0100 Subject: [PATCH 31/40] fix inefassign linter declaring variable --- staging/src/k8s.io/apiserver/pkg/endpoints/installer.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/installer.go b/staging/src/k8s.io/apiserver/pkg/endpoints/installer.go index 0902add4823..9b6cb98c53f 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/installer.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/installer.go @@ -217,7 +217,7 @@ func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storag isSubresource := len(subresource) > 0 // If there is a subresource, namespace scoping is defined by the parent resource - namespaceScoped := true + var namespaceScoped bool if isSubresource { parentStorage, ok := a.group.Storage[resource] if !ok { From e82e0b38ffff895210fc6ce58bb347f77a828c01 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 19:00:22 +0100 Subject: [PATCH 32/40] no lint unused variables --- staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go b/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go index 9407cc57466..7a1dfe69cb2 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go @@ -107,7 +107,7 @@ var ( // responseBodySize is the size of response body which test GOAWAY server sent for watch request, // used to check if watch request was broken by GOAWAY frame. - responseBodySize = len(responseBody) + responseBodySize = len(responseBody) //nolint:unused // requestPostBody is the request body which client must send to test GOAWAY server for POST method, // otherwise, test GOAWAY server will respond 400 HTTP status code. From 0019f986130fdd8ca17c6e5511b15168d9181b1e Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 19:00:31 +0100 Subject: [PATCH 33/40] no lint unused variables --- staging/src/k8s.io/client-go/rest/request_test.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/staging/src/k8s.io/client-go/rest/request_test.go b/staging/src/k8s.io/client-go/rest/request_test.go index 7b1d83ad348..6d1485df23d 100644 --- a/staging/src/k8s.io/client-go/rest/request_test.go +++ b/staging/src/k8s.io/client-go/rest/request_test.go @@ -1436,25 +1436,35 @@ func TestRequestStream(t *testing.T) { } } +//nolint:unused type fakeUpgradeConnection struct{} +//nolint:unused func (c *fakeUpgradeConnection) CreateStream(headers http.Header) (httpstream.Stream, error) { return nil, nil } + +//nolint:unused func (c *fakeUpgradeConnection) Close() error { return nil } + +//nolint:unused func (c *fakeUpgradeConnection) CloseChan() <-chan bool { return make(chan bool) } + +//nolint:unused func (c *fakeUpgradeConnection) SetIdleTimeout(timeout time.Duration) { } +//nolint:unused type fakeUpgradeRoundTripper struct { req *http.Request conn httpstream.Connection } +//nolint:unused func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { f.req = req b := []byte{} @@ -1466,6 +1476,7 @@ func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, return resp, nil } +//nolint:unused func (f *fakeUpgradeRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { return f.conn, nil } From e1821c13ebf78ac6e022948aa9415d9cc0b28a77 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 19:00:51 +0100 Subject: [PATCH 34/40] remove inefficient assignment --- staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go | 1 - 1 file changed, 1 deletion(-) diff --git a/staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go b/staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go index e5979d0f541..9d2807f9c16 100644 --- a/staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go +++ b/staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go @@ -146,7 +146,6 @@ func deleteTaints(taintsToRemove []corev1.Taint, newTaints *[]corev1.Taint) ([]e allErrs := []error{} var removed bool for _, taintToRemove := range taintsToRemove { - removed = false if len(taintToRemove.Effect) > 0 { *newTaints, removed = deleteTaint(*newTaints, &taintToRemove) } else { From 05f9a86f41ecf09bfcb9be6a406d1284ce8b3336 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:39:45 +0100 Subject: [PATCH 35/40] fix diskName assignment --- .../legacy-cloud-providers/gce/gce_disks_test.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go index 834e3c200c1..1f304cab3b2 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go +++ b/staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks_test.go @@ -29,7 +29,7 @@ import ( computebeta "google.golang.org/api/compute/v0.beta" compute "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" cloudprovider "k8s.io/cloud-provider" @@ -268,13 +268,12 @@ func TestCreateDisk_MultiZone(t *testing.T) { nodeInformerSynced: func() bool { return true }, } - var diskName string diskType := DiskTypeStandard const sizeGb int64 = 128 /* Act & Assert */ for _, zone := range gce.managedZones { - diskName = zone + "disk" + diskName := zone + "disk" _, err := gce.CreateDisk(diskName, diskType, zone, sizeGb, nil) if err != nil { t.Errorf("Error creating disk in zone '%v'; error: \"%v\"", zone, err) @@ -420,19 +419,19 @@ func TestDeleteDisk_DiffDiskMultiZone(t *testing.T) { nodeZones: createNodeZones(zonesWithNodes), nodeInformerSynced: func() bool { return true }, } - var diskName string + diskType := DiskTypeSSD const sizeGb int64 = 128 for _, zone := range gce.managedZones { - diskName = zone + "disk" + diskName := zone + "disk" gce.CreateDisk(diskName, diskType, zone, sizeGb, nil) } /* Act & Assert */ var err error for _, zone := range gce.managedZones { - diskName = zone + "disk" + diskName := zone + "disk" err = gce.DeleteDisk(diskName) if err != nil { t.Errorf("Error deleting disk in zone '%v'; error: \"%v\"", zone, err) From f143d1b2cdb0cbb0bfc1cf3928f231d11f9c7879 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:40:47 +0100 Subject: [PATCH 36/40] remove unused constant errLeaseFailed --- .../legacy-cloud-providers/azure/azure_controller_common.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go index 6cce0139bfc..13180e6d8ad 100644 --- a/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go +++ b/staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go @@ -49,8 +49,7 @@ const ( // https://docs.microsoft.com/en-us/azure/virtual-machines/premium-storage-performance#disk-caching diskCachingLimit = 4096 // GiB - maxLUN = 64 // max number of LUNs per VM - errLeaseFailed = "AcquireDiskLeaseFailed" //nolint:unused + maxLUN = 64 // max number of LUNs per VM errLeaseIDMissing = "LeaseIdMissing" errContainerNotFound = "ContainerNotFound" errStatusCode400 = "statuscode=400" From 98884f733a019ab991da29aaba3e42d89bf202ec Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:46:11 +0100 Subject: [PATCH 37/40] remove ineffectual assignment base var --- .../apimachinery/pkg/runtime/serializer/streaming/streaming.go | 1 - 1 file changed, 1 deletion(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go b/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go index bdcbd91c016..971c46d496a 100644 --- a/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go +++ b/staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go @@ -90,7 +90,6 @@ func (d *decoder) Decode(defaults *schema.GroupVersionKind, into runtime.Object) } // must read the rest of the frame (until we stop getting ErrShortBuffer) d.resetRead = true - base = 0 //nolint:ineffassign return nil, nil, ErrObjectTooLarge } if err != nil { From 3490bdc8b508f553018824470b6e9538946494d4 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:47:34 +0100 Subject: [PATCH 38/40] remove unused listMetaType var --- .../pkg/controller/openapi/builder/builder.go | 1 - 1 file changed, 1 deletion(-) diff --git a/staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go b/staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go index 950e8b08ab5..332afb2c93a 100644 --- a/staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go +++ b/staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go @@ -55,7 +55,6 @@ const ( objectMetaSchemaRef = "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" listMetaSchemaRef = "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" - listMetaType = "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta" typeMetaType = "k8s.io/apimachinery/pkg/apis/meta/v1.TypeMeta" objectMetaType = "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta" From 9336ff78f4a95cca8eb4a5cf528812d1bcac552c Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:49:22 +0100 Subject: [PATCH 39/40] remove unused variable responseBodySize --- .../src/k8s.io/apiserver/pkg/server/filters/goaway_test.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go b/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go index 7a1dfe69cb2..a3f3b62aa52 100644 --- a/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go +++ b/staging/src/k8s.io/apiserver/pkg/server/filters/goaway_test.go @@ -105,10 +105,6 @@ var ( // for watch request, test GOAWAY server push 1 byte in every second. responseBody = []byte("hello") - // responseBodySize is the size of response body which test GOAWAY server sent for watch request, - // used to check if watch request was broken by GOAWAY frame. - responseBodySize = len(responseBody) //nolint:unused - // requestPostBody is the request body which client must send to test GOAWAY server for POST method, // otherwise, test GOAWAY server will respond 400 HTTP status code. requestPostBody = responseBody From bf9ce7fd76068903e909358d2b25b05da7e4a431 Mon Sep 17 00:00:00 2001 From: Antonio Ojea Date: Tue, 16 Nov 2021 22:54:18 +0100 Subject: [PATCH 40/40] remove unused fakeUpgradeConnection --- .../src/k8s.io/client-go/rest/request_test.go | 46 ------------------- 1 file changed, 46 deletions(-) diff --git a/staging/src/k8s.io/client-go/rest/request_test.go b/staging/src/k8s.io/client-go/rest/request_test.go index 6d1485df23d..30ae87d8f2e 100644 --- a/staging/src/k8s.io/client-go/rest/request_test.go +++ b/staging/src/k8s.io/client-go/rest/request_test.go @@ -47,7 +47,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/runtime/serializer/streaming" "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/intstr" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/watch" @@ -1436,51 +1435,6 @@ func TestRequestStream(t *testing.T) { } } -//nolint:unused -type fakeUpgradeConnection struct{} - -//nolint:unused -func (c *fakeUpgradeConnection) CreateStream(headers http.Header) (httpstream.Stream, error) { - return nil, nil -} - -//nolint:unused -func (c *fakeUpgradeConnection) Close() error { - return nil -} - -//nolint:unused -func (c *fakeUpgradeConnection) CloseChan() <-chan bool { - return make(chan bool) -} - -//nolint:unused -func (c *fakeUpgradeConnection) SetIdleTimeout(timeout time.Duration) { -} - -//nolint:unused -type fakeUpgradeRoundTripper struct { - req *http.Request - conn httpstream.Connection -} - -//nolint:unused -func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - f.req = req - b := []byte{} - body := ioutil.NopCloser(bytes.NewReader(b)) - resp := &http.Response{ - StatusCode: http.StatusSwitchingProtocols, - Body: body, - } - return resp, nil -} - -//nolint:unused -func (f *fakeUpgradeRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { - return f.conn, nil -} - func TestRequestDo(t *testing.T) { testCases := []struct { Request *Request