diff --git a/cmd/main.go b/cmd/main.go index bcf76baeb..97751b5d1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -93,7 +93,7 @@ func init() { } func StartNSXServiceAccountController(mgr ctrl.Manager, commonService common.Service) { - log.Info("starting NSXServiceAccountController") + log.Info("Starting NSXServiceAccountController") nsxServiceAccountReconcile := &nsxserviceaccountcontroller.NSXServiceAccountReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), @@ -101,12 +101,12 @@ func StartNSXServiceAccountController(mgr ctrl.Manager, commonService common.Ser } nsxServiceAccountService, err := nsxserviceaccount.InitializeNSXServiceAccount(commonService) if err != nil { - log.Error(err, "failed to initialize service", "controller", "NSXServiceAccount") + log.Error(err, "Failed to initialize service", "controller", "NSXServiceAccount") os.Exit(1) } nsxServiceAccountReconcile.Service = nsxServiceAccountService if err := nsxServiceAccountReconcile.Start(mgr); err != nil { - log.Error(err, "failed to create controller", "controller", "NSXServiceAccount") + log.Error(err, "Failed to create controller", "controller", "NSXServiceAccount") os.Exit(1) } go commonctl.GenericGarbageCollector(make(chan bool), common.GCInterval, nsxServiceAccountReconcile.CollectGarbage) @@ -121,7 +121,7 @@ func StartNetworkInfoController(mgr ctrl.Manager, vpcService *vpc.VPCService, ip networkInfoReconciler.Service = vpcService networkInfoReconciler.IPBlocksInfoService = ipblocksInfoService if err := networkInfoReconciler.Start(mgr); err != nil { - log.Error(err, "failed to create networkinfo controller", "controller", "NetworkInfo") + log.Error(err, "Failed to create networkinfo controller", "controller", "NetworkInfo") os.Exit(1) } go commonctl.GenericGarbageCollector(make(chan bool), common.GCInterval, networkInfoReconciler.CollectGarbage) @@ -136,7 +136,7 @@ func StartNamespaceController(mgr ctrl.Manager, cf *config.NSXOperatorConfig, vp } if err := nsReconciler.Start(mgr); err != nil { - log.Error(err, "failed to create namespace controller", "controller", "Namespace") + log.Error(err, "Failed to create namespace controller", "controller", "Namespace") os.Exit(1) } } @@ -151,7 +151,7 @@ func StartIPAddressAllocationController(mgr ctrl.Manager, ipAddressAllocationSer } if err := ipAddressAllocationReconciler.SetupWithManager(mgr); err != nil { - log.Error(err, "failed to create ipaddressallocation controller") + log.Error(err, "Failed to create ipaddressallocation controller") os.Exit(1) } go commonctl.GenericGarbageCollector(make(chan bool), common.GCInterval, ipAddressAllocationReconciler.CollectGarbage) @@ -190,31 +190,31 @@ func startServiceController(mgr manager.Manager, nsxClient *nsx.Client) { var err error vpcService, err = vpc.InitializeVPC(commonService) if err != nil { - log.Error(err, "failed to initialize vpc commonService", "controller", "VPC") + log.Error(err, "Failed to initialize vpc commonService", "controller", "VPC") os.Exit(1) } subnetService, err := subnetservice.InitializeSubnetService(commonService) if err != nil { - log.Error(err, "failed to initialize subnet commonService") + log.Error(err, "Failed to initialize subnet commonService") os.Exit(1) } ipAddressAllocationService, err := ipaddressallocationservice.InitializeIPAddressAllocation(commonService, vpcService, false) if err != nil { - log.Error(err, "failed to initialize ipaddressallocation commonService", "controller", "IPAddressAllocation") + log.Error(err, "Failed to initialize ipaddressallocation commonService", "controller", "IPAddressAllocation") } subnetPortService, err := subnetportservice.InitializeSubnetPort(commonService) if err != nil { - log.Error(err, "failed to initialize subnetport commonService", "controller", "SubnetPort") + log.Error(err, "Failed to initialize subnetport commonService", "controller", "SubnetPort") os.Exit(1) } nodeService, err := nodeservice.InitializeNode(commonService) if err != nil { - log.Error(err, "failed to initialize node commonService", "controller", "Node") + log.Error(err, "Failed to initialize node commonService", "controller", "Node") os.Exit(1) } staticRouteService, err := staticroute.InitializeStaticRoute(commonService, vpcService) if err != nil { - log.Error(err, "failed to initialize staticroute commonService", "controller", "StaticRoute") + log.Error(err, "Failed to initialize staticroute commonService", "controller", "StaticRoute") os.Exit(1) } ipblocksInfoService := ipblocksinfo.InitializeIPBlocksInfoService(commonService) @@ -224,14 +224,14 @@ func startServiceController(mgr manager.Manager, nsxClient *nsx.Client) { var hookServer webhook.Server if _, err := os.Stat(config.WebhookCertDir); errors.Is(err, os.ErrNotExist) { - log.Error(err, "server cert not found, disabling webhook server", "cert", config.WebhookCertDir) + log.Error(err, "Server cert not found, disabling webhook server", "cert", config.WebhookCertDir) } else { hookServer = webhook.NewServer(webhook.Options{ Port: config.WebhookServerPort, CertDir: config.WebhookCertDir, }) if err := mgr.Add(hookServer); err != nil { - log.Error(err, "failed to add hook server") + log.Error(err, "Failed to add hook server") os.Exit(1) } } @@ -258,7 +258,6 @@ func startServiceController(mgr manager.Manager, nsxClient *nsx.Client) { if cf.EnableAntreaNSXInterworking { StartNSXServiceAccountController(mgr, commonService) } - } func electMaster(mgr manager.Manager, nsxClient *nsx.Client) { @@ -272,13 +271,13 @@ func electMaster(mgr manager.Manager, nsxClient *nsx.Client) { // the new master operator is configured to wait for 15 seconds, which is // slightly longer than the default Leader Election Renew Deadline (10 seconds), // ensuring a smooth transition. - log.Info("waiting a 15-second delay to let the old instance know that it has lost its lease") + log.Info("Waiting a 15-second delay to let the old instance know that it has lost its lease") time.Sleep(15 * time.Second) startServiceController(mgr, nsxClient) } func main() { - log.Info("starting NSX Operator") + log.Info("Starting NSX Operator") mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, HealthProbeBindAddress: config.ProbeAddr, @@ -288,14 +287,14 @@ func main() { LeaderElectionID: "nsx-operator", }) if err != nil { - log.Error(err, "failed to init manager") + log.Error(err, "Failed to init manager") os.Exit(1) } // nsxClient is used to interact with NSX API. nsxClient := nsx.GetClient(cf) if nsxClient == nil { - log.Error(nil, "failed to get nsx client") + log.Error(nil, "Failed to get nsx client") os.Exit(1) } @@ -310,17 +309,17 @@ func main() { } if err := mgr.AddHealthzCheck("healthz", nsxClient.NSXChecker.CheckNSXHealth); err != nil { - log.Error(err, "failed to set up health check") + log.Error(err, "Failed to set up health check") os.Exit(1) } if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { - log.Error(err, "failed to set up ready check") + log.Error(err, "Failed to set up ready check") os.Exit(1) } - log.Info("starting manager") + log.Info("Starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { - log.Error(err, "failed to start manager") + log.Error(err, "Failed to start manager") os.Exit(1) } } @@ -340,7 +339,7 @@ func getHealthStatus(nsxClient *nsx.Client) error { func updateHealthMetricsPeriodically(nsxClient *nsx.Client) { for { if err := getHealthStatus(nsxClient); err != nil { - log.Error(err, "failed to fetch health info") + log.Error(err, "Failed to fetch health info") } select { case <-time.After(metrics.ScrapeTimeout): diff --git a/cmd_clean/main.go b/cmd_clean/main.go index 26189b297..af48476eb 100644 --- a/cmd_clean/main.go +++ b/cmd_clean/main.go @@ -81,7 +81,7 @@ func main() { log = logger.ZapLogger(cf.DefaultConfig.Debug, config.LogLevel) err := clean.Clean(ctx, cf, &log, cf.DefaultConfig.Debug, config.LogLevel) if err != nil { - log.Error(err, "failed to clean nsx resources") + log.Error(err, "Failed to clean nsx resources") os.Exit(1) } os.Exit(0) diff --git a/pkg/clean/clean.go b/pkg/clean/clean.go index c315bfa13..d7300640f 100644 --- a/pkg/clean/clean.go +++ b/pkg/clean/clean.go @@ -51,7 +51,7 @@ func Clean(ctx context.Context, cf *config.NSXOperatorConfig, log *logr.Logger, } logger.InitLog(log) - log.Info("starting NSX cleanup") + log.Info("Starting NSX cleanup") if err := cf.ValidateConfigFromCmd(); err != nil { return errors.Join(nsxutil.ValidationFailed, err) } @@ -71,7 +71,7 @@ func Clean(ctx context.Context, cf *config.NSXOperatorConfig, log *logr.Logger, retriable := func(err error) bool { if err != nil && !errors.As(err, &nsxutil.TimeoutFailed) { - log.Info("retrying to clean up NSX resources", "error", err) + log.Info("Retrying to clean up NSX resources", "error", err) return true } return false @@ -97,20 +97,20 @@ func Clean(ctx context.Context, cf *config.NSXOperatorConfig, log *logr.Logger, // delete DLB group -> delete virtual servers -> DLB services -> DLB pools -> persistent profiles for DLB if err := retry.OnError(retry.DefaultRetry, func(err error) bool { if err != nil { - log.Info("retrying to clean up DLB resources", "error", err) + log.Info("Retrying to clean up DLB resources", "error", err) return true } return false }, func() error { if err := CleanDLB(ctx, nsxClient.Cluster, cf, log); err != nil { - return fmt.Errorf("failed to clean up specific resource: %w", err) + return fmt.Errorf("Failed to clean up specific resource: %w", err) } return nil }); err != nil { return err } - log.Info("cleanup NSX resources successfully") + log.Info("Cleanup NSX resources successfully") return nil } @@ -127,7 +127,7 @@ func wrapCleanFunc(ctx context.Context, clean cleanup) func() error { func InitializeCleanupService(cf *config.NSXOperatorConfig, nsxClient *nsx.Client) (*CleanupService, error) { cleanupService := NewCleanupService() - var commonService = common.Service{ + commonService := common.Service{ NSXClient: nsxClient, NSXConfig: cf, } diff --git a/pkg/controllers/common/utils.go b/pkg/controllers/common/utils.go index 35c3e0f65..3fe77f5d5 100644 --- a/pkg/controllers/common/utils.go +++ b/pkg/controllers/common/utils.go @@ -46,11 +46,11 @@ func AllocateSubnetFromSubnetSet(subnetSet *v1alpha1.SubnetSet, vpcService servi if tags == nil { return "", errors.New("failed to generate subnet tags") } - log.Info("the existing subnets are not available, creating new subnet", "subnetList", subnetList, "subnetSet.Name", subnetSet.Name, "subnetSet.Namespace", subnetSet.Namespace) + log.Info("The existing subnets are not available, creating new subnet", "subnetList", subnetList, "subnetSet.Name", subnetSet.Name, "subnetSet.Namespace", subnetSet.Namespace) vpcInfoList := vpcService.ListVPCInfo(subnetSet.Namespace) if len(vpcInfoList) == 0 { err := errors.New("no VPC found") - log.Error(err, "failed to allocate Subnet") + log.Error(err, "Failed to allocate Subnet") return "", err } return subnetService.CreateOrUpdateSubnet(subnetSet, vpcInfoList[0], tags) @@ -60,14 +60,14 @@ func getSharedNamespaceForNamespace(client k8sclient.Client, ctx context.Context namespace := &v1.Namespace{} namespacedName := types.NamespacedName{Name: namespaceName} if err := client.Get(ctx, namespacedName, namespace); err != nil { - log.Error(err, "failed to get target namespace during getting VPC for namespace") + log.Error(err, "Failed to get target namespace during getting VPC for namespace") return "", err } sharedNamespaceName, exists := namespace.Annotations[servicecommon.AnnotationSharedVPCNamespace] if !exists { return "", nil } - log.Info("got shared VPC namespace", "current namespace", namespaceName, "shared namespace", sharedNamespaceName) + log.Info("Got shared VPC namespace", "current namespace", namespaceName, "shared namespace", sharedNamespaceName) return sharedNamespaceName, nil } diff --git a/pkg/controllers/networkpolicy/networkpolicy_controller.go b/pkg/controllers/networkpolicy/networkpolicy_controller.go index 74607f829..5a99396db 100644 --- a/pkg/controllers/networkpolicy/networkpolicy_controller.go +++ b/pkg/controllers/networkpolicy/networkpolicy_controller.go @@ -90,7 +90,7 @@ func cleanNetworkPolicyErrorAnnotation(ctx context.Context, networkPolicy *netwo } updateErr := client.Update(ctx, networkPolicy) if updateErr != nil { - log.Error(updateErr, "failed to clean NetworkPolicy annotation") + log.Error(updateErr, "Failed to clean NetworkPolicy annotation") } log.Info("Clean NetworkPolicy annotation") } @@ -108,13 +108,13 @@ func (r *NetworkPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reques if err := r.Client.Get(ctx, req.NamespacedName, networkPolicy); err != nil { if apierrors.IsNotFound(err) { if err := r.deleteNetworkPolicyByName(req.Namespace, req.Name); err != nil { - log.Error(err, "failed to delete NetworkPolicy", "networkpolicy", req.NamespacedName) + log.Error(err, "Failed to delete NetworkPolicy", "networkpolicy", req.NamespacedName) return ResultRequeue, err } return ResultNormal, nil } // In case that client is unable to check CR - log.Error(err, "client is unable to fetch NetworkPolicy CR", "req", req.NamespacedName) + log.Error(err, "Failed to fetch NetworkPolicy CR", "req", req.NamespacedName) return ResultRequeue, err } @@ -134,7 +134,7 @@ func (r *NetworkPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reques setNetworkPolicyErrorAnnotation(ctx, networkPolicy, r.Client, common.ErrorNoDFWLicense) os.Exit(1) } - log.Error(err, "create or update failed, would retry exponentially", "networkpolicy", req.NamespacedName) + log.Error(err, "Failed to create or update, would retry exponentially", "networkpolicy", req.NamespacedName) updateFail(r, ctx, networkPolicy, &err) return ResultRequeue, err } @@ -145,7 +145,7 @@ func (r *NetworkPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reques metrics.CounterInc(r.Service.NSXConfig, metrics.ControllerDeleteTotal, MetricResType) if err := r.Service.DeleteSecurityPolicy(networkPolicy, false, false, servicecommon.ResourceTypeNetworkPolicy); err != nil { - log.Error(err, "deletion failed, would retry exponentially", "networkpolicy", req.NamespacedName) + log.Error(err, "Failed to Delete, would retry exponentially", "networkpolicy", req.NamespacedName) deleteFail(r, ctx, networkPolicy, &err) return ResultRequeue, err } @@ -217,7 +217,7 @@ func (r *NetworkPolicyReconciler) deleteNetworkPolicyByName(ns, name string) err log.Info("Deleting NetworkPolicy", "networkPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) if err := r.Service.DeleteSecurityPolicy(types.UID(uid), false, false, servicecommon.ResourceTypeNetworkPolicy); err != nil { - log.Error(err, "failed to delete NetworkPolicy", "networkPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) + log.Error(err, "Failed to delete NetworkPolicy", "networkPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) return err } log.Info("Successfully deleted NetworkPolicy", "networkPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) @@ -229,7 +229,7 @@ func (r *NetworkPolicyReconciler) listNetworkPolciyCRIDs() (sets.Set[string], er networkPolicyList := &networkingv1.NetworkPolicyList{} err := r.Client.List(context.Background(), networkPolicyList) if err != nil { - log.Error(err, "failed to list NetworkPolicy CRs") + log.Error(err, "Failed to list NetworkPolicy CRs") return nil, err } @@ -249,7 +249,7 @@ func StartNetworkPolicyController(mgr ctrl.Manager, commonService servicecommon. } networkPolicyReconcile.Service = securitypolicy.GetSecurityService(commonService, vpcService) if err := networkPolicyReconcile.Start(mgr); err != nil { - log.Error(err, "failed to create controller", "controller", "NetworkPolicy") + log.Error(err, "Failed to create controller", "controller", "NetworkPolicy") os.Exit(1) } go common.GenericGarbageCollector(make(chan bool), servicecommon.GCInterval, networkPolicyReconcile.CollectGarbage) diff --git a/pkg/controllers/securitypolicy/namespace_handler.go b/pkg/controllers/securitypolicy/namespace_handler.go index 5e0cc2110..f4a01816b 100644 --- a/pkg/controllers/securitypolicy/namespace_handler.go +++ b/pkg/controllers/securitypolicy/namespace_handler.go @@ -40,7 +40,7 @@ func (e *EnqueueRequestForNamespace) Generic(_ context.Context, _ event.GenericE func (e *EnqueueRequestForNamespace) Update(_ context.Context, updateEvent event.UpdateEvent, l workqueue.RateLimitingInterface) { obj := updateEvent.ObjectNew.(*v1.Namespace) if isInSysNs, err := util.IsSystemNamespace(nil, "", obj); err != nil { - log.Error(err, "failed to fetch namespace", "namespace", obj.Name) + log.Error(err, "Failed to fetch namespace", "namespace", obj.Name) return } else if isInSysNs { log.V(2).Info("NameSpace is in system namespace, ignore it", "namespace", obj.Name) @@ -50,7 +50,7 @@ func (e *EnqueueRequestForNamespace) Update(_ context.Context, updateEvent event podList := &v1.PodList{} err := e.Client.List(context.Background(), podList, client.InNamespace(obj.Name)) if err != nil { - log.Error(err, "failed to list pod in namespace", "namespace", obj.Name) + log.Error(err, "Failed to list pod in namespace", "namespace", obj.Name) return } @@ -68,7 +68,7 @@ func (e *EnqueueRequestForNamespace) Update(_ context.Context, updateEvent event err = reconcileSecurityPolicy(e.SecurityPolicyReconciler, e.Client, podList.Items, l) if err != nil { - log.Error(err, "failed to reconcile security policy for namedport check") + log.Error(err, "Failed to reconcile security policy for namedport check") } } diff --git a/pkg/controllers/securitypolicy/pod_handler.go b/pkg/controllers/securitypolicy/pod_handler.go index 5e21b350d..3320d9ac6 100644 --- a/pkg/controllers/securitypolicy/pod_handler.go +++ b/pkg/controllers/securitypolicy/pod_handler.go @@ -59,21 +59,21 @@ func (e *EnqueueRequestForPod) Raw(evt interface{}, q workqueue.RateLimitingInte case event.GenericEvent: obj = et.Object.(*v1.Pod) default: - log.Error(nil, "unknown event type", "event", evt) + log.Error(nil, "Unknown event type", "event", evt) } pod := obj.(*v1.Pod) if isInSysNs, err := util.IsSystemNamespace(e.Client, pod.Namespace, nil); err != nil { - log.Error(err, "failed to fetch namespace", "namespace", pod.Namespace) + log.Error(err, "Failed to fetch namespace", "namespace", pod.Namespace) return } else if isInSysNs { - log.V(2).Info("pod is in system namespace, do nothing") + log.V(2).Info("POD is in system namespace, do nothing") return } pods = append(pods, *pod) err := reconcileSecurityPolicy(e.SecurityPolicyReconciler, e.Client, pods, q) if err != nil { - log.Error(err, "failed to reconcile security policy") + log.Error(err, "Failed to reconcile security policy") } } diff --git a/pkg/controllers/securitypolicy/securitypolicy_controller.go b/pkg/controllers/securitypolicy/securitypolicy_controller.go index 4905163a4..5cc27f2b4 100644 --- a/pkg/controllers/securitypolicy/securitypolicy_controller.go +++ b/pkg/controllers/securitypolicy/securitypolicy_controller.go @@ -105,7 +105,7 @@ func setSecurityPolicyErrorAnnotation(ctx context.Context, securityPolicy *v1alp updateErr = client.Update(ctx, securityPolicy) } if updateErr != nil { - log.Error(updateErr, "failed to update SecurityPolicy with error annotation") + log.Error(updateErr, "Failed to update SecurityPolicy with error annotation") } log.Info("Updated SecurityPolicy with error annotation", "error", info) } @@ -126,7 +126,7 @@ func cleanSecurityPolicyErrorAnnotation(ctx context.Context, securityPolicy *v1a updateErr = client.Update(ctx, securityPolicy) } if updateErr != nil { - log.Error(updateErr, "failed to clean SecurityPolicy annotation") + log.Error(updateErr, "Failed to clean SecurityPolicy annotation") } log.Info("Clean SecurityPolicy annotation") } @@ -150,13 +150,13 @@ func (r *SecurityPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reque if err := r.Client.Get(ctx, req.NamespacedName, obj); err != nil { if apierrors.IsNotFound(err) { if err := r.deleteSecurityPolicyByName(req.Namespace, req.Name); err != nil { - log.Error(err, "failed to delete SecurityPolicy", "securitypolicy", req.NamespacedName) + log.Error(err, "Failed to delete SecurityPolicy", "securitypolicy", req.NamespacedName) return ResultRequeue, err } return ResultNormal, nil } // In case that client is unable to check CR - log.Error(err, "client is unable to fetch SecurityPolicy CR", "req", req.NamespacedName) + log.Error(err, "Failed to fetch SecurityPolicy CR", "req", req.NamespacedName) return ResultRequeue, err } @@ -187,7 +187,7 @@ func (r *SecurityPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reque if isCRInSysNs, err := util.IsSystemNamespace(r.Client, req.Namespace, nil); err != nil { err = errors.New("fetch namespace associated with security policy CR failed") - log.Error(err, "would retry exponentially", "securitypolicy", req.NamespacedName) + log.Error(err, "Would retry exponentially", "securitypolicy", req.NamespacedName) updateFail(r, ctx, realObj, &err) return ResultRequeue, err } else if isCRInSysNs { @@ -210,7 +210,7 @@ func (r *SecurityPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reque setSecurityPolicyErrorAnnotation(ctx, realObj, securitypolicy.IsVPCEnabled(r.Service), r.Client, common.ErrorNoDFWLicense) os.Exit(1) } - log.Error(err, "create or update failed, would retry exponentially", "securitypolicy", req.NamespacedName) + log.Error(err, "Failed to create or update, would retry exponentially", "securitypolicy", req.NamespacedName) updateFail(r, ctx, realObj, &err) return ResultRequeue, err } @@ -224,14 +224,14 @@ func (r *SecurityPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reque if controllerutil.ContainsFinalizer(obj, finalizerName) { controllerutil.RemoveFinalizer(obj, finalizerName) if err := r.Client.Update(ctx, obj); err != nil { - log.Error(err, "finalizer remove failed, would retry exponentially", "securitypolicy", req.NamespacedName) + log.Error(err, "Failed to remove finalizer, would retry exponentially", "securitypolicy", req.NamespacedName) deleteFail(r, ctx, realObj, &err) return ResultRequeue, err } log.V(1).Info("Removed finalizer", "securitypolicy", req.NamespacedName) } if err := r.Service.DeleteSecurityPolicy(realObj.UID, false, false, servicecommon.ResourceTypeSecurityPolicy); err != nil { - log.Error(err, "deletion failed, would retry exponentially", "securitypolicy", req.NamespacedName) + log.Error(err, "Failed to delete, would retry exponentially", "securitypolicy", req.NamespacedName) deleteFail(r, ctx, realObj, &err) return ResultRequeue, err } @@ -399,7 +399,7 @@ func (r *SecurityPolicyReconciler) deleteSecurityPolicyByName(ns, name string) e log.Info("Deleting SecurityPolicy", "securityPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) if err := r.Service.DeleteSecurityPolicy(types.UID(uid), false, false, servicecommon.ResourceTypeSecurityPolicy); err != nil { - log.Error(err, "failed to delete SecurityPolicy", "securityPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) + log.Error(err, "Failed to delete SecurityPolicy", "securityPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) return err } log.Info("Successfully deleted SecurityPolicy", "securityPolicyUID", uid, "nsxSecurityPolicyId", *item.Id) @@ -416,7 +416,7 @@ func (r *SecurityPolicyReconciler) listSecurityPolciyCRIDs() (sets.Set[string], } err := r.Client.List(context.Background(), objectList) if err != nil { - log.Error(err, "failed to list SecurityPolicy CR") + log.Error(err, "Failed to list SecurityPolicy CR") return nil, err } @@ -449,7 +449,7 @@ func reconcileSecurityPolicy(r *SecurityPolicyReconciler, pkgclient client.Clien } err := pkgclient.List(context.Background(), spList) if err != nil { - log.Error(err, "failed to list all the security policy") + log.Error(err, "Failed to list all the security policy") return err } @@ -505,7 +505,7 @@ func StartSecurityPolicyController(mgr ctrl.Manager, commonService servicecommon } securityPolicyReconcile.Service = securitypolicy.GetSecurityService(commonService, vpcService) if err := securityPolicyReconcile.Start(mgr); err != nil { - log.Error(err, "failed to create controller", "controller", "SecurityPolicy") + log.Error(err, "Failed to create controller", "controller", "SecurityPolicy") os.Exit(1) } go common.GenericGarbageCollector(make(chan bool), servicecommon.GCInterval, securityPolicyReconcile.CollectGarbage) diff --git a/pkg/controllers/service/service_lb_controller.go b/pkg/controllers/service/service_lb_controller.go index 38bc14f84..38f3be6e1 100644 --- a/pkg/controllers/service/service_lb_controller.go +++ b/pkg/controllers/service/service_lb_controller.go @@ -51,16 +51,16 @@ func (r *ServiceLbReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( log.Info("Reconciling LB CR", "service", req.NamespacedName) startTime := time.Now() defer func() { - log.Info("Finished reconciling LB service", "lbService", req.NamespacedName, "duration(ms)", time.Since(startTime).Milliseconds()) + log.Info("Finished reconciling LB service", "LBService", req.NamespacedName, "duration(ms)", time.Since(startTime).Milliseconds()) }() if err := r.Client.Get(ctx, req.NamespacedName, service); err != nil { - log.Error(err, "unable to fetch lb service", "req", req.NamespacedName) + log.Error(err, "Failed to fetch LB service", "req", req.NamespacedName) return ResultNormal, client.IgnoreNotFound(err) } if service.Spec.Type == v1.ServiceTypeLoadBalancer { - log.Info("Reconciling lb service", "lbService", req.NamespacedName) + log.Info("Reconciling LB service", "LBService", req.NamespacedName) metrics.CounterInc(r.Service.NSXConfig, metrics.ControllerSyncTotal, MetricResType) if service.ObjectMeta.DeletionTimestamp.IsZero() { @@ -123,19 +123,19 @@ func isServiceLbStatusIpModeSupported(c *rest.Config) bool { clientset, err := clientset.NewForConfig(c) if err != nil { - log.Error(err, "failed to create clientset") + log.Error(err, "Failed to create clientset") return false } serverVersion, err := clientset.Discovery().ServerVersion() if err != nil { - log.Error(err, "failed to get server Kubernetes version") + log.Error(err, "Failed to get server Kubernetes version") return false } runningVersion, err := version.ParseGeneric(serverVersion.String()) if err != nil { - log.Error(err, "unexpected error parsing server Kubernetes version", "K8sVersion", runningVersion.String()) + log.Error(err, "Failed to parse server Kubernetes version", "K8sVersion", runningVersion.String()) return false } @@ -153,10 +153,10 @@ func StartServiceLbController(mgr ctrl.Manager, commonService servicecommon.Serv } serviceLbReconciler.Service = &commonService if err := serviceLbReconciler.Start(mgr); err != nil { - log.Error(err, "failed to create controller", "controller", "ServiceLb") + log.Error(err, "Failed to create controller", "controller", "ServiceLb") os.Exit(1) } } else { - log.Info("Service Lb controller isn't started since load balancer service ipMode supporting needs K8s version at least 1.29.0") + log.Info("Service LB controller isn't started since load balancer service ipMode supporting needs K8s version at least 1.29.0") } } diff --git a/pkg/controllers/subnetset/subnetset_controller.go b/pkg/controllers/subnetset/subnetset_controller.go index 4a91c4c70..511acd1c0 100644 --- a/pkg/controllers/subnetset/subnetset_controller.go +++ b/pkg/controllers/subnetset/subnetset_controller.go @@ -129,7 +129,7 @@ func (r *SubnetSetReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( return ResultRequeue, errors.New("failed to generate SubnetSet tags") } // tags cannot exceed maximum size 26 - if len(tags) > servicecommon.TagsCountMax { + if len(tags) > servicecommon.MaxTagsCount { errorMsg := fmt.Sprintf("tags cannot exceed maximum size 26, tags length: %d", len(tags)) log.Error(nil, "Exceed tags limit, would not retry", "SubnetSet", req.NamespacedName) updateFail(r, ctx, subnetsetCR, errorMsg) diff --git a/pkg/controllers/subnetset/subnetset_controller_test.go b/pkg/controllers/subnetset/subnetset_controller_test.go index da435e4b2..3f4e6d50c 100644 --- a/pkg/controllers/subnetset/subnetset_controller_test.go +++ b/pkg/controllers/subnetset/subnetset_controller_test.go @@ -190,7 +190,7 @@ func TestReconcile(t *testing.T) { }) tags := []model.Tag{{Scope: common.String(common.TagScopeSubnetCRUID), Tag: common.String("fake-tag")}} - for i := 0; i < common.TagsCountMax; i++ { + for i := 0; i < common.MaxTagsCount; i++ { key := fmt.Sprintf("fake-tag-key-%d", i) value := common.String(fmt.Sprintf("fake-tag-value-%d", i)) tags = append(tags, model.Tag{Scope: &key, Tag: value}) @@ -421,7 +421,6 @@ func TestReconcile_DeleteSubnetSet(t *testing.T) { assert.Equal(t, testCase.expectRes, res) }) } - } // Test Reconcile - SubnetSet Deletion @@ -634,8 +633,7 @@ func (m *MockManager) Start(context.Context) error { return nil } -type mockWebhookServer struct { -} +type mockWebhookServer struct{} func (m *mockWebhookServer) Register(path string, hook http.Handler) { return diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index b4c8088a9..4c46887fe 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -111,7 +111,7 @@ func Register(m ...prometheus.Collector) { // Initialize Prometheus metrics collection. func InitializePrometheusMetrics() { - log.Info("initializing prometheus metrics") + log.Info("Initializing prometheus metrics") Register( NSXOperatorHealthStats, ControllerSyncTotal, diff --git a/pkg/nsx/auth/jwt/JWTtokenprovider.go b/pkg/nsx/auth/jwt/JWTtokenprovider.go index bd82f999b..cdb905672 100644 --- a/pkg/nsx/auth/jwt/JWTtokenprovider.go +++ b/pkg/nsx/auth/jwt/JWTtokenprovider.go @@ -16,9 +16,7 @@ const ( VC_SVCACCOUNT_PWD_PATH = "/etc/nsx-ujo/vc/password" ) -var ( - log = &logger.Log -) +var log = &logger.Log type JWTTokenProvider struct { cache *JWTCache @@ -36,7 +34,7 @@ func NewTokenProvider(vcEndpoint string, port int, ssoDomain, user, password str // not load username/password, not create vapi session, defer them to cache.refreshJWT tesClient, err := NewTESClient(vcEndpoint, port, ssoDomain, user, password, caCert, insecure, scheme) if err != nil { - log.Error(err, "failed to create tes client") + log.Error(err, "Failed to create tes client") return nil, err } diff --git a/pkg/nsx/auth/jwt/jwtcache.go b/pkg/nsx/auth/jwt/jwtcache.go index 911afcd44..f35537ce2 100644 --- a/pkg/nsx/auth/jwt/jwtcache.go +++ b/pkg/nsx/auth/jwt/jwtcache.go @@ -46,13 +46,13 @@ func (cache *JWTCache) GetJWT(refreshToken bool) (string, error) { } jwt, err := cache.refreshJWT() if err != nil || jwt == "" { - log.V(1).Info("get JWT", "Refresh JWT error", err) + log.V(1).Info("Get JWT", "Refresh JWT error", err) cache.tesClient.signer = nil return "", err } exp, err := cache.getJWTExpire(jwt) if err != nil { - log.Info("get JWT", "get JWT expire", err) + log.Info("Get JWT", "get JWT expire", err) cache.expire = exp return "", err } diff --git a/pkg/nsx/auth/jwt/tesclient.go b/pkg/nsx/auth/jwt/tesclient.go index 7444c1a1a..d6477c3d1 100644 --- a/pkg/nsx/auth/jwt/tesclient.go +++ b/pkg/nsx/auth/jwt/tesclient.go @@ -32,7 +32,7 @@ type TESClient struct { func NewTESClient(hostname string, port int, ssoDomain string, username, password string, caCertPem []byte, insecureSkipVerify bool, scheme string) (*TESClient, error) { client, err := NewVCClient(hostname, port, ssoDomain, username, password, caCertPem, insecureSkipVerify, scheme) if err != nil { - log.Error(err, "new TESClient failed") + log.Error(err, "Failed to create new TESClient") return nil, err } return &TESClient{client}, nil @@ -58,7 +58,7 @@ func newTokenExchange(samlToken string, useOldAudience bool) *tokenExchange { func (client *TESClient) ExchangeJWT(samlToken string, useOldAudience bool) (string, error) { // assume that response should have "access_token" field // no retry while hit "Unknown audience value" error - log.V(1).Info("sending saml token to TES for JWT") + log.V(1).Info("Sending saml token to TES for JWT") exchange := newTokenExchange(samlToken, useOldAudience) body, err := json.Marshal(*exchange) @@ -72,9 +72,9 @@ func (client *TESClient) ExchangeJWT(samlToken string, useOldAudience bool) (str tesErr := client.HandleRequest("/vcenter/tokenservice/token-exchange", body, &res) if tesErr != nil { msg := fmt.Sprintf("failed to exchange JWT due to error :%v", tesErr) - log.Error(tesErr, "failed to exchange JWT") + log.Error(tesErr, "Failed to exchange JWT") return "", errors.New(msg) } - log.V(1).Info("exchanged JWT") + log.V(1).Info("Exchanged JWT") return res.Value["access_token"].(string), nil } diff --git a/pkg/nsx/auth/jwt/vcclient.go b/pkg/nsx/auth/jwt/vcclient.go index 9e4fe7582..fd80b49bb 100644 --- a/pkg/nsx/auth/jwt/vcclient.go +++ b/pkg/nsx/auth/jwt/vcclient.go @@ -53,7 +53,7 @@ func createHttpClient(insecureSkipVerify bool, caCertPem []byte) *http.Client { TLSClientConfig: tlsConfig, } if len(caCertPem) > 0 { - log.V(1).Info("append CA cert") + log.V(1).Info("Append CA cert") clientCertPool := x509.NewCertPool() clientCertPool.AppendCertsFromPEM(caCertPem) tlsConfig.RootCAs = clientCertPool @@ -82,7 +82,7 @@ func NewVCClient(hostname string, port int, ssoDomain string, userName, password // createVAPISession creates a VAPI session using the specified STS signer and sets it on the vcClient. func (vcClient *VCClient) createVAPISession() (string, error) { - log.Info("creating new vapi session for vcClient") + log.Info("Creating new vapi session for vcClient") request, err := vcClient.prepareRequest(http.MethodPost, "com/vmware/cis/session", nil) if err != nil { return "", err @@ -101,7 +101,7 @@ func (vcClient *VCClient) createVAPISession() (string, error) { if !ok { msg := fmt.Sprintf("unexpected session data %v from vapi-endpoint", sessionData) err := errors.New(msg) - log.Error(err, "failed to create VAPI session") + log.Error(err, "Failed to create VAPI session") return "", errors.New(msg) } return session, nil @@ -131,14 +131,14 @@ func (vcClient *VCClient) reloadUsernamePass() error { } f, err := os.ReadFile(VC_SVCACCOUNT_USER_PATH) if err != nil { - log.Error(err, "failed to read user name") + log.Error(err, "Failed to read user name") return err } username := strings.TrimRight(string(f), "\n\r") f, err = os.ReadFile(VC_SVCACCOUNT_PWD_PATH) if err != nil { - log.Error(err, "failed to read password") + log.Error(err, "Failed to read password") return err } password := strings.TrimRight(string(f), "\n\r") @@ -155,7 +155,7 @@ func (vcClient *VCClient) reloadUsernamePass() error { // createHOKSigner creates a Hok token for the service account user. func (vcClient *VCClient) createHOKSigner() (*sts.Signer, error) { - log.V(1).Info("creating Holder of Key signer") + log.V(1).Info("Creating Holder of Key signer") userName := vcClient.url.User.Username() password, _ := vcClient.url.User.Password() client, err := vcClient.getorCreateSTSClient() @@ -165,7 +165,7 @@ func (vcClient *VCClient) createHOKSigner() (*sts.Signer, error) { cert, err := createCertificate(userName) if err != nil { - log.Error(err, "failed to process service account keypair") + log.Error(err, "Failed to process service account keypair") return nil, err } @@ -178,7 +178,7 @@ func (vcClient *VCClient) createHOKSigner() (*sts.Signer, error) { signed, err := client.Issue(context.Background(), req) if err != nil { - log.Error(err, "failed to get token from cert,key pair") + log.Error(err, "Failed to get token from cert,key pair") return nil, err } return signed, nil @@ -209,14 +209,14 @@ func (vcClient *VCClient) createSCClient(vimClient *vim25.Client) *soap.Client { } func (vcClient *VCClient) createVimClient(ctx context.Context, vimSdkURL string) (*vim25.Client, error) { - log.V(1).Info("creating vmomi client") + log.V(1).Info("Creating vmomi client") vcURL, err := url.Parse(vimSdkURL) if err != nil { return nil, err } vimClient, err := vim25.NewClient(ctx, soap.NewClient(vcURL, true)) if err != nil { - log.Error(err, "failed to create VIM client", "vimSdkURL", vimSdkURL) + log.Error(err, "Failed to create VIM client", "vimSdkURL", vimSdkURL) return nil, err } return vimClient, nil @@ -247,7 +247,6 @@ func (client *VCClient) prepareRequest(method string, urlPath string, data []byt req.Header.Set("Content-Type", "application/json") if client.signer != nil { client.signer.SignRequest(req) - } else if client.session != "" { req.Header.Set("vmware-api-session-id", client.session) } else { @@ -259,19 +258,19 @@ func (client *VCClient) prepareRequest(method string, urlPath string, data []byt func createCertificate(userName string) (*tls.Certificate, error) { privKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { - log.Error(err, "failed to generate RSA private key") + log.Error(err, "Failed to generate RSA private key") return nil, err } serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { - log.Error(err, "failed to generate random serial number") + log.Error(err, "Failed to generate random serial number") return nil, err } currentTime := time.Now() notBeforeTime := currentTime.Add(-6 * time.Minute).UTC() notAfterTime := currentTime.Add(60 * time.Minute).UTC() - log.V(1).Info("generating certificate", "user", userName, "notBefore", notBeforeTime, "notAfter", notAfterTime) + log.V(1).Info("Generating certificate", "user", userName, "notBefore", notBeforeTime, "notAfter", notAfterTime) certTemplate := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{CommonName: userName}, @@ -284,7 +283,7 @@ func createCertificate(userName string) (*tls.Certificate, error) { certBytes, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, &privKey.PublicKey, privKey) if err != nil { - log.Error(err, "failed to generate certificate") + log.Error(err, "Failed to generate certificate") return nil, err } @@ -292,7 +291,7 @@ func createCertificate(userName string) (*tls.Certificate, error) { privateKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privKey)}) certificate, err := tls.X509KeyPair([]byte(cert), []byte(privateKey)) if err != nil { - log.Error(err, "failed to process service account keypair") + log.Error(err, "Failed to process service account keypair") return nil, err } diff --git a/pkg/nsx/client.go b/pkg/nsx/client.go index d0922bc6d..e6bb1ed68 100644 --- a/pkg/nsx/client.go +++ b/pkg/nsx/client.go @@ -252,19 +252,19 @@ func GetClient(cf *config.NSXOperatorConfig) *Client { // So, it's unnecessary to exit even if failed in the first time if !nsxClient.NSXCheckVersion(SecurityPolicy) { err := errors.New("SecurityPolicy feature support check failed") - log.Error(err, "initial NSX version check for SecurityPolicy got error") + log.Error(err, "Initial NSX version check for SecurityPolicy got error") } if !nsxClient.NSXCheckVersion(ServiceAccount) { err := errors.New("NSXServiceAccount feature support check failed") - log.Error(err, "initial NSX version check for NSXServiceAccount got error") + log.Error(err, "Initial NSX version check for NSXServiceAccount got error") } if !nsxClient.NSXCheckVersion(ServiceAccountRestore) { err := errors.New("NSXServiceAccountRestore feature support check failed") - log.Error(err, "initial NSX version check for NSXServiceAccountRestore got error") + log.Error(err, "Initial NSX version check for NSXServiceAccountRestore got error") } if !nsxClient.NSXCheckVersion(ServiceAccountCertRotation) { err := errors.New("ServiceAccountCertRotation feature support check failed") - log.Error(err, "initial NSX version check for ServiceAccountCertRotation got error") + log.Error(err, "Initial NSX version check for ServiceAccountCertRotation got error") } return nsxClient @@ -277,12 +277,12 @@ func (client *Client) NSXCheckVersion(feature int) bool { nsxVersion, err := client.NSXVerChecker.cluster.GetVersion() if err != nil { - log.Error(err, "get version error") + log.Error(err, "Get version error") return false } err = nsxVersion.Validate() if err != nil { - log.Error(err, "validate version error") + log.Error(err, "Validate version error") return false } @@ -313,14 +313,14 @@ func (client *Client) ValidateLicense(init bool) error { } if !util.IsLicensed(util.FeatureContainer) { err = errors.New("NSX license check failed") - log.Error(err, "container license is not supported") + log.Error(err, "Container license is not supported") return err } if !init { newContainerLicense := util.IsLicensed(util.FeatureContainer) newDfwLicense := util.IsLicensed(util.FeatureDFW) if newContainerLicense != oldContainerLicense || newDfwLicense != oldDfwLicense { - log.Info("license updated, reset", "container license new value", newContainerLicense, "DFW license new value", newDfwLicense, "container license old value", oldContainerLicense, "DFW license old value", oldDfwLicense) + log.Info("License updated, reset", "container license new value", newContainerLicense, "DFW license new value", newDfwLicense, "container license old value", oldContainerLicense, "DFW license old value", oldDfwLicense) return errors.New("license updated") } } diff --git a/pkg/nsx/cluster.go b/pkg/nsx/cluster.go index 4ef866d4c..438ac844e 100644 --- a/pkg/nsx/cluster.go +++ b/pkg/nsx/cluster.go @@ -36,6 +36,7 @@ const ( // GREEN means endpoints status are UP. GREEN ClusterHealth = "GREEN" ) + const ( EnvoyUrlWithCert = "http://%s:%d/external-cert/http1/%s" EnvoyUrlWithThumbprint = "http://%s:%d/external-tp/http1/%s/%s" @@ -68,7 +69,7 @@ var ( // NewCluster creates a cluster based on nsx Config. func NewCluster(config *Config) (*Cluster, error) { - log.Info("creating cluster") + log.Info("Creating cluster") cluster := &Cluster{} cluster.config = config cluster.transport = cluster.createTransport(time.Duration(config.ConnIdleTimeout)) @@ -78,7 +79,7 @@ func NewCluster(config *Config) (*Cluster, error) { r := ratelimiter.NewRateLimiter(config.APIRateMode) eps, err := cluster.createEndpoints(config.APIManagers, cluster.client, cluster.noBalancerClient, r, config.TokenProvider) if err != nil { - log.Error(err, "creating cluster failed") + log.Error(err, "Failed to create cluster") return nil, err } @@ -119,10 +120,10 @@ func (cluster *Cluster) loadCAforEnvoy() { cert := util.CertPemBytesToHeader(caFile) if cert != "" { cluster.endpoints[i].caFile = cert - log.Info("load CA for envoy sidecar", "caFile", caFile) + log.Info("Load CA for envoy sidecar", "caFile", caFile) return } else { - log.Info("failed to load CA for envoy sidecar", "caFile", caFile) + log.Info("Failed to load CA for envoy sidecar", "caFile", caFile) } } @@ -138,7 +139,7 @@ func (cluster *Cluster) CreateServerUrl(host string, scheme string) string { index := strings.Index(host, ":") mgrIP := "" if index == -1 { - log.Info("no port provided, use default port 443", "host", host) + log.Info("No port provided, use default port 443", "host", host) mgrIP = host + "/443" } else { mgrIP = strings.ReplaceAll(host, ":", "/") @@ -156,7 +157,7 @@ func (cluster *Cluster) CreateServerUrl(host string, scheme string) string { } else { serverUrl = fmt.Sprintf("%s://%s", scheme, host) } - log.V(1).Info("create serverUrl", "serverUrl", serverUrl) + log.V(1).Info("Create serverUrl", "serverUrl", serverUrl) return serverUrl } @@ -222,29 +223,29 @@ func (cluster *Cluster) createTransport(idle time.Duration) *Transport { tr := &http.Transport{ IdleConnTimeout: idle * time.Second, } - log.Info("cluster envoy mode", "envoy mode", cluster.UsingEnvoy()) + log.Info("Cluster envoy mode", "envoy mode", cluster.UsingEnvoy()) if cluster.config.Insecure == false { dial := func(ctx context.Context, network, addr string) (net.Conn, error) { // #nosec G402: ignore insecure options var config *tls.Config cafile := cluster.getCaFile(addr) caCount := len(cluster.config.CAFile) - log.Info("create Transport", "ca file", cafile, "caCount", caCount) + log.Info("Create Transport", "ca file", cafile, "caCount", caCount) if caCount > 0 { caCert, err := os.ReadFile(cafile) if err != nil { - log.Error(err, "create transport", "read ca file", cafile) + log.Error(err, "Create transport", "read ca file", cafile) return nil, err } config, err = util.GetTLSConfigForCert(caCert) if err != nil { - log.Error(err, "create transport", "get tls config from cert", cafile) + log.Error(err, "Create transport", "get TLS config from cert", cafile) return nil, err } } else { thumbprint := cluster.getThumbprint(addr) tpCount := len(cluster.config.Thumbprint) - log.Info("create Transport", "thumbprint", thumbprint, "tpCount", tpCount) + log.Info("Create Transport", "thumbprint", thumbprint, "tpCount", tpCount) // #nosec G402: ignore insecure options config = &tls.Config{ InsecureSkipVerify: true, @@ -261,7 +262,7 @@ func (cluster *Cluster) createTransport(idle time.Duration) *Transport { } conn, err := tls.Dial(network, addr, config) if err != nil { - log.Error(err, "transport connect to", "addr", addr) + log.Error(err, "Failed to do transport connect to", "addr", addr) return nil, err } @@ -342,19 +343,19 @@ func (cluster *Cluster) GetVersion() (*NsxVersion, error) { serverUrl := cluster.CreateServerUrl(cluster.endpoints[0].Host(), cluster.endpoints[0].Scheme()) req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/v1/node/version", serverUrl), nil) if err != nil { - log.Error(err, "failed to create http request") + log.Error(err, "Failed to create HTTP request") return nil, err } - log.V(1).Info("get version", "url", req.URL) + log.V(1).Info("Get version", "url", req.URL) err = ep.UpdateHttpRequestAuth(req) if err != nil { - log.Error(err, "keep alive update auth error") + log.Error(err, "Failed to keep alive update auth") return nil, err } ep.UpdateCAforEnvoy(req) resp, err := ep.noBalancerClient.Do(req) if err != nil { - log.Error(err, "failed to get nsx version") + log.Error(err, "Failed to get NSX version") return nil, err } err, _ = util.HandleHTTPResponse(resp, nsxVersion, true) @@ -365,7 +366,7 @@ func (cluster *Cluster) GetVersion() (*NsxVersion, error) { func (cluster *Cluster) HttpGet(url string) (map[string]interface{}, error) { resp, err := cluster.httpAction(url, "GET") if err != nil { - log.Error(err, "failed to do http GET operation") + log.Error(err, "Failed to do HTTP GET operation") return nil, err } respJson := make(map[string]interface{}) @@ -379,7 +380,7 @@ func (cluster *Cluster) httpAction(url, method string) (*http.Response, error) { url = fmt.Sprintf("%s/%s", serverUrl, url) req, err := http.NewRequest(method, url, nil) if err != nil { - log.Error(err, "failed to create http request") + log.Error(err, "Failed to create HTTP request") return nil, err } log.V(1).Info(method+" url", "url", req.URL) @@ -394,7 +395,7 @@ func (cluster *Cluster) httpAction(url, method string) (*http.Response, error) { func (cluster *Cluster) HttpDelete(url string) error { _, err := cluster.httpAction(url, "DELETE") if err != nil { - log.Error(err, "failed to do http DELETE operation") + log.Error(err, "Failed to do HTTP DELETE operation") return err } return nil @@ -405,7 +406,7 @@ func (nsxVersion *NsxVersion) Validate() error { result := re.Find([]byte(nsxVersion.NodeVersion)) if len(result) < 1 { err := errors.New("error version format") - log.Error(err, "check version", "version", nsxVersion.NodeVersion) + log.Error(err, "Failed to check NSX version", "version", nsxVersion.NodeVersion) return err } @@ -445,7 +446,7 @@ func (nsxVersion *NsxVersion) featureSupported(feature int) bool { for i, str := range buff { val, err := strconv.ParseInt(str, 10, 64) if err != nil { - log.Error(err, "parse version error") + log.Error(err, "Failed to parse NSX version") return false } sections[i] = val @@ -467,7 +468,7 @@ func (nsxVersion *NsxVersion) featureSupported(feature int) bool { func (cluster *Cluster) FetchLicense() error { resp, err := cluster.httpAction(LicenseAPI, "GET") if err != nil { - log.Error(err, "failed to get nsx license") + log.Error(err, "Failed to get NSX license") return err } nsxLicense := &util.NsxLicense{} diff --git a/pkg/nsx/endpoint.go b/pkg/nsx/endpoint.go index dbbe433fc..1e9427228 100644 --- a/pkg/nsx/endpoint.go +++ b/pkg/nsx/endpoint.go @@ -68,6 +68,7 @@ type address struct { func (addr *address) Scheme() string { return addr.scheme } + func (addr *address) Host() string { return addr.host } @@ -99,7 +100,7 @@ func parseURL(u string) (string, string, error) { } ur, err := url.Parse(u) if err != nil { - log.Error(err, "endpoint url format is invalid", "url", u) + log.Error(err, "Failed to parse invalid endpoint url", "url", u) return "", "", err } return ur.Host, ur.Scheme, nil @@ -114,11 +115,13 @@ func (ep *Endpoint) UpdateCAforEnvoy(req *http.Request) { req.Header.Set("x-vmware-server-tls-cert", ep.caFile) } } + func (ep *Endpoint) SetEnvoyUrl(url string) { ep.Lock() ep.envoyUrl = url ep.Unlock() } + func (ep *Endpoint) keepAlive() error { var req *http.Request var err error @@ -130,22 +133,22 @@ func (ep *Endpoint) keepAlive() error { } else { req, err = http.NewRequest("GET", fmt.Sprintf(healthURL, ep.Scheme(), ep.Host()), nil) } - log.V(1).Info("keep alive request", "url", req.URL.String()) + log.V(1).Info("Keep alive request", "url", req.URL.String()) if err != nil { - log.Error(err, "create keep alive request error") + log.Error(err, "Failed to create keep alive request") return err } err = ep.UpdateHttpRequestAuth(req) if err != nil { - log.Error(err, "keep alive update auth error") + log.Error(err, "Failed to keep alive update auth") ep.setStatus(DOWN) return err } ep.UpdateCAforEnvoy(req) resp, err := ep.noBalancerClient.Do(req) if err != nil { - log.Error(err, "failed to validate API cluster", "endpoint", ep.Host()) + log.Error(err, "Failed to validate API cluster", "endpoint", ep.Host()) return err } var a epHealthy @@ -157,18 +160,18 @@ func (ep *Endpoint) keepAlive() error { log.V(2).Info("keepAlive", "body", body) err = util.InitErrorFromResponse(ep.Host(), resp.StatusCode, body) if util.ShouldRegenerate(err) { - log.Error(err, "failed to validate API cluster due to an exception that calls for regeneration", "endpoint", ep.Host()) + log.Error(err, "Failed to validate API cluster due to an exception that calls for regeneration", "endpoint", ep.Host()) // TODO, should we regenerate the token here ? ep.setXSRFToken("") ep.setStatus(DOWN) return err } else if util.ShouldRetry(err) { - log.Info("error is retriable, endpoint stays up") + log.Info("Error is retriable, endpoint stays up") ep.setStatus(UP) } else { ep.setStatus(DOWN) } - log.Error(err, "failed to validate API cluster", "endpoint", ep.Host()) + log.Error(err, "Failed to validate API cluster", "endpoint", ep.Host()) return err } @@ -190,7 +193,7 @@ func (ep *Endpoint) KeepAlive() { inter := ep.nextInterval() select { case <-ep.stop: - log.Info("keepalive stopped by cluster") + log.Info("KeepAlive stopped by cluster") return case <-time.After(time.Second * time.Duration(inter)): } @@ -198,19 +201,19 @@ func (ep *Endpoint) KeepAlive() { } func (ep *Endpoint) setup() { - log.V(2).Info("begin to setup endpoint") + log.V(2).Info("Begin to setup endpoint") err := ep.keepAlive() if err != nil { - log.Error(err, "setup endpoint failed") + log.Error(err, "Failed to setup endpoint") } else { - log.Info("succeeded to setup endpoint") + log.Info("Succeeded to setup endpoint") } } func (ep *Endpoint) setStatus(s EndpointStatus) { ep.Lock() if ep.status != s { - log.Info("endpoint status is changing", "endpoint", ep.Host(), "oldStatus", ep.status, "newStatus", s) + log.Info("Endpoint status is changing", "endpoint", ep.Host(), "oldStatus", ep.status, "newStatus", s) ep.status = s } ep.Unlock() @@ -272,7 +275,7 @@ func (ep *Endpoint) ConnNumber() int { func (ep *Endpoint) createAuthSession(certProvider auth.ClientCertProvider, tokenProvider auth.TokenProvider, username string, password string, jar *Jar) error { if certProvider != nil { - log.V(2).Info("skipping session creation with client certificate auth") + log.V(2).Info("Skipping session creation with client certificate auth") return nil } if tokenProvider != nil { @@ -296,17 +299,17 @@ func (ep *Endpoint) createAuthSession(certProvider auth.ClientCertProvider, toke } if err != nil { - log.Error(err, "failed to generate request for session creation", "endpoint", ep.Host()) + log.Error(err, "Failed to generate request for session creation", "endpoint", ep.Host()) return err } req.Header.Add("Accept", "application/json") req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - log.V(1).Info("creating auth session", "url", req.URL.String(), "endpoint", ep.Host(), "request header", req.Header) + log.V(1).Info("Creating auth session", "url", req.URL.String(), "endpoint", ep.Host(), "request header", req.Header) ep.UpdateCAforEnvoy(req) resp, err := ep.noBalancerClient.Do(req) if err != nil { - log.Error(err, "session creation failed", "endpoint", u.Host) + log.Error(err, "Failed to create session", "endpoint", u.Host) return err } body, err := io.ReadAll(resp.Body) @@ -315,13 +318,13 @@ func (ep *Endpoint) createAuthSession(certProvider auth.ClientCertProvider, toke err = fmt.Errorf("session creation failed, unexpected status code %d", resp.StatusCode) } if err != nil { - log.Error(err, "session creation failed", "endpoint", u.Host, "statusCode", resp.StatusCode, "headerDate", resp.Header["Date"], "body", string(body)) + log.Error(err, "Failed to create session", "endpoint", u.Host, "statusCode", resp.StatusCode, "headerDate", resp.Header["Date"], "body", string(body)) return err } tokens, ok := resp.Header["X-Xsrf-Token"] if !ok { err = errors.New("no token in response") - log.Error(err, "session creation failed", "endpoint", u.Host, "statusCode", resp.StatusCode, "headerDate", resp.Header["Date"], "body", body) + log.Error(err, "Failed to create session", "endpoint", u.Host, "statusCode", resp.StatusCode, "headerDate", resp.Header["Date"], "body", body) return err } ep.setXSRFToken(tokens[0]) @@ -331,7 +334,7 @@ func (ep *Endpoint) createAuthSession(certProvider auth.ClientCertProvider, toke ep.client.Jar = jar ep.Unlock() ep.setStatus(UP) - log.Info("session creation succeeded", "endpoint", u.Host) + log.Info("Session creation succeeded", "endpoint", u.Host) return nil } @@ -350,7 +353,7 @@ func (ep *Endpoint) UpdateHttpRequestAuth(request *http.Request) error { }), retry.LastErrorOnly(true), retry.Delay(ep.lockWait), retry.MaxDelay(ep.lockWait), ) if err != nil { - log.Error(err, "retrieving JSON Web Token eror") + log.Error(err, "Failed to retrieve JSON Web Token") return err } bearerToken := ep.tokenProvider.HeaderValue(token) @@ -374,7 +377,7 @@ func (ep *Endpoint) UpdateHttpRequestAuth(request *http.Request) error { request.Header.Set("Cookie", cookie.String()) } } else { - log.V(2).Info("update user/password") + log.V(2).Info("Update user/password") request.SetBasicAuth(ep.user, ep.password) } } diff --git a/pkg/nsx/ratelimiter/ratelimiter.go b/pkg/nsx/ratelimiter/ratelimiter.go index 1bc92fe54..ae96a12b1 100644 --- a/pkg/nsx/ratelimiter/ratelimiter.go +++ b/pkg/nsx/ratelimiter/ratelimiter.go @@ -121,7 +121,7 @@ func (limiter *FixRateLimiter) Wait() { defer cancel() err := limiter.l.WaitN(ctx, 1) if err != nil { - log.V(1).Info("wait for token timeout", "error", err.Error()) + log.V(1).Info("Wait for token timeout", "error", err.Error()) return } } @@ -146,7 +146,7 @@ func (limiter *AIMDRateLimter) Wait() { defer cancel() err := limiter.l.WaitN(ctx, 1) if err != nil { - log.V(1).Info("wait for token timeout", "error", err.Error()) + log.V(1).Info("Wait for token timeout", "error", err.Error()) return } } @@ -174,13 +174,13 @@ func (limiter *AIMDRateLimter) AdjustRate(waitTime time.Duration, statusCode int if r < limiter.max { r++ limiter.l.SetLimit(rate.Limit(r)) - log.V(1).Info("increasing API rate limit", "rateLimit", r, "statusCode", statusCode) + log.V(1).Info("Increasing API rate limit", "rateLimit", r, "statusCode", statusCode) } } else if limiter.neg > 0 { if r > 1 { r = r / 2 limiter.l.SetLimit(rate.Limit(r)) - log.V(1).Info("decreasing API rate limit", "rateLimit", r, "statusCode", statusCode) + log.V(1).Info("Decreasing API rate limit", "rateLimit", r, "statusCode", statusCode) } } limiter.lastAdjuctRate = now diff --git a/pkg/nsx/services/common/compare.go b/pkg/nsx/services/common/compare.go index bd743b2b9..e428dd0aa 100644 --- a/pkg/nsx/services/common/compare.go +++ b/pkg/nsx/services/common/compare.go @@ -15,7 +15,7 @@ type Comparable interface { } func CompareResource(existing Comparable, expected Comparable) (isChanged bool) { - var dataValueToJSONEncoder = cleanjson.NewDataValueToJsonEncoder() + dataValueToJSONEncoder := cleanjson.NewDataValueToJsonEncoder() s1, _ := dataValueToJSONEncoder.Encode(existing.Value()) s2, _ := dataValueToJSONEncoder.Encode(expected.Value()) if s1 != s2 { @@ -42,16 +42,16 @@ func CompareResources(existing []Comparable, expected []Comparable) (changed []C if isChanged := CompareResource(existed_item, expected_item); !isChanged { continue } - log.V(1).Info("resource changed", "existing", existed_item, "expected", expected_item) + log.V(1).Info("Resource changed", "existing", existed_item, "expected", expected_item) } changed = append(changed, expected_item) } for key, existed_item := range existingMap { if _, ok := expectedMap[key]; !ok { - log.V(1).Info("resource stale", "existing", existed_item) + log.V(1).Info("Resource stale", "existing", existed_item) stale = append(stale, existed_item) } } - log.V(1).Info("resources differ", "stale", stale, "changed", changed) + log.V(1).Info("Resources differ", "stale", stale, "changed", changed) return changed, stale } diff --git a/pkg/nsx/services/common/limit.go b/pkg/nsx/services/common/limit.go deleted file mode 100644 index 32ecdf195..000000000 --- a/pkg/nsx/services/common/limit.go +++ /dev/null @@ -1,5 +0,0 @@ -package common - -const ( - TagsCountMax = 26 -) diff --git a/pkg/nsx/services/common/store.go b/pkg/nsx/services/common/store.go index 1af2fea83..817c96140 100644 --- a/pkg/nsx/services/common/store.go +++ b/pkg/nsx/services/common/store.go @@ -50,7 +50,7 @@ func (resourceStore *ResourceStore) TransResourceToStore(entity *data.StructValu } objAddr := nsxutil.CasttoPointer(obj) if objAddr == nil { - return fmt.Errorf("failed to cast to pointer") + return fmt.Errorf("Failed to cast to pointer") } err2 := resourceStore.Add(objAddr) if err2 != nil { @@ -80,7 +80,7 @@ func (resourceStore *ResourceStore) ListIndexFuncValues(key string) sets.Set[str func (resourceStore *ResourceStore) GetByKey(key string) interface{} { res, exists, err := resourceStore.Indexer.GetByKey(key) if err != nil { - log.Error(err, "failed to get obj by key", "key", key) + log.Error(err, "Failed to get obj by key", "key", key) } else if exists { return res } @@ -92,7 +92,7 @@ func (resourceStore *ResourceStore) GetByKey(key string) interface{} { func (resourceStore *ResourceStore) GetByIndex(index string, value string) []interface{} { indexResults, err := resourceStore.Indexer.ByIndex(index, value) if err != nil { - log.Error(err, "failed to get obj by index", "index", value) + log.Error(err, "Failed to get obj by index", "index", value) } return indexResults } @@ -104,7 +104,7 @@ func (resourceStore *ResourceStore) IsPolicyAPI() bool { func TransError(err error) error { apierror, errortype := nsxutil.DumpAPIError(err) if apierror != nil { - log.Info("translate error", "apierror", apierror, "error type", errortype) + log.Info("Translate error", "apierror", apierror, "error type", errortype) if *errortype == apierrors.ErrorType_SERVICE_UNAVAILABLE && *apierror.ErrorCode == int64(60576) || *errortype == apierrors.ErrorType_INVALID_REQUEST && *apierror.ErrorCode == int64(255) { return nsxutil.PageMaxError{Desc: "page max overflow"} @@ -184,7 +184,7 @@ func (service *Service) PopulateResourcetoStore(wg *sync.WaitGroup, fatalErrors if err != nil { fatalErrors <- err } - log.Info("initialized store", "resourceType", resourceTypeValue, "count", count) + log.Info("Initialized store", "resourceType", resourceTypeValue, "count", count) } // InitializeCommonStore is the common method used by InitializeResourceStore and InitializeVPCResourceStore diff --git a/pkg/nsx/services/common/types.go b/pkg/nsx/services/common/types.go index bcf57aa8a..09b2f76e3 100644 --- a/pkg/nsx/services/common/types.go +++ b/pkg/nsx/services/common/types.go @@ -16,6 +16,7 @@ import ( const ( HashLength int = 8 + MaxTagsCount int = 26 MaxTagScopeLength int = 128 MaxTagValueLength int = 256 MaxIdLength int = 255 diff --git a/pkg/nsx/services/securitypolicy/builder.go b/pkg/nsx/services/securitypolicy/builder.go index 8af220dcb..754294994 100644 --- a/pkg/nsx/services/securitypolicy/builder.go +++ b/pkg/nsx/services/securitypolicy/builder.go @@ -77,7 +77,7 @@ func (service *SecurityPolicyService) buildSecurityPolicy(obj *v1alpha1.Security policyGroup, policyGroupPath, err := service.buildPolicyGroup(obj, createdFor) if err != nil { - log.Error(err, "failed to build policy group", "policy", *obj) + log.Error(err, "Failed to build policy group", "policy", *obj) return nil, nil, nil, err } @@ -91,7 +91,7 @@ func (service *SecurityPolicyService) buildSecurityPolicy(obj *v1alpha1.Security // A rule containing named port may be expanded to multiple rules if the named ports map to multiple port numbers. expandRules, buildGroups, buildGroupShares, err := service.buildRuleAndGroups(obj, &rule, ruleIdx, createdFor) if err != nil { - log.Error(err, "failed to build rule and groups", "rule", rule, "ruleIndex", ruleIdx) + log.Error(err, "Failed to build rule and groups", "rule", rule, "ruleIndex", ruleIdx) return nil, nil, nil, err } @@ -901,7 +901,7 @@ func (service *SecurityPolicyService) buildRulePeerGroup(obj *v1alpha1.SecurityP // Build a NSX share resource in infra level nsxInfraShare, err := service.buildGroupShare(obj, &rulePeerGroup, []string{rulePeerGroupPath}, *sharedWith, vpcInfo, true, false, createdFor) if err != nil { - log.Error(err, "failed to build NSX infra share", "ruleGroupName", rulePeerGroupName) + log.Error(err, "Failed to build NSX infra share", "ruleGroupName", rulePeerGroupName) return nil, "", nil, err } infraGroupShare.share = nsxInfraShare @@ -913,7 +913,7 @@ func (service *SecurityPolicyService) buildRulePeerGroup(obj *v1alpha1.SecurityP // Build a NSX share resource in project level nsxProjectShare, err := service.buildGroupShare(obj, &rulePeerGroup, []string{rulePeerGroupPath}, *sharedWith, vpcInfo, false, true, createdFor) if err != nil { - log.Error(err, "failed to build NSX project share", "ruleGroupName", rulePeerGroupName) + log.Error(err, "Failed to build NSX project share", "ruleGroupName", rulePeerGroupName) return nil, "", nil, err } projectGroupShare.share = nsxProjectShare @@ -941,7 +941,7 @@ func (service *SecurityPolicyService) buildRuleBasicInfo(obj *v1alpha1.SecurityP } displayName, err := service.buildRuleDisplayName(rule, createdFor, namedPortInfo) if err != nil { - log.Error(err, "failed to build rule's display name", "securityPolicyUID", obj.UID, "rule", rule, "createdFor", createdFor) + log.Error(err, "Failed to build rule's display name", "securityPolicyUID", obj.UID, "rule", rule, "createdFor", createdFor) } nsxRule := model.Rule{ @@ -1842,7 +1842,7 @@ func (service *SecurityPolicyService) getNamespaceUID(ns string) (nsUid types.UI Name: ns, } if err := service.Client.Get(context.Background(), namespacedName, namespace); err != nil { - log.Error(err, "failed to get namespace UID", "namespace", ns) + log.Error(err, "Failed to get namespace UID", "namespace", ns) return "" } namespace_uid := namespace.UID diff --git a/pkg/nsx/services/securitypolicy/firewall.go b/pkg/nsx/services/securitypolicy/firewall.go index bb425954c..4e3e868ad 100644 --- a/pkg/nsx/services/securitypolicy/firewall.go +++ b/pkg/nsx/services/securitypolicy/firewall.go @@ -68,7 +68,7 @@ func GetSecurityService(service common.Service, vpcService common.VPCServiceProv if securityService == nil { var err error if securityService, err = InitializeSecurityPolicy(service, vpcService); err != nil { - log.Error(err, "failed to initialize subnet commonService") + log.Error(err, "Failed to initialize SecurityPolicy service") os.Exit(1) } } @@ -456,7 +456,7 @@ func (service *SecurityPolicyService) getFinalSecurityPolicyResource(obj *v1alph nsxSecurityPolicy, nsxGroups, nsxGroupShares, err := service.buildSecurityPolicy(obj, createdFor) if err != nil { - log.Error(err, "failed to build SecurityPolicy from CR", "securityPolicyUID", obj.UID) + log.Error(err, "Failed to build SecurityPolicy from CR", "securityPolicyUID", obj.UID) return nil, nil, nil, nil, false, err } @@ -498,7 +498,7 @@ func (service *SecurityPolicyService) getFinalSecurityPolicyResource(obj *v1alph func (service *SecurityPolicyService) createOrUpdateSecurityPolicy(obj *v1alpha1.SecurityPolicy, createdFor string) error { finalSecurityPolicy, finalGroups, _, _, isChanged, err := service.getFinalSecurityPolicyResource(obj, createdFor, false) if err != nil { - log.Error(err, "failed to get SecurityPolicy resources from CR", "securityPolicyUID", obj.UID) + log.Error(err, "Failed to get SecurityPolicy resources from CR", "securityPolicyUID", obj.UID) return err } @@ -513,20 +513,20 @@ func (service *SecurityPolicyService) createOrUpdateSecurityPolicy(obj *v1alpha1 infraSecurityPolicy, err := service.WrapHierarchySecurityPolicy(finalSecurityPolicy, finalGroups) if err != nil { - log.Error(err, "failed to wrap SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) + log.Error(err, "Failed to wrap SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) return err } err = service.NSXClient.InfraClient.Patch(*infraSecurityPolicy, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to create or update SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) + log.Error(err, "Failed to create or update SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) return err } // Get SecurityPolicy from NSX after HAPI call as NSX renders several fields like `path`/`parent_path`. finalGetNSXSecurityPolicy, err := service.NSXClient.SecurityClient.Get(getDomain(service), *finalSecurityPolicy.Id) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to get SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) + log.Error(err, "Failed to get SecurityPolicy", "nsxSecurityPolicyId", finalSecurityPolicy.Id) return err } @@ -536,18 +536,18 @@ func (service *SecurityPolicyService) createOrUpdateSecurityPolicy(obj *v1alpha1 if isChanged { err = securityPolicyStore.Apply(&finalGetNSXSecurityPolicy) if err != nil { - log.Error(err, "failed to apply store", "securityPolicy", finalGetNSXSecurityPolicy) + log.Error(err, "Failed to apply store", "securityPolicy", finalGetNSXSecurityPolicy) return err } } err = ruleStore.Apply(&finalRules) if err != nil { - log.Error(err, "failed to apply store", "nsxRules", finalRules) + log.Error(err, "Failed to apply store", "nsxRules", finalRules) return err } err = groupStore.Apply(&finalGroups) if err != nil { - log.Error(err, "failed to apply store", "nsxGroups", finalGroups) + log.Error(err, "Failed to apply store", "nsxGroups", finalGroups) return err } log.Info("Successfully created or updated NSX SecurityPolicy", "nsxSecurityPolicy", finalGetNSXSecurityPolicy) @@ -568,7 +568,7 @@ func (service *SecurityPolicyService) createOrUpdateVPCSecurityPolicy(obj *v1alp finalSecurityPolicy, finalGroups, finalShares, finalShareGroups, isChanged, err := service.getFinalSecurityPolicyResource(obj, createdFor, isDefaultProject) if err != nil { - log.Error(err, "failed to get SecurityPolicy resources from CR", "securityPolicyUID", obj.UID) + log.Error(err, "Failed to get SecurityPolicy resources from CR", "securityPolicyUID", obj.UID) return err } @@ -646,7 +646,7 @@ func (service *SecurityPolicyService) deleteSecurityPolicy(sp types.UID) error { nsxSecurityPolicy = existingSecurityPolices[0] if nsxSecurityPolicy.Path == nil { err = errors.New("nsxSecurityPolicy path is empty") - log.Error(err, "failed to delete SecurityPolicy", "nsxSecurityPolicyUID", sp) + log.Error(err, "Failed to delete SecurityPolicy", "nsxSecurityPolicyUID", sp) return err } @@ -667,29 +667,29 @@ func (service *SecurityPolicyService) deleteSecurityPolicy(sp types.UID) error { infraSecurityPolicy, err := service.WrapHierarchySecurityPolicy(nsxSecurityPolicy, *nsxGroups) if err != nil { - log.Error(err, "failed to wrap SecurityPolicy", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap SecurityPolicy", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return err } err = service.NSXClient.InfraClient.Patch(*infraSecurityPolicy, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to delete SecurityPolicy", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to delete SecurityPolicy", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return err } err = securityPolicyStore.Apply(&finalSecurityPolicyCopy) if err != nil { - log.Error(err, "failed to apply store", "securityPolicy", finalSecurityPolicyCopy) + log.Error(err, "Failed to apply store", "securityPolicy", finalSecurityPolicyCopy) return err } err = ruleStore.Apply(&finalSecurityPolicyCopy.Rules) if err != nil { - log.Error(err, "failed to apply store", "nsxRules", finalSecurityPolicyCopy.Rules) + log.Error(err, "Failed to apply store", "nsxRules", finalSecurityPolicyCopy.Rules) return err } err = groupStore.Apply(nsxGroups) if err != nil { - log.Error(err, "failed to apply store", "nsxGroups", nsxGroups) + log.Error(err, "Failed to apply store", "nsxGroups", nsxGroups) return err } @@ -741,7 +741,7 @@ func (service *SecurityPolicyService) deleteVPCSecurityPolicy(sp types.UID, isGC // Get orgID, projectID, vpcID from security policy path "/orgs//projects//vpcs//security-policies/" if nsxSecurityPolicy.Path == nil { err = errors.New("nsxSecurityPolicy path is empty") - log.Error(err, "failed to delete SecurityPolicy in VPC", "nsxSecurityPolicyUID", sp) + log.Error(err, "Failed to delete SecurityPolicy in VPC", "nsxSecurityPolicyUID", sp) return err } vpcInfo, _ := common.ParseVPCResourcePath(*(nsxSecurityPolicy.Path)) @@ -920,7 +920,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicy(nsxSecurityPolicy // Wrap project groups and shares into project child infra. projectInfraResource, err = service.wrapHierarchyProjectResources(nsxShares, nsxShareGroups) if err != nil { - log.Error(err, "failed to wrap NSX project groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap NSX project groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } } @@ -928,7 +928,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicy(nsxSecurityPolicy // Wrap SecurityPolicy, groups, rules under VPC level together with project groups and shares into one hierarchy resource tree. orgRoot, err := service.wrapHierarchyVpcSecurityPolicy(nsxSecurityPolicy, nsxGroups, projectInfraResource, vpcInfo) if err != nil { - log.Error(err, "failed to wrap SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } @@ -936,7 +936,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicy(nsxSecurityPolicy err = service.NSXClient.OrgRootClient.Patch(*orgRoot, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to create/update or delete SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to create/update or delete SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } @@ -945,7 +945,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicy(nsxSecurityPolicy nsxGetSecurityPolicy, err = service.NSXClient.VPCSecurityClient.Get(vpcInfo.OrgID, vpcInfo.ProjectID, vpcInfo.VPCID, *nsxSecurityPolicy.Id) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to get SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to get SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } } @@ -988,14 +988,14 @@ func (service *SecurityPolicyService) manipulateSecurityPolicyForDefaultProject( // Wrap infra groups and shares into infra child infra. infraResource, err = service.wrapHierarchyInfraResources(finalChangedShares, finalChangedShareGroups) if err != nil { - log.Error(err, "failed to wrap NSX infra changed groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap NSX infra changed groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } err = service.NSXClient.InfraClient.Patch(*infraResource, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to create or update NSX infra Resource", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to create or update NSX infra Resource", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } @@ -1004,7 +1004,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicyForDefaultProject( // Wrap SecurityPolicy, groups, rules under VPC level into one hierarchy resource tree. orgRoot, err := service.wrapHierarchyVpcSecurityPolicy(nsxSecurityPolicy, nsxGroups, projectInfraResource, vpcInfo) if err != nil { - log.Error(err, "failed to wrap SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } @@ -1012,7 +1012,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicyForDefaultProject( err = service.NSXClient.OrgRootClient.Patch(*orgRoot, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to create/update or delete SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to create/update or delete SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } @@ -1022,13 +1022,13 @@ func (service *SecurityPolicyService) manipulateSecurityPolicyForDefaultProject( // Wrap infra groups and shares into infra child infra. infraResource, err = service.wrapHierarchyInfraResources(finalStaleShares, finalStaleShareGroups) if err != nil { - log.Error(err, "failed to wrap NSX infra stale groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to wrap NSX infra stale groups and shares", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } err = service.NSXClient.InfraClient.Patch(*infraResource, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to delete NSX infra Resource", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to delete NSX infra Resource", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } } @@ -1038,7 +1038,7 @@ func (service *SecurityPolicyService) manipulateSecurityPolicyForDefaultProject( nsxGetSecurityPolicy, err = service.NSXClient.VPCSecurityClient.Get(vpcInfo.OrgID, vpcInfo.ProjectID, vpcInfo.VPCID, *nsxSecurityPolicy.Id) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to get SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) + log.Error(err, "Failed to get SecurityPolicy in VPC", "nsxSecurityPolicyId", nsxSecurityPolicy.Id) return nsxGetSecurityPolicy, err } } @@ -1052,19 +1052,19 @@ func (service *SecurityPolicyService) applySecurityPolicyStore(nsxSecurityPolicy if isChanged { err = securityPolicyStore.Apply(&nsxSecurityPolicy) if err != nil { - log.Error(err, "failed to apply store", "securityPolicy", nsxSecurityPolicy) + log.Error(err, "Failed to apply store", "securityPolicy", nsxSecurityPolicy) return err } } err = ruleStore.Apply(&nsxRules) if err != nil { - log.Error(err, "failed to apply store", "nsxRules", nsxRules) + log.Error(err, "Failed to apply store", "nsxRules", nsxRules) return err } err = groupStore.Apply(&nsxGroups) if err != nil { - log.Error(err, "failed to apply store", "nsxGroups", nsxGroups) + log.Error(err, "Failed to apply store", "nsxGroups", nsxGroups) return err } return nil @@ -1076,23 +1076,23 @@ func (service *SecurityPolicyService) applyVPCShareResourceStore(nsxShares []mod if isDefaultProject { err = infraGroupStore.Apply(&nsxShareGroups) if err != nil { - log.Error(err, "failed to apply store", "nsxInfraGroups", nsxShareGroups) + log.Error(err, "Failed to apply store", "nsxInfraGroups", nsxShareGroups) return err } err = infraShareStore.Apply(&nsxShares) if err != nil { - log.Error(err, "failed to apply store", "nsxInfraShares", nsxShares) + log.Error(err, "Failed to apply store", "nsxInfraShares", nsxShares) return err } } else { err = projectGroupStore.Apply(&nsxShareGroups) if err != nil { - log.Error(err, "failed to apply store", "nsxProjectGroups", nsxShareGroups) + log.Error(err, "Failed to apply store", "nsxProjectGroups", nsxShareGroups) return err } err = projectShareStore.Apply(&nsxShares) if err != nil { - log.Error(err, "failed to apply store", "nsxProjectShares", nsxShares) + log.Error(err, "Failed to apply store", "nsxProjectShares", nsxShares) return err } } @@ -1185,13 +1185,13 @@ func (service *SecurityPolicyService) gcInfraSharesGroups(sp types.UID, indexSco infraResource, err = service.wrapHierarchyInfraResources(*nsxShares, *nsxShareGroups) if err != nil { - log.Error(err, "failed to wrap NSX infra groups and shares", "securityPolicyUID", sp) + log.Error(err, "Failed to wrap NSX infra groups and shares", "securityPolicyUID", sp) return err } err = service.NSXClient.InfraClient.Patch(*infraResource, &EnforceRevisionCheckParam) err = nsxutil.TransNSXApiError(err) if err != nil { - log.Error(err, "failed to delete NSX infra Resource in GC", "securityPolicyUID", sp) + log.Error(err, "Failed to delete NSX infra Resource in GC", "securityPolicyUID", sp) return err } return nil diff --git a/pkg/nsx/services/subnet/builder.go b/pkg/nsx/services/subnet/builder.go index 8fe2eb806..092d829de 100644 --- a/pkg/nsx/services/subnet/builder.go +++ b/pkg/nsx/services/subnet/builder.go @@ -86,7 +86,7 @@ func (service *SubnetService) buildSubnet(obj client.Object, tags []model.Tag) ( return nil, SubnetTypeError } // tags cannot exceed maximum size 26 - if len(tags) > common.TagsCountMax { + if len(tags) > common.MaxTagsCount { errorMsg := fmt.Sprintf("tags cannot exceed maximum size 26, tags length: %d", len(tags)) return nil, util2.ExceedTagsError{Desc: errorMsg} } diff --git a/pkg/nsx/transport.go b/pkg/nsx/transport.go index 1d33cdedc..0935c9a37 100644 --- a/pkg/nsx/transport.go +++ b/pkg/nsx/transport.go @@ -86,7 +86,7 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { } else if util.ShouldRetry(err) { return true } else { - log.V(1).Info("error is configurated as not retriable", "error", err.Error()) + log.V(1).Info("Error is configured as not retriable", "error", err.Error()) return false } }), retry.LastErrorOnly(true), @@ -96,7 +96,7 @@ func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) { } func handleRoundTripError(err error, ep *Endpoint) error { - log.Error(err, "request failed") + log.Error(err, "Failed to request") errString := err.Error() if strings.HasSuffix(errString, "connection refused") { ep.setStatus(DOWN) diff --git a/pkg/nsx/util/license.go b/pkg/nsx/util/license.go index 45348480f..018861026 100644 --- a/pkg/nsx/util/license.go +++ b/pkg/nsx/util/license.go @@ -16,9 +16,13 @@ var ( licenseMutex sync.Mutex licenseMap = map[string]bool{} Features_to_check = []string{} - Feature_license_map = map[string][]string{FeatureContainer: {LicenseContainerNetwork, - LicenseContainer}, - FeatureDFW: {LicenseDFW}} + Feature_license_map = map[string][]string{ + FeatureContainer: { + LicenseContainerNetwork, + LicenseContainer, + }, + FeatureDFW: {LicenseDFW}, + } ) func init() { @@ -65,6 +69,6 @@ func UpdateFeatureLicense(licenses *NsxLicense) { licenseNames := Feature_license_map[feature] license := searchLicense(licenses, licenseNames) UpdateLicense(feature, license) - log.V(1).Info("update license", "feature", feature, "license", license) + log.V(1).Info("Update license", "feature", feature, "license", license) } } diff --git a/pkg/nsx/util/utils.go b/pkg/nsx/util/utils.go index 2d8fecb02..7485e1592 100644 --- a/pkg/nsx/util/utils.go +++ b/pkg/nsx/util/utils.go @@ -34,9 +34,11 @@ import ( var log = &logger.Log -var HttpCommonError = errors.New("received HTTP Error") -var HttpNotFoundError = errors.New("received HTTP Not Found Error") -var HttpBadRequest = errors.New("received HTTP Bad Request Error") +var ( + HttpCommonError = errors.New("received HTTP Error") + HttpNotFoundError = errors.New("received HTTP Not Found Error") + HttpBadRequest = errors.New("received HTTP Bad Request Error") +) // ErrorDetail is error detail which info extracted from http.Response.Body. type ErrorDetail struct { @@ -139,7 +141,7 @@ func InitErrorFromResponse(host string, statusCode int, body []byte) NsxError { } func extractHTTPDetailFromBody(host string, statusCode int, body []byte) (ErrorDetail, error) { - log.V(2).Info("http response", "status code", statusCode, "body", string(body)) + log.V(2).Info("HTTP response", "status code", statusCode, "body", string(body)) ec := ErrorDetail{StatusCode: statusCode} if len(body) == 0 { log.V(1).Info("body length is 0") @@ -147,7 +149,7 @@ func extractHTTPDetailFromBody(host string, statusCode int, body []byte) (ErrorD } var res responseBody if err := json.Unmarshal(body, &res); err != nil { - log.Error(err, "failed to decode response body for extracting HTTP detail") + log.Error(err, "Failed to decode response body for extracting HTTP detail") return ec, CreateGeneralManagerError(host, "decode body", err.Error()) } @@ -258,7 +260,7 @@ func HandleHTTPResponse(response *http.Response, result interface{}, debug bool) if response.StatusCode == http.StatusBadRequest { err = HttpBadRequest } - log.Error(err, "handle http response", "status", response.StatusCode, "request URL", response.Request.URL, "response body", string(body)) + log.Error(err, "Handle HTTP response", "status", response.StatusCode, "request URL", response.Request.URL, "response body", string(body)) return err, nil } if err != nil || body == nil { @@ -269,10 +271,10 @@ func HandleHTTPResponse(response *http.Response, result interface{}, debug bool) } if debug { - log.V(2).Info("received HTTP response", "response", string(body)) + log.V(2).Info("Received HTTP response", "response", string(body)) } if err := json.Unmarshal(body, result); err != nil { - log.Error(err, "error converting HTTP response to result", "result type", result) + log.Error(err, "Failed to convert HTTP response to result", "result type", result) return err, body } return nil, body @@ -305,6 +307,7 @@ func ParseVPCPath(nsxResourcePath string) (orgID string, projectID string, vpcID resourceID = paras[8] return } + func DumpHttpRequest(request *http.Request) { var body []byte var err error @@ -319,7 +322,7 @@ func DumpHttpRequest(request *http.Request) { } request.Body.Close() request.Body = io.NopCloser(bytes.NewReader(body)) - log.V(2).Info("http request", "url", request.URL, "body", string(body), "head", request.Header) + log.V(2).Info("HTTP request", "url", request.URL, "body", string(body), "head", request.Header) } type NSXApiError struct { @@ -331,6 +334,7 @@ func NewNSXApiError(apiError *model.ApiError) *NSXApiError { ApiError: apiError, } } + func (e *NSXApiError) Error() string { if e.ApiError != nil { apierror := e.ApiError @@ -452,18 +456,18 @@ func DumpAPIError(err error) (*model.ApiError, *apierrors.ErrorTypeEnum) { case apierrors.UnverifiedPeer: return castApiError(i.Data), i.ErrorType default: - log.Info("dump api error", "error not supported", err) + log.Info("Dump api error", "error not supported", err) return nil, nil } } func castApiError(apiErrorDataValue *data.StructValue) *model.ApiError { - info := "dump api error" + info := "Dump api error" if apiErrorDataValue == nil { log.Info(info, "no extra error info", apiErrorDataValue) return nil } - var typeConverter = bindings.NewTypeConverter() + typeConverter := bindings.NewTypeConverter() data, err := typeConverter.ConvertToGolang(apiErrorDataValue, model.ApiErrorBindingType()) if err != nil && isEmptyAPIError(data.(model.ApiError)) { log.Error(err[0], info) @@ -494,7 +498,7 @@ func VerifyNsxCertWithThumbprint(der []byte, thumbprint string) error { tbFromCert = hex.EncodeToString(digest[:]) } else { err := errors.New("invalid thumbprint format") - log.Error(err, "unknown thumbprint length", "thumbprint", tbRaw) + log.Error(err, "Unknown thumbprint length", "thumbprint", tbRaw) return err } @@ -503,7 +507,7 @@ func VerifyNsxCertWithThumbprint(der []byte, thumbprint string) error { } err := errors.New("server certificate didn't match trusted fingerprint") - log.Error(err, "verify thumbprint", "server", tbFromCert, "local", tbRaw) + log.Error(err, "Verify thumbprint", "server", tbFromCert, "local", tbRaw) return err } @@ -515,24 +519,24 @@ func GetTLSConfigForCert(pemCerts []byte) (*tls.Config, error) { block, _ := pem.Decode(pemCerts) if block == nil { err := errors.New("decode ca file fail") - log.Error(err, "failed to decode cert", "pem", pemCerts) + log.Error(err, "Failed to decode cert", "pem", pemCerts) return nil, err } if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { err := errors.New("pem not certificate or header not found") - log.Error(err, "failed to decode cert", "pem", pemCerts) + log.Error(err, "Failed to decode cert", "pem", pemCerts) return nil, err } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { - log.Error(err, "failed to decode cert", "pem", pemCerts) + log.Error(err, "Failed to decode cert", "pem", pemCerts) return nil, err } // Native cert verification in case of CA cert if cert.IsCA { - log.Info("configured CA cert", "subject", cert.Subject) + log.Info("Configured CA cert", "subject", cert.Subject) certPool := x509.NewCertPool() certPool.AddCert(cert) // #nosec G402: ignore insecure options @@ -549,18 +553,18 @@ func GetTLSConfigForCert(pemCerts []byte) (*tls.Config, error) { VerifyConnection: func(cs tls.ConnectionState) error { if cs.PeerCertificates == nil || cs.PeerCertificates[0] == nil { err := errors.New("server didn't present cert") - log.Error(err, "verify cert") + log.Error(err, "Verify cert") return err } if !bytes.Equal(cs.PeerCertificates[0].Raw, cert.Raw) { err := errors.New("server certificate didn't match pinned leaf cert") - log.Error(err, "verify cert") + log.Error(err, "Verify cert") return err } return nil }, } - log.Info("configured cert pining", "subject", cert.Subject) + log.Info("Configured cert pining", "subject", cert.Subject) return config, nil } @@ -623,7 +627,7 @@ func CertPemBytesToHeader(caFile string) string { if certIdx > 0 { cert = cert[:certIdx] } else { - log.Info("not found pem footer", "cert", cert) + log.Info("Not found pem footer", "cert", cert) return "" } cert = strings.ReplaceAll(cert, X509_PEM_HEADER, "") diff --git a/pkg/util/crypto.go b/pkg/util/crypto.go index 1cf19bfc8..a7d3d1358 100644 --- a/pkg/util/crypto.go +++ b/pkg/util/crypto.go @@ -23,16 +23,14 @@ const ( DefaultSerialNumberLength = 160 ) -var ( - DefaultSubject = pkix.Name{ - Country: []string{"US"}, - Organization: []string{"VMware"}, - OrganizationalUnit: []string{"Antrea Cluster"}, - Locality: []string{"Palo Alto"}, - Province: []string{"CA"}, - CommonName: "dummy", - } -) +var DefaultSubject = pkix.Name{ + Country: []string{"US"}, + Organization: []string{"VMware"}, + OrganizationalUnit: []string{"Antrea Cluster"}, + Locality: []string{"Palo Alto"}, + Province: []string{"CA"}, + CommonName: "dummy", +} // GenerateCertificate returns generated certificate and private key in PEM format func GenerateCertificate(subject *pkix.Name, validDays int) (string, string, error) { @@ -46,13 +44,13 @@ func GenerateCertificate(subject *pkix.Name, validDays int) (string, string, err priv, err := rsa.GenerateKey(rand.Reader, DefaultRSABits) if err != nil { - log.Error(err, "failed to generate RSA key") + log.Error(err, "Failed to generate RSA key") return "", "", err } serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), DefaultSerialNumberLength)) if err != nil { - log.Error(err, "failed to generate serial number") + log.Error(err, "Failed to generate serial number") return "", "", err } notBefore := time.Now() @@ -66,7 +64,7 @@ func GenerateCertificate(subject *pkix.Name, validDays int) (string, string, err derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) if err != nil { - log.Error(err, "failed to create certificate") + log.Error(err, "Failed to create certificate") return "", "", err } diff --git a/pkg/util/utils.go b/pkg/util/utils.go index 199db4c69..39f6ae819 100644 --- a/pkg/util/utils.go +++ b/pkg/util/utils.go @@ -440,7 +440,7 @@ func BuildBasicTags(cluster string, obj interface{}, namespaceID types.UID) []mo tags = append(tags, model.Tag{Scope: String(common.TagScopeIPAddressAllocationCRName), Tag: String(i.ObjectMeta.Name)}) tags = append(tags, model.Tag{Scope: String(common.TagScopeIPAddressAllocationCRUID), Tag: String(string(i.UID))}) default: - log.Info("unknown obj type", "obj", obj) + log.Info("Unknown obj type", "obj", obj) } if len(namespaceID) > 0 {