diff --git a/cmd/cluster-network-operator/mtu_probe.go b/cmd/cluster-network-operator/mtu_probe.go index c7b32cf6cd..38e60c2ab7 100644 --- a/cmd/cluster-network-operator/mtu_probe.go +++ b/cmd/cluster-network-operator/mtu_probe.go @@ -69,7 +69,7 @@ func newMTUProberCommand() *cobra.Command { } // Write the CM in the apiserver, retrying as needed. - for tries := 0; tries < 10; tries++ { + for range 10 { _, err = clientSet.CoreV1().ConfigMaps(namespace).Create(context.Background(), &cm, metav1.CreateOptions{}) if err != nil && apierrors.IsAlreadyExists(err) { _, err = clientSet.CoreV1().ConfigMaps(namespace).Update(context.Background(), &cm, metav1.UpdateOptions{}) diff --git a/pkg/apply/apply.go b/pkg/apply/apply.go index a98a06fe61..e11a2e9304 100644 --- a/pkg/apply/apply.go +++ b/pkg/apply/apply.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log" + "maps" "strings" cnoclient "github.com/openshift/cluster-network-operator/pkg/client" @@ -16,7 +17,6 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" - utilpointer "k8s.io/utils/ptr" ) type Object interface { @@ -113,7 +113,7 @@ func ApplyObject(ctx context.Context, client cnoclient.Client, obj Object, subco // Use server-side apply to merge the desired object with the object on disk patchOptions := metav1.PatchOptions{ // It is considered best-practice for controllers to force - Force: utilpointer.To(true), + Force: new(true), FieldManager: fieldManager, } // Send the full object to be applied on the server side. @@ -188,9 +188,7 @@ func getCopySource(ctx context.Context, obj Object, client cnoclient.Client) (Ob if annotations == nil { annotations = make(map[string]string) } - for k, v := range obj.GetAnnotations() { - annotations[k] = v - } + maps.Copy(annotations, obj.GetAnnotations()) ret.SetAnnotations(annotations) return ret, nil diff --git a/pkg/cmd/checkendpoints/controller/backoff_recorder.go b/pkg/cmd/checkendpoints/controller/backoff_recorder.go index f597ea7d4a..ae5279f41a 100644 --- a/pkg/cmd/checkendpoints/controller/backoff_recorder.go +++ b/pkg/cmd/checkendpoints/controller/backoff_recorder.go @@ -15,9 +15,9 @@ import ( // Recorder is a stripped down version of the library-go events.Recorder interface. type Recorder interface { Event(reason, message string) - Eventf(reason, messageFmt string, args ...interface{}) + Eventf(reason, messageFmt string, args ...any) Warning(reason, message string) - Warningf(reason, messageFmt string, args ...interface{}) + Warningf(reason, messageFmt string, args ...any) } // NewBackoffEventRecorder returns a new Recorder that keeps track of the rate of events @@ -84,7 +84,7 @@ func (r *backoffEventRecorder) Event(reason, message string) { r.event(corev1.EventTypeNormal, reason, message) } -func (r *backoffEventRecorder) Eventf(reason, messageFmt string, args ...interface{}) { +func (r *backoffEventRecorder) Eventf(reason, messageFmt string, args ...any) { r.Event(reason, fmt.Sprintf(messageFmt, args...)) } @@ -92,7 +92,7 @@ func (r *backoffEventRecorder) Warning(reason, message string) { r.event(corev1.EventTypeWarning, reason, message) } -func (r *backoffEventRecorder) Warningf(reason, messageFmt string, args ...interface{}) { +func (r *backoffEventRecorder) Warningf(reason, messageFmt string, args ...any) { r.Warning(reason, fmt.Sprintf(messageFmt, args...)) } diff --git a/pkg/cmd/checkendpoints/controller/backoff_recorder_test.go b/pkg/cmd/checkendpoints/controller/backoff_recorder_test.go index 8bf2ada0f8..3352023c02 100644 --- a/pkg/cmd/checkendpoints/controller/backoff_recorder_test.go +++ b/pkg/cmd/checkendpoints/controller/backoff_recorder_test.go @@ -83,7 +83,7 @@ func TestWithLongWindow(t *testing.T) { } // excessive events for long window - for i := 0; i < excessiveEventCount; i++ { + for range excessiveEventCount { r.Eventf(t.Name(), "TEST") } @@ -91,7 +91,7 @@ func TestWithLongWindow(t *testing.T) { <-time.After(backoffDuration) // some more events - for i := 0; i < 2; i++ { + for range 2 { r.Eventf(t.Name(), "TEST") } diff --git a/pkg/cmd/checkendpoints/controller/connection_checker.go b/pkg/cmd/checkendpoints/controller/connection_checker.go index 18793cd51d..7a7c1f5b3c 100644 --- a/pkg/cmd/checkendpoints/controller/connection_checker.go +++ b/pkg/cmd/checkendpoints/controller/connection_checker.go @@ -40,7 +40,7 @@ func NewConnectionChecker(name, podName, podNamespace string, getCheck GetCheckF clientCertGetter: clientCertGetter, recorder: recorder, updates: NewUpdatesManager(checkPeriod, checkTimeout, newUpdatesProcessor(client, name)), - stop: make(chan interface{}), + stop: make(chan any), metrics: NewMetricsContext(podNamespace, name), } } @@ -63,7 +63,7 @@ type connectionChecker struct { clientCertGetter CertificatesGetter recorder Recorder updates UpdatesManager - stop chan interface{} + stop chan any metrics MetricsContext } diff --git a/pkg/cmd/checkendpoints/controller/connection_checker_test.go b/pkg/cmd/checkendpoints/controller/connection_checker_test.go index 9a0c5d80a6..3ffb54d311 100644 --- a/pkg/cmd/checkendpoints/controller/connection_checker_test.go +++ b/pkg/cmd/checkendpoints/controller/connection_checker_test.go @@ -510,7 +510,7 @@ func withConnectivityRestoredMessage(start, end int) func(*v1alpha1.OutageEntry) return withOutageMessage("Connectivity restored after %v", testTime(end).Sub(testTime(start))) } -func withOutageMessage(msg string, args ...interface{}) func(*v1alpha1.OutageEntry) { +func withOutageMessage(msg string, args ...any) func(*v1alpha1.OutageEntry) { return func(entry *v1alpha1.OutageEntry) { entry.Message = fmt.Sprintf(msg, args...) } diff --git a/pkg/controller/eventrecorder/event_recorder.go b/pkg/controller/eventrecorder/event_recorder.go index 4ef83467d2..e7a0df9719 100644 --- a/pkg/controller/eventrecorder/event_recorder.go +++ b/pkg/controller/eventrecorder/event_recorder.go @@ -16,14 +16,14 @@ var _ events.Recorder = &LoggingRecorder{} func (r *LoggingRecorder) Event(reason, message string) { log.Println(message) } -func (r *LoggingRecorder) Eventf(reason, messageFmt string, args ...interface{}) { +func (r *LoggingRecorder) Eventf(reason, messageFmt string, args ...any) { log.Printf(messageFmt, args...) } func (r *LoggingRecorder) Warning(reason, message string) { log.Println(message) } -func (r *LoggingRecorder) Warningf(reason, messageFmt string, args ...interface{}) { +func (r *LoggingRecorder) Warningf(reason, messageFmt string, args ...any) { log.Printf(messageFmt, args...) } diff --git a/pkg/controller/infrastructureconfig/validations.go b/pkg/controller/infrastructureconfig/validations.go index 0ba63ad0c5..0b94915177 100644 --- a/pkg/controller/infrastructureconfig/validations.go +++ b/pkg/controller/infrastructureconfig/validations.go @@ -30,7 +30,7 @@ func validateVipsWithVips(api, ingress []configv1.IP, elb bool) error { // For external load balancer we allow VIPs to be equal. if !elb { - for i := 0; i < len(api); i++ { + for i := range api { if api[i] == ingress[i] { return fmt.Errorf("VIPs cannot be equal, got '%s' for API and '%s' for Ingress", api[i], ingress[i]) } diff --git a/pkg/controller/observability/observability_controller.go b/pkg/controller/observability/observability_controller.go index edd746a1a9..d7dac76c49 100644 --- a/pkg/controller/observability/observability_controller.go +++ b/pkg/controller/observability/observability_controller.go @@ -402,7 +402,7 @@ func (r *ReconcileObservability) checkOLMv1Installation(ctx context.Context) (in // Check for "Installed" condition for _, cond := range conditions { - condMap, ok := cond.(map[string]interface{}) + condMap, ok := cond.(map[string]any) if !ok { continue } diff --git a/pkg/controller/observability/observability_controller_test.go b/pkg/controller/observability/observability_controller_test.go index 1b18f07c3b..36fa51a940 100644 --- a/pkg/controller/observability/observability_controller_test.go +++ b/pkg/controller/observability/observability_controller_test.go @@ -122,8 +122,8 @@ func createTestClusterExtension(t *testing.T, name string, installed bool) *unst ce.SetName(name) // Set status conditions - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Installed", "status": func() string { if installed { @@ -674,8 +674,8 @@ func TestIsNetObservOperatorInstalled_OLMv1InstallationFailed(t *testing.T) { Kind: "ClusterExtension", }) ce.SetName("netobserv-operator") - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Installed", "status": "False", "reason": "InstallationFailed", @@ -715,8 +715,8 @@ func TestIsNetObservOperatorInstalled_OLMv1NotInstalledYet(t *testing.T) { Kind: "ClusterExtension", }) ce.SetName("netobserv-operator") - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Installed", "status": "Unknown", "reason": "Installing", @@ -1468,8 +1468,8 @@ func TestReconcile_RecoveryAfterOperatorBecomesReady(t *testing.T) { g.Expect(result1.RequeueAfter).To(Equal(requeueAfterStandard)) // Update ClusterExtension to Installed status - conditions := []interface{}{ - map[string]interface{}{ + conditions := []any{ + map[string]any{ "type": "Installed", "status": "True", "reason": "InstallSucceeded", @@ -1527,7 +1527,7 @@ func TestReconcile_ConcurrentReconciliations(t *testing.T) { // Run 5 concurrent reconciliations errChan := make(chan error, 5) - for i := 0; i < 5; i++ { + for range 5 { go func() { _, err := r.Reconcile(context.TODO(), req) errChan <- err @@ -1536,7 +1536,7 @@ func TestReconcile_ConcurrentReconciliations(t *testing.T) { // Wait for all to complete and collect errors var unexpectedErrors []error - for i := 0; i < 5; i++ { + for range 5 { if err := <-errChan; err != nil { // Filter out 409 conflict errors which are expected when multiple // goroutines try to update the same resource status concurrently diff --git a/pkg/controller/proxyconfig/validation.go b/pkg/controller/proxyconfig/validation.go index a1194d6b83..99c3deca8a 100644 --- a/pkg/controller/proxyconfig/validation.go +++ b/pkg/controller/proxyconfig/validation.go @@ -64,7 +64,7 @@ func (r *ReconcileProxyConfig) ValidateProxyConfig(proxyConfig *configv1.ProxySp if isSpecNoProxySet(proxyConfig) { if proxyConfig.NoProxy != noProxyWildcard { - for _, v := range strings.Split(proxyConfig.NoProxy, ",") { + for v := range strings.SplitSeq(proxyConfig.NoProxy, ",") { v = strings.TrimSpace(v) errDomain := validation.DomainName(v, true) errCIDR := validation.IPAddressOrCIDR(v) @@ -219,7 +219,7 @@ func validateReadinessEndpoint(caBundle []*x509.Certificate, proxy, endpoint str // finite loop using proxy and returns the last result if it never succeeds. func validateReadinessEndpointWithRetries(caBundle []*x509.Certificate, proxy, endpoint *url.URL, retries int) error { var err error - for i := 0; i < retries; i++ { + for range retries { err = runReadinessProbe(caBundle, proxy, endpoint) if err == nil { return nil diff --git a/pkg/controller/statusmanager/kube.go b/pkg/controller/statusmanager/kube.go index 0b0d2e585c..38fc25fe1c 100644 --- a/pkg/controller/statusmanager/kube.go +++ b/pkg/controller/statusmanager/kube.go @@ -34,7 +34,7 @@ type patchAnnotations struct { Metadata md `json:"metadata"` } type md struct { - Annotations map[string]interface{} `json:"annotations"` + Annotations map[string]any `json:"annotations"` } func (status *StatusManager) setAnnotation(ctx context.Context, obj crclient.Object, key string, value *string) error { @@ -48,7 +48,7 @@ func (status *StatusManager) setAnnotation(ctx context.Context, obj crclient.Obj } patch := &patchAnnotations{ Metadata: md{ - Annotations: map[string]interface{}{ + Annotations: map[string]any{ key: value, }, }, diff --git a/pkg/controller/statusmanager/status_manager.go b/pkg/controller/statusmanager/status_manager.go index 2d64add274..5631967d12 100644 --- a/pkg/controller/statusmanager/status_manager.go +++ b/pkg/controller/statusmanager/status_manager.go @@ -422,7 +422,7 @@ func (status *StatusManager) set(reachedAvailableLevel bool, conditions ...operv buf, err := yaml.Marshal(oc.Status.Conditions) if err != nil { - buf = []byte(fmt.Sprintf("(failed to convert to YAML: %s)", err)) + buf = fmt.Appendf(nil, "(failed to convert to YAML: %s)", err) } // Use applyconfigurations to change only the specified fields @@ -497,7 +497,7 @@ func (status *StatusManager) set(reachedAvailableLevel bool, conditions ...operv buf, err := yaml.Marshal(co.Status.Conditions) if err != nil { - buf = []byte(fmt.Sprintf("(failed to convert to YAML: %s)", err)) + buf = fmt.Appendf(nil, "(failed to convert to YAML: %s)", err) } if isNotFound { @@ -583,7 +583,7 @@ func (status *StatusManager) MaybeSetDegraded(statusLevel StatusLevel, reason, m status.maybeSetDegraded(statusLevel, reason, message) } -func (status *StatusManager) SetDegradedOnPanicAndCrash(panicVal interface{}) { +func (status *StatusManager) SetDegradedOnPanicAndCrash(panicVal any) { status.Lock() defer status.Unlock() status.setDegraded(PanicLevel, "ReconcileError", fmt.Sprintf("Panic detected: %v", panicVal)) diff --git a/pkg/hypershift/hypershift.go b/pkg/hypershift/hypershift.go index fd43765d4d..b2c2014889 100644 --- a/pkg/hypershift/hypershift.go +++ b/pkg/hypershift/hypershift.go @@ -170,10 +170,10 @@ func ParseHostedControlPlane(hcp *unstructured.Unstructured) (*HostedControlPlan return nil, fmt.Errorf("failed extract tolerations: %v", err) } if tolerationsArrayFound { - tolerationsArrayConverted, hasConverted := tolerationsArray.([]interface{}) + tolerationsArrayConverted, hasConverted := tolerationsArray.([]any) if hasConverted { for _, entry := range tolerationsArrayConverted { - tolerationConverted, hasConverted := entry.(map[string]interface{}) + tolerationConverted, hasConverted := entry.(map[string]any) if hasConverted { toleration := corev1.Toleration{} raw, ok := tolerationConverted["key"] @@ -233,10 +233,10 @@ func ParseHostedControlPlane(hcp *unstructured.Unstructured) (*HostedControlPlan return nil, fmt.Errorf("failed extract serviceNetwork: %v", err) } if cidrArrayValueFound { - cidrArrayConverted, hasConverted := cidrArray.([]interface{}) + cidrArrayConverted, hasConverted := cidrArray.([]any) if hasConverted { sampleCidrVal := cidrArrayConverted[0] - sampleCidrValConverted, sampleCidrHasConverted := sampleCidrVal.(map[string]interface{}) + sampleCidrValConverted, sampleCidrHasConverted := sampleCidrVal.(map[string]any) if sampleCidrHasConverted { cidrRawVal, hasCidrKey := sampleCidrValConverted["cidr"] if hasCidrKey { @@ -264,7 +264,7 @@ func ParseHostedControlPlane(hcp *unstructured.Unstructured) (*HostedControlPlan return nil, fmt.Errorf("failed to extract apiServer config: %v", err) } if found && apiServerConfig != nil { - apiServerMap, ok := apiServerConfig.(map[string]interface{}) + apiServerMap, ok := apiServerConfig.(map[string]any) if ok { var spec configv1.APIServerSpec if err := runtime.DefaultUnstructuredConverter.FromUnstructured(apiServerMap, &spec); err != nil { @@ -396,7 +396,7 @@ func SetHostedControlPlaneConditions(hcp *unstructured.Unstructured, operStatus // Set the conditions directly instead of using SetNestedField // because it does a DeepCopy and metav1.Condition doesn't implement it - hcp.Object["status"].(map[string]interface{})["conditions"] = conditions + hcp.Object["status"].(map[string]any)["conditions"] = conditions return conditions, nil } @@ -415,7 +415,7 @@ func tolerationsToStringSliceYaml(tolerations []corev1.Toleration) ([]string, er } yamlStrs := []string{} - for _, arg := range strings.Split(string(yamlBytes), "\n") { + for arg := range strings.SplitSeq(string(yamlBytes), "\n") { // filter out null and empty strings if strings.Contains(arg, ": null") || strings.Contains(arg, ": \"\"") { diff --git a/pkg/hypershift/hypershift_test.go b/pkg/hypershift/hypershift_test.go index 23ba761290..c30acad505 100644 --- a/pkg/hypershift/hypershift_test.go +++ b/pkg/hypershift/hypershift_test.go @@ -134,16 +134,16 @@ func TestSetRestartDateAnnotation(t *testing.T) { makeObj := func(apiVersion, kind, name, ns string) *unstructured.Unstructured { return &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": apiVersion, "kind": kind, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": name, "namespace": ns, }, - "spec": map[string]interface{}{ - "template": map[string]interface{}{ - "metadata": map[string]interface{}{}, + "spec": map[string]any{ + "template": map[string]any{ + "metadata": map[string]any{}, }, }, }, diff --git a/pkg/network/additional_networks.go b/pkg/network/additional_networks.go index 9315851ccb..464981b4b8 100644 --- a/pkg/network/additional_networks.go +++ b/pkg/network/additional_networks.go @@ -46,7 +46,7 @@ func renderRawCNIConfig(conf *operv1.AdditionalNetworkDefinition, manifestDir st // validateRaw checks the AdditionalNetwork name and RawCNIConfig. func validateRaw(conf *operv1.AdditionalNetworkDefinition) []error { out := []error{} - var rawConfig map[string]interface{} + var rawConfig map[string]any var err error if conf.Name == "" { diff --git a/pkg/network/bootstrap_test.go b/pkg/network/bootstrap_test.go index b40f620cb5..5f2bb1dfc3 100644 --- a/pkg/network/bootstrap_test.go +++ b/pkg/network/bootstrap_test.go @@ -135,12 +135,12 @@ func TestBootstrap(t *testing.T) { hcp.SetGroupVersionKind(hypershift.HostedControlPlaneGVK) hcp.SetName(hostedClusterName) hcp.SetNamespace(hostedClusterNamespace) - hcp.Object["spec"] = map[string]interface{}{ + hcp.Object["spec"] = map[string]any{ "clusterID": "test-cluster-id", "controllerAvailabilityPolicy": "SingleReplica", - "configuration": map[string]interface{}{ - "apiServer": map[string]interface{}{ - "tlsSecurityProfile": map[string]interface{}{ + "configuration": map[string]any{ + "apiServer": map[string]any{ + "tlsSecurityProfile": map[string]any{ "type": string(configv1.TLSProfileModernType), }, "tlsAdherence": string(configv1.TLSAdherencePolicyStrictAllComponents), @@ -186,7 +186,7 @@ func TestBootstrap(t *testing.T) { hcp.SetGroupVersionKind(hypershift.HostedControlPlaneGVK) hcp.SetName(hostedClusterName) hcp.SetNamespace(hostedClusterNamespace) - hcp.Object["spec"] = map[string]interface{}{ + hcp.Object["spec"] = map[string]any{ "clusterID": "test-cluster-id", "controllerAvailabilityPolicy": "SingleReplica", } diff --git a/pkg/network/cloud_network_test.go b/pkg/network/cloud_network_test.go index 2539e14876..fba3a30a7c 100644 --- a/pkg/network/cloud_network_test.go +++ b/pkg/network/cloud_network_test.go @@ -1,6 +1,7 @@ package network import ( + "slices" "testing" "github.com/openshift/cluster-network-operator/pkg/render" @@ -43,14 +44,14 @@ func makeManagedControllerRenderData() render.RenderData { } // getEnvVar looks up an env var by name from a container map and returns its value. -func getEnvVar(t *testing.T, container map[string]interface{}, name string) (string, bool) { +func getEnvVar(t *testing.T, container map[string]any, name string) (string, bool) { t.Helper() envSlice, found, err := uns.NestedSlice(container, "env") if err != nil || !found { return "", false } for _, e := range envSlice { - em := e.(map[string]interface{}) + em := e.(map[string]any) n, _, _ := uns.NestedString(em, "name") if n == name { v, _, _ := uns.NestedString(em, "value") @@ -61,14 +62,14 @@ func getEnvVar(t *testing.T, container map[string]interface{}, name string) (str } // findUnstructuredContainer finds a container by name from a deployment's unstructured object. -func findUnstructuredContainer(t *testing.T, obj map[string]interface{}, containerName string) (map[string]interface{}, bool) { +func findUnstructuredContainer(t *testing.T, obj map[string]any, containerName string) (map[string]any, bool) { t.Helper() containers, found, err := uns.NestedSlice(obj, "spec", "template", "spec", "containers") if err != nil || !found { return nil, false } for _, c := range containers { - cm := c.(map[string]interface{}) + cm := c.(map[string]any) name, _, _ := uns.NestedString(cm, "name") if name == containerName { return cm, true @@ -161,10 +162,8 @@ func TestCloudTokenMinterHasTokenAudience(t *testing.T) { t.Fatal("args not found in cloud-token-minter container") } - for _, arg := range args { - if arg == "--token-audience=openshift" { - return - } + if slices.Contains(args, "--token-audience=openshift") { + return } t.Error("expected cloud-token minter to have --token-audience=openshift arg") return diff --git a/pkg/network/mtu.go b/pkg/network/mtu.go index 98a7515ece..d7b1c34e67 100644 --- a/pkg/network/mtu.go +++ b/pkg/network/mtu.go @@ -1,5 +1,4 @@ //go:build linux -// +build linux package network diff --git a/pkg/network/mtu_unsupported.go b/pkg/network/mtu_unsupported.go index 43e534779a..1fddf341f4 100644 --- a/pkg/network/mtu_unsupported.go +++ b/pkg/network/mtu_unsupported.go @@ -1,5 +1,4 @@ //go:build !linux -// +build !linux package network diff --git a/pkg/network/multus_ipam.go b/pkg/network/multus_ipam.go index bd8c404dba..2f488be10e 100644 --- a/pkg/network/multus_ipam.go +++ b/pkg/network/multus_ipam.go @@ -14,8 +14,8 @@ const ipamTypeWhereabouts = "whereabouts" // this facilitates using auxiliary features associated with that IPAM (such as DHCP CNI daemon, or ip-reconciler for Whereabouts) func detectIPAMTypeRaw(targetType string, addNet *operv1.AdditionalNetworkDefinition) bool { // Parse the RawCNIConfig - var rawConfig map[string]interface{} - var useipam interface{} + var rawConfig map[string]any + var useipam any var err error foundipam := false @@ -29,14 +29,14 @@ func detectIPAMTypeRaw(targetType string, addNet *operv1.AdditionalNetworkDefini // First we determine if it's a conflist. if rawConfig["plugins"] != nil { // As a limitation, we'll only look for the first instance of ipam (should be the primary case) - plugins, okplugincast := rawConfig["plugins"].([]interface{}) + plugins, okplugincast := rawConfig["plugins"].([]any) if !okplugincast { log.Printf("WARNING: Plugins (conflist) element has data of type %T but wanted []interface{}", rawConfig["plugins"]) return false } for _, pvalue := range plugins { - eachConfig, okeachconfigcast := pvalue.(map[string]interface{}) + eachConfig, okeachconfigcast := pvalue.(map[string]any) if !okeachconfigcast { log.Printf("WARNING: Each Plugin element (conflist) has data of type %T but wanted map[string]interface{}", pvalue) return false @@ -56,7 +56,7 @@ func detectIPAMTypeRaw(targetType string, addNet *operv1.AdditionalNetworkDefini } if foundipam { - ipam, okipamcast := useipam.(map[string]interface{}) + ipam, okipamcast := useipam.(map[string]any) if !okipamcast { log.Printf("WARNING: IPAM element has data of type %T but wanted map[string]interface{}", useipam) return false diff --git a/pkg/network/ovn_kubernetes.go b/pkg/network/ovn_kubernetes.go index bf531cd725..4ec20e3895 100644 --- a/pkg/network/ovn_kubernetes.go +++ b/pkg/network/ovn_kubernetes.go @@ -471,10 +471,7 @@ func renderOVNKubernetes(conf *operv1.NetworkSpec, bootstrapResult *bootstrap.Bo } //there only needs to be two cluster managers - clusterManagerReplicas := 2 - if bootstrapResult.OVN.ControlPlaneReplicaCount < 2 { - clusterManagerReplicas = bootstrapResult.OVN.ControlPlaneReplicaCount - } + clusterManagerReplicas := min(bootstrapResult.OVN.ControlPlaneReplicaCount, 2) data.Data["ClusterManagerReplicas"] = clusterManagerReplicas commonManifestDir := filepath.Join(manifestDir, "network/ovn-kubernetes/common") @@ -1558,7 +1555,7 @@ func bootstrapOVN(conf *operv1.Network, kubeClient cnoclient.Client, infraStatus // preserve any default masquerade subnet values that might have been set previously if masqueradeCIDRs, ok := nodeDaemonSet.GetAnnotations()[names.MasqueradeCIDRsAnnotation]; ok { - for _, masqueradeCIDR := range strings.Split(masqueradeCIDRs, ",") { + for masqueradeCIDR := range strings.SplitSeq(masqueradeCIDRs, ",") { if utilnet.IsIPv6CIDRString(masqueradeCIDR) { klog.Infof("Found the DefaultV6MasqueradeSubnet(%s) in the %q annotation", masqueradeCIDR, names.MasqueradeCIDRsAnnotation) res.DefaultV6MasqueradeSubnet = masqueradeCIDR @@ -1785,12 +1782,7 @@ func isCNOIPsecMachineConfigPresent(infra bootstrap.InfraStatus) bool { // are already present in both master and worker nodes, otherwise returns false. func isUserDefinedIPsecMachineConfigPresent(infra bootstrap.InfraStatus) bool { isUserDefinedMachineConfigPresentIn := func(mcs []*mcfgv1.MachineConfig) bool { - for _, mc := range mcs { - if mcutil.IsUserDefinedIPsecMachineConfig(mc) { - return true - } - } - return false + return slices.ContainsFunc(mcs, mcutil.IsUserDefinedIPsecMachineConfig) } return isUserDefinedMachineConfigPresentIn(infra.MasterIPsecMachineConfigs) && isUserDefinedMachineConfigPresentIn(infra.WorkerIPsecMachineConfigs) diff --git a/pkg/network/ovn_kubernetes_dpu_host_test.go b/pkg/network/ovn_kubernetes_dpu_host_test.go index 484fe2c186..8dea916703 100644 --- a/pkg/network/ovn_kubernetes_dpu_host_test.go +++ b/pkg/network/ovn_kubernetes_dpu_host_test.go @@ -105,7 +105,7 @@ func TestOVNKubernetesNodeModeTemplates(t *testing.T) { var containerNames []string for _, container := range containers { - cmap := container.(map[string]interface{}) + cmap := container.(map[string]any) name, found, err := uns.NestedString(cmap, "name") g.Expect(err).NotTo(HaveOccurred()) g.Expect(found).To(BeTrue()) @@ -113,7 +113,7 @@ func TestOVNKubernetesNodeModeTemplates(t *testing.T) { } // Verify container list exactly matches expected containers - expectedContainersInterface := make([]interface{}, len(mode.expectedContainers)) + expectedContainersInterface := make([]any, len(mode.expectedContainers)) for i, container := range mode.expectedContainers { expectedContainersInterface[i] = container } diff --git a/pkg/network/ovn_kubernetes_test.go b/pkg/network/ovn_kubernetes_test.go index 5d9419e3d1..bd45c5b99e 100644 --- a/pkg/network/ovn_kubernetes_test.go +++ b/pkg/network/ovn_kubernetes_test.go @@ -67,7 +67,7 @@ var OVNKubernetesConfig = operv1.Network{ DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), }, }, }, @@ -486,7 +486,7 @@ cluster-subnets="10.132.0.0/14"`, RoutingViaHost: true, }, egressIPConfig: &operv1.EgressIPConfig{ - ReachabilityTotalTimeoutSeconds: ptrToUint32(3), + ReachabilityTotalTimeoutSeconds: new(uint32(3)), }, controlPlaneReplicaCount: 2, }, @@ -547,7 +547,7 @@ cluster-subnets="10.132.0.0/14"`, RoutingViaHost: true, }, egressIPConfig: &operv1.EgressIPConfig{ - ReachabilityTotalTimeoutSeconds: ptrToUint32(0), + ReachabilityTotalTimeoutSeconds: new(uint32(0)), }, controlPlaneReplicaCount: 2, }, @@ -605,7 +605,7 @@ hybrid-overlay-vxlan-port="9000"`, HybridClusterNetwork: []operv1.ClusterNetworkEntry{ {CIDR: "10.132.0.0/14", HostPrefix: 23}, }, - HybridOverlayVXLANPort: ptrToUint32(9000), + HybridOverlayVXLANPort: new(uint32(9000)), }, gatewayConfig: &operv1.GatewayConfig{ RoutingViaHost: true, @@ -1064,7 +1064,7 @@ logfile-maxage=0`, OVNKubeConfig.Spec.DefaultNetwork.OVNKubernetesConfig.EgressIPConfig = *tc.egressIPConfig } //set a few inputs so that the tests are not machine dependant - OVNKubeConfig.Spec.DefaultNetwork.OVNKubernetesConfig.MTU = ptrToUint32(1500) + OVNKubeConfig.Spec.DefaultNetwork.OVNKubernetesConfig.MTU = new(uint32(1500)) if tc.v4InternalSubnet != "" { OVNKubeConfig.Spec.DefaultNetwork.OVNKubernetesConfig.V4InternalSubnet = tc.v4InternalSubnet @@ -1160,9 +1160,9 @@ func checkOVNKubernetesPostStart(objects []*uns.Unstructured) error { return fmt.Errorf("unable to find containers in ovnkube-node daemonset : %w", err) } - var nbdb map[string]interface{} + var nbdb map[string]any for _, container := range ovnkubeNodeContainers { - cmap := container.(map[string]interface{}) + cmap := container.(map[string]any) name, found, err := uns.NestedString(cmap, "name") if found && err == nil && name == "nbdb" { nbdb = cmap @@ -1213,14 +1213,14 @@ func TestFillOVNKubernetesDefaults(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - MTU: ptrToUint32(8900), - GenevePort: ptrToUint32(6081), + MTU: new(uint32(8900)), + GenevePort: new(uint32(6081)), // Note: DefaultNetworkTransport is not set by fillOVNKubernetesDefaults // When NoOverlayMode feature gate is disabled, the CRD doesn't have this field // When enabled, the CRD itself provides the default PolicyAuditConfig: &operv1.PolicyAuditConfig{ - RateLimit: ptrToUint32(20), - MaxFileSize: ptrToUint32(50), + RateLimit: new(uint32(20)), + MaxFileSize: new(uint32(50)), Destination: "null", SyslogFacility: "local0", }, @@ -1256,13 +1256,13 @@ func TestFillOVNKubernetesDefaultsIPsec(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - MTU: ptrToUint32(8854), - GenevePort: ptrToUint32(8061), + MTU: new(uint32(8854)), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{Mode: operv1.IPsecModeFull}, // Note: DefaultNetworkTransport is not set by fillOVNKubernetesDefaults PolicyAuditConfig: &operv1.PolicyAuditConfig{ - RateLimit: ptrToUint32(20), - MaxFileSize: ptrToUint32(50), + RateLimit: new(uint32(20)), + MaxFileSize: new(uint32(50)), Destination: "null", SyslogFacility: "local0", }, @@ -1294,11 +1294,11 @@ func TestValidateOVNKubernetes(t *testing.T) { } // set mtu to insanity - ovnConfig.MTU = ptrToUint32(70000) + ovnConfig.MTU = new(uint32(70000)) errExpect("invalid MTU 70000") // set geneve port to insanity - ovnConfig.GenevePort = ptrToUint32(70001) + ovnConfig.GenevePort = new(uint32(70001)) errExpect("invalid GenevePort 70001") config.ClusterNetwork = []operv1.ClusterNetworkEntry{{ @@ -1306,7 +1306,7 @@ func TestValidateOVNKubernetes(t *testing.T) { }} // invalid ipv6 mtu - ovnConfig.MTU = ptrToUint32(576) + ovnConfig.MTU = new(uint32(576)) errExpect("invalid MTU 576") config.ClusterNetwork = nil @@ -1561,10 +1561,10 @@ func TestOVNKubernetesIsSafe(t *testing.T) { g.Expect(errs).To(BeEmpty()) // change the mtu without migration - next.DefaultNetwork.OVNKubernetesConfig.MTU = ptrToUint32(70000) + next.DefaultNetwork.OVNKubernetesConfig.MTU = new(uint32(70000)) // change the geneve port - next.DefaultNetwork.OVNKubernetesConfig.GenevePort = ptrToUint32(34001) + next.DefaultNetwork.OVNKubernetesConfig.GenevePort = new(uint32(34001)) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(2)) g.Expect(errs[0]).To(MatchError("cannot change ovn-kubernetes MTU without migration")) @@ -1580,10 +1580,10 @@ func TestOVNKubernetesIsSafe(t *testing.T) { MTU: &operv1.MTUMigration{ Network: &operv1.MTUMigrationValues{ From: prev.DefaultNetwork.OVNKubernetesConfig.MTU, - To: ptrToUint32(1300), + To: new(uint32(1300)), }, Machine: &operv1.MTUMigrationValues{ - To: ptrToUint32(1500), + To: new(uint32(1500)), }, }, } @@ -1597,7 +1597,7 @@ func TestOVNKubernetesIsSafe(t *testing.T) { g.Expect(errs[0]).To(MatchError("invalid Migration.MTU, at least one of the required fields is missing")) // invalid Migration.MTU.Network.From, not equal to previously applied MTU - next.Migration.MTU.Network.From = ptrToUint32(*prev.DefaultNetwork.OVNKubernetesConfig.MTU + 100) + next.Migration.MTU.Network.From = new(*prev.DefaultNetwork.OVNKubernetesConfig.MTU + 100) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(1)) g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Network.From(%d) not equal to the currently applied MTU(%d)", *next.Migration.MTU.Network.From, *prev.DefaultNetwork.OVNKubernetesConfig.MTU))) @@ -1605,27 +1605,27 @@ func TestOVNKubernetesIsSafe(t *testing.T) { next.Migration.MTU.Network.From = prev.DefaultNetwork.OVNKubernetesConfig.MTU // invalid Migration.MTU.Network.To, lower than minimum MTU for IPv4 - next.Migration.MTU.Network.To = ptrToUint32(100) + next.Migration.MTU.Network.To = new(uint32(100)) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(1)) g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Network.To(%d), has to be in range: %d-%d", *next.Migration.MTU.Network.To, MinMTUIPv4, MaxMTU))) // invalid Migration.MTU.Network.To, higher than maximum MTU for IPv4 - next.Migration.MTU.Network.To = ptrToUint32(MaxMTU + 1) + next.Migration.MTU.Network.To = new(MaxMTU + 1) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(2)) g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Network.To(%d), has to be in range: %d-%d", *next.Migration.MTU.Network.To, MinMTUIPv4, MaxMTU))) - next.Migration.MTU.Network.To = ptrToUint32(1300) + next.Migration.MTU.Network.To = new(uint32(1300)) // invalid Migration.MTU.Machine.To, not big enough to accommodate next.Migration.MTU.Network.To with encap overhead - next.Migration.MTU.Network.To = ptrToUint32(1500) + next.Migration.MTU.Network.To = new(uint32(1500)) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(1)) g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Machine.To(%d), has to be at least %d", *next.Migration.MTU.Machine.To, *next.Migration.MTU.Network.To+getOVNEncapOverhead(next)))) // invalid Migration.MTU.Network.To, lower than minimum MTU for IPv6 - next.Migration.MTU.Network.To = ptrToUint32(1200) + next.Migration.MTU.Network.To = new(uint32(1200)) next.ClusterNetwork = []operv1.ClusterNetworkEntry{ { CIDR: "fd00:1:2:3::/64", @@ -1637,8 +1637,8 @@ func TestOVNKubernetesIsSafe(t *testing.T) { g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Network.To(%d), has to be in range: %d-%d", *next.Migration.MTU.Network.To, MinMTUIPv6, MaxMTU))) // invalid Migration.MTU.Machine.To, higher than max MTU - next.Migration.MTU.Network.To = ptrToUint32(MaxMTU) - next.Migration.MTU.Machine.To = ptrToUint32(*next.Migration.MTU.Network.To + getOVNEncapOverhead(next)) + next.Migration.MTU.Network.To = new(MaxMTU) + next.Migration.MTU.Machine.To = new(*next.Migration.MTU.Network.To + getOVNEncapOverhead(next)) errs = isOVNKubernetesChangeSafe(prev, next) g.Expect(errs).To(HaveLen(1)) g.Expect(errs[0]).To(MatchError(fmt.Sprintf("invalid Migration.MTU.Machine.To(%d), has to be in range: %d-%d", *next.Migration.MTU.Machine.To, MinMTUIPv6, MaxMTU))) @@ -2561,7 +2561,7 @@ func TestRenderOVNKubernetesEnableIPsec(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{Mode: operv1.IPsecModeFull}, }, }, @@ -2791,7 +2791,7 @@ func TestRenderOVNKubernetesEnableIPsecForHostedControlPlane(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{Mode: operv1.IPsecModeFull}, }, }, @@ -2891,7 +2891,7 @@ func TestRenderOVNKubernetesIPsecUpgradeWithMachineConfig(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{}, }, }, @@ -3003,7 +3003,7 @@ func TestRenderOVNKubernetesIPsecUpgradeWithNoMachineConfig(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{}, }, }, @@ -3155,7 +3155,7 @@ func TestRenderOVNKubernetesIPsecUpgradeWithHypershiftHostedCluster(t *testing.T DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{Mode: operv1.IPsecModeFull}, }, }, @@ -3260,7 +3260,7 @@ func TestRenderOVNKubernetesDisableIPsec(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), }, }, } @@ -3474,7 +3474,7 @@ func TestRenderOVNKubernetesEnableIPsecWithUserInstalledIPsecMachineConfigs(t *t DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), IPsecConfig: &operv1.IPsecConfig{Mode: operv1.IPsecModeFull}, }, }, @@ -3620,7 +3620,7 @@ func TestRenderOVNKubernetesDisableIPsecWithUserInstalledIPsecMachineConfigs(t * DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), }, }, } @@ -3764,7 +3764,7 @@ func TestRenderOVNKubernetesDualStackPrecedenceOverUpgrade(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), }, }, } @@ -3839,11 +3839,11 @@ func TestRenderOVNKubernetesOVSFlowsConfigMap(t *testing.T) { DefaultNetwork: operv1.DefaultNetworkDefinition{ Type: operv1.NetworkTypeOVNKubernetes, OVNKubernetesConfig: &operv1.OVNKubernetesConfig{ - GenevePort: ptrToUint32(8061), + GenevePort: new(uint32(8061)), PolicyAuditConfig: &operv1.PolicyAuditConfig{}, }, }, - DisableMultiNetwork: boolPtr(true), + DisableMultiNetwork: new(true), } testCases := []struct { Description string @@ -3869,9 +3869,9 @@ func TestRenderOVNKubernetesOVSFlowsConfigMap(t *testing.T) { Description: "IPFIX performance variables are specified", FlowsConfig: &bootstrap.FlowsConfig{ Target: "7.8.9.10:1112", - CacheMaxFlows: uintPtr(123), - CacheActiveTimeout: uintPtr(456), - Sampling: uintPtr(789), + CacheMaxFlows: new(uint(123)), + CacheActiveTimeout: new(uint(456)), + Sampling: new(uint(789)), }, Expected: []v1.EnvVar{ {Name: "IPFIX_COLLECTORS", Value: "7.8.9.10:1112"}, @@ -3883,9 +3883,9 @@ func TestRenderOVNKubernetesOVSFlowsConfigMap(t *testing.T) { { Description: "Wrong configuration: target missing but performance variables present", FlowsConfig: &bootstrap.FlowsConfig{ - CacheMaxFlows: uintPtr(123), - CacheActiveTimeout: uintPtr(456), - Sampling: uintPtr(789), + CacheMaxFlows: new(uint(123)), + CacheActiveTimeout: new(uint(456)), + Sampling: new(uint(789)), }, NotExpected: []string{"IPFIX_COLLECTORS", "IPFIX_CACHE_MAX_FLOWS", "IPFIX_CACHE_ACTIVE_TIMEOUT", "IPFIX_SAMPLING"}, @@ -4091,25 +4091,25 @@ func TestRenderOVNKubernetesReachability(t *testing.T) { }, { name: "Reachability timeout set to 0", - reachabilityTimeout: ptrToUint32(0), + reachabilityTimeout: new(uint32(0)), expectKubernetesFeatureReachability: true, expectErr: false, }, { name: "Reachability timeout changed to 10", - reachabilityTimeout: ptrToUint32(10), + reachabilityTimeout: new(uint32(10)), expectKubernetesFeatureReachability: true, expectErr: false, }, { name: "Reachability timeout unchanged to 10", - reachabilityTimeout: ptrToUint32(10), + reachabilityTimeout: new(uint32(10)), expectKubernetesFeatureReachability: true, expectErr: false, }, { name: "Reachability timeout changed to 5", - reachabilityTimeout: ptrToUint32(5), + reachabilityTimeout: new(uint32(5)), expectKubernetesFeatureReachability: true, expectErr: false, }, @@ -4170,7 +4170,7 @@ func TestRenderOVNKubernetesReachability(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) g.Expect(found).To(BeTrue()) for _, c := range containers { - cm := c.(map[string]interface{}) + cm := c.(map[string]any) if name, ok := cm["name"]; ok && name == "ovnkube-cluster-manager" { command, found, err := uns.NestedSlice(cm, "command") g.Expect(err).NotTo(HaveOccurred()) @@ -4344,18 +4344,6 @@ func checkContainerImagePullPolicy(g *WithT, container map[string]any) { g.Expect(policy).To(Equal(string(v1.PullIfNotPresent))) } -func ptrToUint32(x uint32) *uint32 { - return &x -} - -func uintPtr(x uint) *uint { - return &x -} - -func boolPtr(x bool) *bool { - return &x -} - func networkOwnerRef() []metav1.OwnerReference { isController := true return []metav1.OwnerReference{{APIVersion: operv1.GroupVersion.String(), Kind: "Network", Controller: &isController, Name: "cluster"}} @@ -4382,7 +4370,7 @@ func Test_renderOVNKubernetes(t *testing.T) { } fakeNetworkConf := func() *operv1.NetworkSpec { config := OVNKubernetesConfig.DeepCopy() - config.Spec.DisableMultiNetwork = boolPtr(false) + config.Spec.DisableMultiNetwork = new(false) config.Spec.DefaultNetwork.OVNKubernetesConfig.PolicyAuditConfig = &operv1.PolicyAuditConfig{} return &config.Spec } @@ -4849,7 +4837,7 @@ func TestRenderOVNKubernetesNoOverlay(t *testing.T) { t.Run(tc.name, func(t *testing.T) { crd := OVNKubernetesConfig.DeepCopy() config := &crd.Spec - config.DefaultNetwork.OVNKubernetesConfig.MTU = ptrToUint32(1500) + config.DefaultNetwork.OVNKubernetesConfig.MTU = new(uint32(1500)) config.DefaultNetwork.OVNKubernetesConfig.Transport = tc.defaultNetworkTransport if tc.noOverlayConfig != nil { @@ -5171,7 +5159,7 @@ func extractDaemonSetEnvVars(g *WithT, objs []*uns.Unstructured, dsName, contain g.Expect(err).NotTo(HaveOccurred()) g.Expect(found).To(BeTrue()) for _, c := range containers { - cmap := c.(map[string]interface{}) + cmap := c.(map[string]any) name, _, _ := uns.NestedString(cmap, "name") if name != containerName { continue @@ -5182,7 +5170,7 @@ func extractDaemonSetEnvVars(g *WithT, objs []*uns.Unstructured, dsName, contain return envVars } for _, e := range envList { - emap := e.(map[string]interface{}) + emap := e.(map[string]any) eName, _, _ := uns.NestedString(emap, "name") eVal, _, _ := uns.NestedString(emap, "value") envVars[eName] = eVal diff --git a/pkg/network/testutil_test.go b/pkg/network/testutil_test.go index 413f7c872e..005956d2b7 100644 --- a/pkg/network/testutil_test.go +++ b/pkg/network/testutil_test.go @@ -32,7 +32,7 @@ type KubeObjectMatcher struct { kind, namespace, name string } -func (k *KubeObjectMatcher) Match(actual interface{}) (bool, error) { +func (k *KubeObjectMatcher) Match(actual any) (bool, error) { obj, ok := actual.(*uns.Unstructured) if !ok { return false, fmt.Errorf("cannot match object of type %t", actual) @@ -44,7 +44,7 @@ func (k *KubeObjectMatcher) Match(actual interface{}) (bool, error) { return ok, nil } -func (k *KubeObjectMatcher) FailureMessage(actual interface{}) string { +func (k *KubeObjectMatcher) FailureMessage(actual any) string { obj, ok := actual.(*uns.Unstructured) if !ok { return "not of type Unstructured" @@ -55,7 +55,7 @@ func (k *KubeObjectMatcher) FailureMessage(actual interface{}) string { obj.GetKind(), obj.GetNamespace(), obj.GetName()) } -func (k *KubeObjectMatcher) NegatedFailureMessage(actual interface{}) string { +func (k *KubeObjectMatcher) NegatedFailureMessage(actual any) string { obj, ok := actual.(*uns.Unstructured) if !ok { return "not of type Unstructured" diff --git a/pkg/network/tls.go b/pkg/network/tls.go index 520339ccd9..163831cc12 100644 --- a/pkg/network/tls.go +++ b/pkg/network/tls.go @@ -30,7 +30,7 @@ const ( // addTLSInfoToRenderData adds TLS-related template data to the render data. // It converts OpenSSL cipher names (from TLSProfile.Spec.Ciphers) to IANA format for Go components, // and also adds NGINX-specific parameters using the original OpenSSL names. -func addTLSInfoToRenderData(data map[string]interface{}, bootstrapResult *bootstrap.BootstrapResult, respectAdherence bool) { +func addTLSInfoToRenderData(data map[string]any, bootstrapResult *bootstrap.BootstrapResult, respectAdherence bool) { if respectAdherence && !crypto.ShouldHonorClusterTLSProfile(bootstrapResult.TLSProfile.Adherence) { data[UseTLSProfileKey] = false return diff --git a/pkg/network/tls_test.go b/pkg/network/tls_test.go index 9a75ca3daa..cdcff0de86 100644 --- a/pkg/network/tls_test.go +++ b/pkg/network/tls_test.go @@ -19,7 +19,7 @@ func TestAddTLSInfoToRenderData(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - data := make(map[string]interface{}) + data := make(map[string]any) bootstrapResult := &bootstrap.BootstrapResult{ TLSProfile: bootstrap.TLSProfile{ Spec: configv1.TLSProfileSpec{ @@ -69,7 +69,7 @@ func TestAddTLSInfoToRenderData(t *testing.T) { for _, policy := range adherencePolicies { t.Run(policy.name, func(t *testing.T) { t.Run("and respecting adherence", func(t *testing.T) { - data := make(map[string]interface{}) + data := make(map[string]any) bootstrapResult := &bootstrap.BootstrapResult{ TLSProfile: bootstrap.TLSProfile{ Spec: configv1.TLSProfileSpec{ @@ -102,7 +102,7 @@ func TestAddTLSInfoToRenderData(t *testing.T) { }) t.Run("and not respecting adherence", func(t *testing.T) { - data := make(map[string]interface{}) + data := make(map[string]any) bootstrapResult := &bootstrap.BootstrapResult{ TLSProfile: bootstrap.TLSProfile{ Spec: configv1.TLSProfileSpec{ @@ -143,7 +143,7 @@ func TestAddTLSInfoToRenderData(t *testing.T) { }) t.Run("with nil cipher list", func(t *testing.T) { - data := make(map[string]interface{}) + data := make(map[string]any) bootstrapResult := &bootstrap.BootstrapResult{ TLSProfile: bootstrap.TLSProfile{ Spec: configv1.TLSProfileSpec{ diff --git a/pkg/render/funcs.go b/pkg/render/funcs.go index fb5a6d8f60..3f8e61e9fc 100644 --- a/pkg/render/funcs.go +++ b/pkg/render/funcs.go @@ -9,7 +9,7 @@ import ( // getOr returns the value of m[key] if it exists, fallback otherwise. // As a special case, it also returns fallback if the value of m[key] is // the empty string -func getOr(m map[string]interface{}, key string, fallback interface{}) interface{} { +func getOr(m map[string]any, key string, fallback any) any { val, ok := m[key] if !ok { return fallback @@ -25,7 +25,7 @@ func getOr(m map[string]interface{}, key string, fallback interface{}) interface // isSet returns the value of m[key] if key exists, otherwise false // Different from getOr because it will return zero values. -func isSet(m map[string]interface{}, key string) interface{} { +func isSet(m map[string]any, key string) any { val, ok := m[key] if !ok { return false diff --git a/pkg/render/render.go b/pkg/render/render.go index e7af482a05..681c0e1db3 100644 --- a/pkg/render/render.go +++ b/pkg/render/render.go @@ -19,13 +19,13 @@ import ( type RenderData struct { Funcs template.FuncMap - Data map[string]interface{} + Data map[string]any } func MakeRenderData() RenderData { return RenderData{ Funcs: template.FuncMap{}, - Data: map[string]interface{}{}, + Data: map[string]any{}, } } diff --git a/pkg/util/k8s/unstructured.go b/pkg/util/k8s/unstructured.go index 081ed4c90a..3b1ce19476 100644 --- a/pkg/util/k8s/unstructured.go +++ b/pkg/util/k8s/unstructured.go @@ -13,7 +13,7 @@ import ( // ToUnstructured converts an arbitrary object (which MUST obey the // k8s object conventions) to an Unstructured -func ToUnstructured(obj interface{}) (*uns.Unstructured, error) { +func ToUnstructured(obj any) (*uns.Unstructured, error) { b, err := json.Marshal(obj) if err != nil { return nil, errors.Wrapf(err, "failed to convert to unstructured (marshal)") @@ -26,7 +26,7 @@ func ToUnstructured(obj interface{}) (*uns.Unstructured, error) { } // CalculateHash computes SHA256 sum of the JSONfied object passed as obj. -func CalculateHash(obj interface{}) (string, error) { +func CalculateHash(obj any) (string, error) { configStr, err := json.Marshal(obj) if err != nil { return "", err diff --git a/pkg/util/proxyconfig/no_proxy.go b/pkg/util/proxyconfig/no_proxy.go index a6357d8e1e..e13d030043 100644 --- a/pkg/util/proxyconfig/no_proxy.go +++ b/pkg/util/proxyconfig/no_proxy.go @@ -142,7 +142,7 @@ func mergeUserSystemNoProxy(proxy *configv1.Proxy, infra *configv1.Infrastructur } if len(proxy.Spec.NoProxy) > 0 { - for _, userValue := range strings.Split(proxy.Spec.NoProxy, ",") { + for userValue := range strings.SplitSeq(proxy.Spec.NoProxy, ",") { if userValue != "" { set.Insert(userValue) }