From c7d9f1e47a485763aad443500ca62769d9a4d73f Mon Sep 17 00:00:00 2001 From: vie-serendipity <2733147505@qq.com> Date: Thu, 7 Nov 2024 15:35:39 +0800 Subject: [PATCH] fix: golang lint feat: update klog related code feat: add logconstructor for controller --- cmd/yurt-iot-dock/app/core.go | 14 ++++++++++---- cmd/yurt-manager/app/client/token.go | 4 ++-- cmd/yurt-manager/app/manager.go | 11 +++++++++-- go.mod | 1 + pkg/apis/apps/v1alpha1/default.go | 6 +++--- pkg/util/iptables/testing/parse_test.go | 8 ++++---- .../filter/forwardkubesvctraffic/filter_test.go | 4 ++-- pkg/yurthub/healthchecker/node_lease.go | 6 +++--- pkg/yurthub/proxy/autonomy/autonomy.go | 4 ++-- pkg/yurthub/proxy/pool/pool.go | 2 +- pkg/yurthub/server/nonresource.go | 4 ++-- pkg/yurthub/yurtcoordinator/coordinator_test.go | 6 +++--- pkg/yurthub/yurtcoordinator/informer_lease.go | 6 +++--- .../clients/edgex-foundry/v3/device_client.go | 2 +- .../internal/controller/controller.go | 12 ++---------- .../nodelifecycle/node_life_cycle_controller.go | 1 - .../node_life_cycle_controller_test.go | 4 ++-- .../nodelifecycle/scheduler/timed_workers.go | 2 +- .../controller/platformadmin/iotdock.go | 8 ++++---- .../platformadmin/platform_admin_controller.go | 6 +++--- .../raven/dns/gateway_dns_controller.go | 2 +- pkg/yurtmanager/controller/util/tools.go | 17 +++++++++++++++++ .../controller/yurtappset/revision.go | 8 ++++---- .../yurtappset/yurt_app_set_controller.go | 2 +- .../upgradeinfo/upgrade_info_test.go | 8 ++++---- .../v1alpha1/yurtappdaemon_default.go | 2 +- .../yurtappset/v1beta1/yurtappset_default.go | 6 +++--- .../v1beta1/yurtappset_default_test.go | 8 ++++---- test/e2e/cmd/init/kindoperator.go | 2 +- test/e2e/yurt/yurtappset.go | 2 +- 30 files changed, 95 insertions(+), 73 deletions(-) diff --git a/cmd/yurt-iot-dock/app/core.go b/cmd/yurt-iot-dock/app/core.go index 47ffc6f5727..4c78e7850e7 100644 --- a/cmd/yurt-iot-dock/app/core.go +++ b/cmd/yurt-iot-dock/app/core.go @@ -18,6 +18,7 @@ package app import ( "context" + "flag" "fmt" "net/http" "os" @@ -31,10 +32,10 @@ import ( "k8s.io/client-go/kubernetes" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/klog/v2" - "k8s.io/klog/v2/klogr" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "github.com/openyurtio/openyurt/cmd/yurt-iot-dock/app/options" @@ -65,8 +66,8 @@ func NewCmdYurtIoTDock(stopCh <-chan struct{}) *cobra.Command { Short: "Launch yurt-iot-dock", Long: "Launch yurt-iot-dock", Run: func(cmd *cobra.Command, args []string) { - cmd.Flags().VisitAll(func(flag *pflag.Flag) { - klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value) + cmd.Flags().VisitAll(func(f *pflag.Flag) { + klog.V(1).Infof("FLAG: --%s=%q", f.Name, f.Value) }) if err := options.ValidateOptions(yurtIoTDockOptions); err != nil { klog.Fatalf("validate options: %v", err) @@ -75,12 +76,17 @@ func NewCmdYurtIoTDock(stopCh <-chan struct{}) *cobra.Command { }, } + opts := zap.Options{ + Development: true, + } + opts.BindFlags(flag.CommandLine) + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + yurtIoTDockOptions.AddFlags(cmd.Flags()) return cmd } func Run(opts *options.YurtIoTDockOptions, stopCh <-chan struct{}) { - ctrl.SetLogger(klogr.New()) cfg := ctrl.GetConfigOrDie() metricsServerOpts := metricsserver.Options{ diff --git a/cmd/yurt-manager/app/client/token.go b/cmd/yurt-manager/app/client/token.go index 9e4694831c2..377857bd589 100644 --- a/cmd/yurt-manager/app/client/token.go +++ b/cmd/yurt-manager/app/client/token.go @@ -29,7 +29,7 @@ import ( "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" - utilpointer "k8s.io/utils/pointer" + utilpointer "k8s.io/utils/ptr" ) var ( @@ -68,7 +68,7 @@ func (ts *tokenSourceImpl) Token() (*oauth2.Token, error) { tr, inErr := ts.cli.CoreV1().ServiceAccounts(ts.namespace).CreateToken(context.TODO(), ts.serviceAccountName, &v1authenticationapi.TokenRequest{ Spec: v1authenticationapi.TokenRequestSpec{ - ExpirationSeconds: utilpointer.Int64(ts.expirationSeconds), + ExpirationSeconds: utilpointer.To(ts.expirationSeconds), }, }, metav1.CreateOptions{}) if inErr != nil { diff --git a/cmd/yurt-manager/app/manager.go b/cmd/yurt-manager/app/manager.go index 4c87fb73762..be8e0e2cd44 100644 --- a/cmd/yurt-manager/app/manager.go +++ b/cmd/yurt-manager/app/manager.go @@ -17,6 +17,7 @@ limitations under the License. package app import ( + "flag" "fmt" "net/http" "os" @@ -33,10 +34,10 @@ import ( "k8s.io/component-base/cli/globalflag" "k8s.io/component-base/term" "k8s.io/klog/v2" - "k8s.io/klog/v2/klogr" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" runtimewebhook "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -124,6 +125,13 @@ current state towards the desired state.`, } fs := cmd.Flags() + + opts := zap.Options{ + Development: true, + } + opts.BindFlags(flag.CommandLine) + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + namedFlagSets := s.Flags(controller.KnownControllers(), controller.ControllersDisabledByDefault.List()) // verflag.AddFlags(namedFlagSets.FlagSet("global")) globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name()) @@ -156,7 +164,6 @@ func PrintFlags(flags *pflag.FlagSet) { // Run runs the KubeControllerManagerOptions. This should never exit. func Run(c *config.CompletedConfig, stopCh <-chan struct{}) error { - ctrl.SetLogger(klogr.New()) ctx := ctrl.SetupSignalHandler() cfg := ctrl.GetConfigOrDie() if len(c.ComponentConfig.Generic.Kubeconfig) != 0 { diff --git a/go.mod b/go.mod index 4405d2a4d20..687cc443a7c 100644 --- a/go.mod +++ b/go.mod @@ -85,6 +85,7 @@ require ( github.com/fxamacker/cbor/v2 v2.6.0 // indirect github.com/go-errors/errors v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-logr/zapr v1.3.0 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.3 // indirect diff --git a/pkg/apis/apps/v1alpha1/default.go b/pkg/apis/apps/v1alpha1/default.go index 23c4d6682ee..50669877d4e 100644 --- a/pkg/apis/apps/v1alpha1/default.go +++ b/pkg/apis/apps/v1alpha1/default.go @@ -22,7 +22,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/intstr" v1 "k8s.io/kubernetes/pkg/apis/core/v1" - utilpointer "k8s.io/utils/pointer" + utilpointer "k8s.io/utils/ptr" ) // SetDefaultsNodePool set default values for NodePool. @@ -38,7 +38,7 @@ func SetDefaultsNodePool(obj *NodePool) { func SetDefaultsYurtAppSet(obj *YurtAppSet) { if obj.Spec.RevisionHistoryLimit == nil { - obj.Spec.RevisionHistoryLimit = utilpointer.Int32(10) + obj.Spec.RevisionHistoryLimit = utilpointer.To[int32](10) } if obj.Spec.WorkloadTemplate.StatefulSetTemplate != nil { @@ -239,7 +239,7 @@ func SetDefaultsYurtStaticSet(obj *YurtStaticSet) { func SetDefaultsYurtAppDaemon(obj *YurtAppDaemon) { if obj.Spec.RevisionHistoryLimit == nil { - obj.Spec.RevisionHistoryLimit = utilpointer.Int32(10) + obj.Spec.RevisionHistoryLimit = utilpointer.To[int32](10) } if obj.Spec.WorkloadTemplate.StatefulSetTemplate != nil { diff --git a/pkg/util/iptables/testing/parse_test.go b/pkg/util/iptables/testing/parse_test.go index 6a33d2aaf3c..2c7ae243c06 100644 --- a/pkg/util/iptables/testing/parse_test.go +++ b/pkg/util/iptables/testing/parse_test.go @@ -23,7 +23,7 @@ import ( "testing" "github.com/lithammer/dedent" - utilpointer "k8s.io/utils/pointer" + utilpointer "k8s.io/utils/ptr" "github.com/openyurtio/openyurt/pkg/util/iptables" ) @@ -136,8 +136,8 @@ func TestParseRule(t *testing.T) { Comment: &IPTablesValue{Value: "ns1/svc1:p80"}, AffinityName: &IPTablesValue{Value: "KUBE-SEP-SXIVWICOYRO3J4NJ"}, AffinitySeconds: &IPTablesValue{Value: "10800"}, - AffinityCheck: utilpointer.Bool(true), - AffinityReap: utilpointer.Bool(true), + AffinityCheck: utilpointer.To(true), + AffinityReap: utilpointer.To(true), Jump: &IPTablesValue{Value: "KUBE-SEP-SXIVWICOYRO3J4NJ"}, }, }, @@ -197,7 +197,7 @@ func TestParseRule(t *testing.T) { parsed: &Rule{ Raw: `-A TEST -m recent ! --rcheck -j KUBE-SEP-SXIVWICOYRO3J4NJ`, Chain: iptables.Chain("TEST"), - AffinityCheck: utilpointer.Bool(false), + AffinityCheck: utilpointer.To(false), Jump: &IPTablesValue{Value: "KUBE-SEP-SXIVWICOYRO3J4NJ"}, }, }, diff --git a/pkg/yurthub/filter/forwardkubesvctraffic/filter_test.go b/pkg/yurthub/filter/forwardkubesvctraffic/filter_test.go index adc51b529ae..70d85bcc626 100644 --- a/pkg/yurthub/filter/forwardkubesvctraffic/filter_test.go +++ b/pkg/yurthub/filter/forwardkubesvctraffic/filter_test.go @@ -26,7 +26,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" "github.com/openyurtio/openyurt/pkg/util" "github.com/openyurtio/openyurt/pkg/yurthub/filter/base" @@ -68,7 +68,7 @@ func TestSupportedResourceAndVerbs(t *testing.T) { func TestFilter(t *testing.T) { portName := "https" - readyCondition := pointer.Bool(true) + readyCondition := ptr.To(true) var kasPort, masterPort int32 kasPort = 6443 masterHost := "169.251.2.1" diff --git a/pkg/yurthub/healthchecker/node_lease.go b/pkg/yurthub/healthchecker/node_lease.go index a00d37fbbba..5216b1a5c93 100644 --- a/pkg/yurthub/healthchecker/node_lease.go +++ b/pkg/yurthub/healthchecker/node_lease.go @@ -29,7 +29,7 @@ import ( coordclientset "k8s.io/client-go/kubernetes/typed/coordination/v1" "k8s.io/klog/v2" "k8s.io/utils/clock" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) const ( @@ -142,8 +142,8 @@ func (nl *nodeLeaseImpl) newLease(base *coordinationv1.Lease) *coordinationv1.Le Namespace: corev1.NamespaceNodeLease, }, Spec: coordinationv1.LeaseSpec{ - HolderIdentity: pointer.String(nl.holderIdentity), - LeaseDurationSeconds: pointer.Int32(nl.leaseDurationSeconds), + HolderIdentity: ptr.To(nl.holderIdentity), + LeaseDurationSeconds: ptr.To(nl.leaseDurationSeconds), }, } } else { diff --git a/pkg/yurthub/proxy/autonomy/autonomy.go b/pkg/yurthub/proxy/autonomy/autonomy.go index 13aca27380e..4ec154689cf 100644 --- a/pkg/yurthub/proxy/autonomy/autonomy.go +++ b/pkg/yurthub/proxy/autonomy/autonomy.go @@ -29,7 +29,7 @@ import ( apirequest "k8s.io/apiserver/pkg/endpoints/request" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" appsv1beta1 "github.com/openyurtio/openyurt/pkg/apis/apps/v1beta1" "github.com/openyurtio/openyurt/pkg/projectinfo" @@ -60,7 +60,7 @@ func NewAutonomyProxy( return &AutonomyProxy{ restConfigMgr: restConfigMgr, cacheMgr: cacheMgr, - cacheFailedCount: pointer.Int32(0), + cacheFailedCount: ptr.To[int32](0), } } diff --git a/pkg/yurthub/proxy/pool/pool.go b/pkg/yurthub/proxy/pool/pool.go index 2e1d95bdcc3..d8dffbdf443 100644 --- a/pkg/yurthub/proxy/pool/pool.go +++ b/pkg/yurthub/proxy/pool/pool.go @@ -108,7 +108,7 @@ func (pp *YurtCoordinatorProxy) ServeHTTP(rw http.ResponseWriter, req *http.Requ ctx := req.Context() reqInfo, ok := apirequest.RequestInfoFrom(ctx) if !ok || reqInfo == nil { - klog.Errorf("yurt-coordinator proxy cannot handle request(%s), cannot get requestInfo", hubutil.ReqString(req), reqInfo) + klog.Errorf("yurt-coordinator proxy cannot handle request(%s), cannot get requestInfo: %v", hubutil.ReqString(req), reqInfo) hubutil.Err(errors.NewBadRequest(fmt.Sprintf("yurt-coordinator proxy cannot handle request(%s), cannot get requestInfo", hubutil.ReqString(req))), rw, req) return } diff --git a/pkg/yurthub/server/nonresource.go b/pkg/yurthub/server/nonresource.go index 9c6dc6eb8cc..5936babfd00 100644 --- a/pkg/yurthub/server/nonresource.go +++ b/pkg/yurthub/server/nonresource.go @@ -25,7 +25,7 @@ import ( "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" "github.com/openyurtio/openyurt/cmd/yurthub/app/config" yurtutil "github.com/openyurtio/openyurt/pkg/util" @@ -97,7 +97,7 @@ func nonResourceHandler(kubeClient *kubernetes.Clientset, sw cachemanager.Storag } result := kubeClient.RESTClient().Get().AbsPath(path).Do(context.TODO()) - code := pointer.Int(0) + code := ptr.To(0) result.StatusCode(code) if result.Error() != nil { err := result.Error() diff --git a/pkg/yurthub/yurtcoordinator/coordinator_test.go b/pkg/yurthub/yurtcoordinator/coordinator_test.go index c7eedd5e14e..38543b84a8c 100644 --- a/pkg/yurthub/yurtcoordinator/coordinator_test.go +++ b/pkg/yurthub/yurtcoordinator/coordinator_test.go @@ -27,7 +27,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes/fake" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) var leaseGVR = schema.GroupVersionResource{ @@ -208,7 +208,7 @@ func TestIfInformerSyncLease(t *testing.T) { Namespace: namespaceInformerLease, }, Spec: coordinationv1.LeaseSpec{ - HolderIdentity: pointer.String("leader-yurthub"), + HolderIdentity: ptr.To("leader-yurthub"), }, }, Expect: true, @@ -221,7 +221,7 @@ func TestIfInformerSyncLease(t *testing.T) { Namespace: "kube-system", }, Spec: coordinationv1.LeaseSpec{ - HolderIdentity: pointer.String("other-lease"), + HolderIdentity: ptr.To("other-lease"), }, }, Expect: false, diff --git a/pkg/yurthub/yurtcoordinator/informer_lease.go b/pkg/yurthub/yurtcoordinator/informer_lease.go index 4a3c122b2e5..1d6e85e81c1 100644 --- a/pkg/yurthub/yurtcoordinator/informer_lease.go +++ b/pkg/yurthub/yurtcoordinator/informer_lease.go @@ -29,7 +29,7 @@ import ( coordclientset "k8s.io/client-go/kubernetes/typed/coordination/v1" "k8s.io/klog/v2" "k8s.io/utils/clock" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" ) // TODO: reuse code of healthchecker.NodeLease @@ -151,8 +151,8 @@ func (nl *informerLeaseTmpl) newLease(base *coordinationv1.Lease) *coordinationv Namespace: nl.leaseNamespace, }, Spec: coordinationv1.LeaseSpec{ - HolderIdentity: pointer.String(nl.holderIdentity), - LeaseDurationSeconds: pointer.Int32(nl.leaseDurationSeconds), + HolderIdentity: ptr.To(nl.holderIdentity), + LeaseDurationSeconds: ptr.To(nl.leaseDurationSeconds), }, } } else { diff --git a/pkg/yurtiotdock/clients/edgex-foundry/v3/device_client.go b/pkg/yurtiotdock/clients/edgex-foundry/v3/device_client.go index 51d3e68f0ff..9f505a1feac 100644 --- a/pkg/yurtiotdock/clients/edgex-foundry/v3/device_client.go +++ b/pkg/yurtiotdock/clients/edgex-foundry/v3/device_client.go @@ -264,7 +264,7 @@ func (efc *EdgexDeviceClient) UpdatePropertyState(ctx context.Context, propertyN bodyMap := make(map[string]string) bodyMap[parameterName] = dps.DesiredValue body, _ := json.Marshal(bodyMap) - klog.V(5).Infof("setting the property to desired value", "propertyName", parameterName, "desiredValue", string(body)) + klog.V(5).Info("setting the property to desired value", "propertyName", parameterName, "desiredValue", string(body)) rep, err := efc.R(). SetHeader("Content-Type", "application/json"). SetBody(body). diff --git a/pkg/yurtmanager/controller/internal/controller/controller.go b/pkg/yurtmanager/controller/internal/controller/controller.go index 6cc74758bd2..f33638295f1 100644 --- a/pkg/yurtmanager/controller/internal/controller/controller.go +++ b/pkg/yurtmanager/controller/internal/controller/controller.go @@ -28,8 +28,6 @@ import ( "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/util/workqueue" "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" @@ -83,17 +81,11 @@ type Controller struct { LeaderElected *bool } -// watchDescription contains all the information necessary to start a watch. -type watchDescription struct { - src source.Source - handler handler.EventHandler - predicates []predicate.Predicate -} - // Watch implements controller.Controller. func (c *Controller) Watch(src source.Source) error { c.mu.Lock() defer c.mu.Unlock() + // Controller hasn't started yet, store the watches locally and return. // // These watches are going to be held on the controller struct until the manager or user calls Start(...). @@ -150,7 +142,7 @@ func (c *Controller) Start(ctx context.Context) error { } // Start the SharedIndexInformer factories to begin populating the SharedIndexInformer caches - klog.V(2).InfoS("Starting Controller WatchSource", "controller", c.Name) + c.LogConstructor(nil).Info("Starting Controller") for _, watch := range c.startWatches { syncingSource, ok := watch.(source.SyncingSource) diff --git a/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller.go b/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller.go index 8ea899e60ed..54dc7056770 100644 --- a/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller.go +++ b/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller.go @@ -215,7 +215,6 @@ type podUpdateItem struct { // ReconcileNodeLifeCycle is the controller that manages node's life cycle. type ReconcileNodeLifeCycle struct { controllerRuntimeClient client.Client - taintManager *scheduler.NoExecuteTaintManager kubeClient clientset.Interface // This timestamp is to be used instead of LastProbeTime stored in Condition. We do this diff --git a/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller_test.go b/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller_test.go index 4a761981e50..b2b4b7bf12f 100644 --- a/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller_test.go +++ b/pkg/yurtmanager/controller/nodelifecycle/node_life_cycle_controller_test.go @@ -36,7 +36,7 @@ import ( "k8s.io/client-go/util/workqueue" "k8s.io/klog/v2" kubeletapis "k8s.io/kubelet/pkg/apis" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" taintutils "github.com/openyurtio/openyurt/pkg/util/taints" @@ -61,7 +61,7 @@ func createNodeLease(nodeName string, renewTime metav1.MicroTime) *coordv1.Lease Namespace: v1.NamespaceNodeLease, }, Spec: coordv1.LeaseSpec{ - HolderIdentity: pointer.String(nodeName), + HolderIdentity: ptr.To(nodeName), RenewTime: &renewTime, }, } diff --git a/pkg/yurtmanager/controller/nodelifecycle/scheduler/timed_workers.go b/pkg/yurtmanager/controller/nodelifecycle/scheduler/timed_workers.go index 3fd50beb111..6a065f33dec 100644 --- a/pkg/yurtmanager/controller/nodelifecycle/scheduler/timed_workers.go +++ b/pkg/yurtmanager/controller/nodelifecycle/scheduler/timed_workers.go @@ -121,7 +121,7 @@ func (q *TimedWorkerQueue) AddWork(ctx context.Context, args *WorkArgs, createdA q.Lock() defer q.Unlock() if _, exists := q.workers[key]; exists { - klog.Info("Trying to add already existing work(%v), skipping", args) + klog.Infof("Trying to add already existing work(%v), skipping", args) return } worker := createWorker(ctx, args, createdAt, fireAt, q.getWrappedWorkerFunc(key), q.clock) diff --git a/pkg/yurtmanager/controller/platformadmin/iotdock.go b/pkg/yurtmanager/controller/platformadmin/iotdock.go index 3df438759fa..4672590c1a6 100644 --- a/pkg/yurtmanager/controller/platformadmin/iotdock.go +++ b/pkg/yurtmanager/controller/platformadmin/iotdock.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" iotv1beta1 "github.com/openyurtio/openyurt/pkg/apis/iot/v1beta1" "github.com/openyurtio/openyurt/pkg/yurtmanager/controller/platformadmin/config" @@ -109,13 +109,13 @@ func newYurtIoTDockComponent(platformAdmin *iotv1beta1.PlatformAdmin, platformAd }, }, SecurityContext: &corev1.SecurityContext{ - AllowPrivilegeEscalation: pointer.Bool(false), + AllowPrivilegeEscalation: ptr.To(false), }, }, }, - TerminationGracePeriodSeconds: pointer.Int64(10), + TerminationGracePeriodSeconds: ptr.To[int64](10), SecurityContext: &corev1.PodSecurityContext{ - RunAsUser: pointer.Int64(65532), + RunAsUser: ptr.To[int64](65532), }, }, }, diff --git a/pkg/yurtmanager/controller/platformadmin/platform_admin_controller.go b/pkg/yurtmanager/controller/platformadmin/platform_admin_controller.go index e01393da44a..52c055cff2f 100644 --- a/pkg/yurtmanager/controller/platformadmin/platform_admin_controller.go +++ b/pkg/yurtmanager/controller/platformadmin/platform_admin_controller.go @@ -33,7 +33,7 @@ import ( "k8s.io/client-go/tools/record" "k8s.io/klog/v2" "k8s.io/kubectl/pkg/scheme" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" "k8s.io/utils/strings/slices" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" @@ -461,7 +461,7 @@ func (r *ReconcilePlatformAdmin) reconcileComponent(ctx context.Context, platfor { Pools: []string{poolName}, Tweaks: appsv1beta1.Tweaks{ - Replicas: pointer.Int32(1), + Replicas: ptr.To[int32](1), }, }, } @@ -591,7 +591,7 @@ func (r *ReconcilePlatformAdmin) handleYurtAppSet(ctx context.Context, platformA { Pools: yas.Spec.Pools, Tweaks: appsv1beta1.Tweaks{ - Replicas: pointer.Int32(1), + Replicas: ptr.To[int32](1), }, }, } diff --git a/pkg/yurtmanager/controller/raven/dns/gateway_dns_controller.go b/pkg/yurtmanager/controller/raven/dns/gateway_dns_controller.go index 90c239703bf..cb533977eb2 100644 --- a/pkg/yurtmanager/controller/raven/dns/gateway_dns_controller.go +++ b/pkg/yurtmanager/controller/raven/dns/gateway_dns_controller.go @@ -139,7 +139,7 @@ func (r *ReconcileDns) Reconcile(ctx context.Context, req reconcile.Request) (re } if svc != nil { if svc.Spec.ClusterIP == "" { - klog.Infoln("the service %s/%s cluster IP is empty", util.WorkingNamespace, util.GatewayProxyInternalService) + klog.Infof("the service %s/%s cluster IP is empty", util.WorkingNamespace, util.GatewayProxyInternalService) } else { proxyAddress = svc.Spec.ClusterIP } diff --git a/pkg/yurtmanager/controller/util/tools.go b/pkg/yurtmanager/controller/util/tools.go index f8095dbd9df..d0d998593ed 100644 --- a/pkg/yurtmanager/controller/util/tools.go +++ b/pkg/yurtmanager/controller/util/tools.go @@ -25,10 +25,13 @@ import ( utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/client-go/util/workqueue" + "k8s.io/klog/v2" "k8s.io/utils/integer" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "github.com/go-logr/logr" controllerimpl "github.com/openyurtio/openyurt/pkg/yurtmanager/controller/internal/controller" ) @@ -89,6 +92,10 @@ func NewNoReconcileController(name string, mgr manager.Manager, options controll options.RateLimiter = workqueue.DefaultControllerRateLimiter() } + log := mgr.GetLogger().WithValues( + "controller", name, + ) + // Create controller with dependencies set c := &controllerimpl.Controller{ MakeQueue: func() workqueue.RateLimitingInterface { @@ -97,6 +104,16 @@ func NewNoReconcileController(name string, mgr manager.Manager, options controll CacheSyncTimeout: options.CacheSyncTimeout, Name: name, RecoverPanic: options.RecoverPanic, + LogConstructor: func(req *reconcile.Request) logr.Logger { + log := log + if req != nil { + log = log.WithValues( + "object", klog.KRef(req.Namespace, req.Name), + "namespace", req.Namespace, "name", req.Name, + ) + } + return log + }, } if err := mgr.Add(c); err != nil { diff --git a/pkg/yurtmanager/controller/yurtappset/revision.go b/pkg/yurtmanager/controller/yurtappset/revision.go index 1ba69001ef5..263659235c2 100644 --- a/pkg/yurtmanager/controller/yurtappset/revision.go +++ b/pkg/yurtmanager/controller/yurtappset/revision.go @@ -142,14 +142,14 @@ func cleanRevisions(cli client.Client, yas *appsbetav1.YurtAppSet, revisions []* } if len(revisions) > revisionLimit { - klog.V(4).Info("YurtAppSet [%s/%s] clean expired revisions", yas.GetNamespace(), yas.GetName()) + klog.V(4).Infof("YurtAppSet [%s/%s] clean expired revisions", yas.GetNamespace(), yas.GetName()) for i := 0; i < len(revisions)-revisionLimit; i++ { if revisions[i].GetName() == yas.Status.CurrentRevision { - klog.Warningf("YurtAppSet [%s/%s] current revision %s is expired, skip") + klog.Warningf("YurtAppSet [%s/%s] current revision %s is expired, skip", yas.GetNamespace(), yas.GetName(), yas.Status.CurrentRevision) continue } if err := cli.Delete(context.TODO(), revisions[i]); err != nil { - klog.Errorf("YurtAppSet [%s/%s] delete expired revision %s error: %v") + klog.Errorf("YurtAppSet [%s/%s] delete expired revision %s error: %v", yas.GetNamespace(), yas.GetName(), yas.Status.CurrentRevision, err) return err } klog.Infof("YurtAppSet [%s/%s] delete expired revision %s", yas.GetNamespace(), yas.GetName(), revisions[i].Name) @@ -187,7 +187,7 @@ func createControllerRevision(cli client.Client, parent metav1.Object, revision klog.V(4).Infof("YurtAppSet [%s/%s] createControllerRevision %s: contents are the same with cr already exists", parent.GetNamespace(), parent.GetName(), clone.GetName()) return exists, nil } - klog.Info("YurtAppSet [%s/%s] createControllerRevision collision exists, collision count increased %d->%d", parent.GetNamespace(), parent.GetName(), *collisionCount, *collisionCount+1) + klog.Infof("YurtAppSet [%s/%s] createControllerRevision collision exists, collision count increased %d->%d", parent.GetNamespace(), parent.GetName(), *collisionCount, *collisionCount+1) *collisionCount++ continue } diff --git a/pkg/yurtmanager/controller/yurtappset/yurt_app_set_controller.go b/pkg/yurtmanager/controller/yurtappset/yurt_app_set_controller.go index 124e33bcaea..0ee59f57370 100644 --- a/pkg/yurtmanager/controller/yurtappset/yurt_app_set_controller.go +++ b/pkg/yurtmanager/controller/yurtappset/yurt_app_set_controller.go @@ -369,7 +369,7 @@ func (r *ReconcileYurtAppSet) conciliateWorkloads(yas *unitv1beta1.YurtAppSet, e yas.GetNamespace(), yas.GetName(), templateType, nodepoolName, err.Error()) } } - klog.Infof("YurtAppSet[%s/%s] create workload %s[%s/%s] success", + klog.Infof("YurtAppSet[%s/%s] create workload [%s/%s] success", yas.GetNamespace(), yas.GetName(), templateType, nodepoolName) return nil }) diff --git a/pkg/yurtmanager/controller/yurtstaticset/upgradeinfo/upgrade_info_test.go b/pkg/yurtmanager/controller/yurtstaticset/upgradeinfo/upgrade_info_test.go index 9ba2519898c..064ec1284ab 100644 --- a/pkg/yurtmanager/controller/yurtstaticset/upgradeinfo/upgrade_info_test.go +++ b/pkg/yurtmanager/controller/yurtstaticset/upgradeinfo/upgrade_info_test.go @@ -23,7 +23,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/rand" - utilpointer "k8s.io/utils/pointer" + utilpointer "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -274,7 +274,7 @@ var ( }, HostNetwork: true, PriorityClassName: "system-node-critical", - Priority: utilpointer.Int32(2000001000), + Priority: utilpointer.To[int32](2000001000), }, }, }, @@ -306,7 +306,7 @@ func preparePods() []*corev1.Pod { }, HostNetwork: true, PriorityClassName: "system-node-critical", - Priority: utilpointer.Int32(2000001000), + Priority: utilpointer.To[int32](2000001000), NodeName: "aaa", SchedulerName: "default-scheduler", RestartPolicy: "Always", @@ -332,7 +332,7 @@ func preparePods() []*corev1.Pod { }, }, PriorityClassName: "system-node-critical", - Priority: utilpointer.Int32(2000001000), + Priority: utilpointer.To[int32](2000001000), NodeName: "aaa", SchedulerName: "default-scheduler", RestartPolicy: "Always", diff --git a/pkg/yurtmanager/webhook/yurtappdaemon/v1alpha1/yurtappdaemon_default.go b/pkg/yurtmanager/webhook/yurtappdaemon/v1alpha1/yurtappdaemon_default.go index 71344a83e1f..712f16fdb01 100644 --- a/pkg/yurtmanager/webhook/yurtappdaemon/v1alpha1/yurtappdaemon_default.go +++ b/pkg/yurtmanager/webhook/yurtappdaemon/v1alpha1/yurtappdaemon_default.go @@ -29,7 +29,7 @@ import ( // Default satisfies the defaulting webhook interface. func (webhook *YurtAppDaemonHandler) Default(ctx context.Context, obj runtime.Object) error { - klog.Info("default object %v", obj) + klog.Infof("default object %v", obj) daemon, ok := obj.(*v1alpha1.YurtAppDaemon) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a YurtAppDaemon but got a %T", obj)) diff --git a/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default.go b/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default.go index 64c3af3b2d7..34c4b33cf35 100644 --- a/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default.go +++ b/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default.go @@ -23,7 +23,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/klog/v2" - utilpointer "k8s.io/utils/pointer" + utilpointer "k8s.io/utils/ptr" "github.com/openyurtio/openyurt/pkg/apis/apps/v1beta1" ) @@ -36,11 +36,11 @@ func (webhook *YurtAppSetHandler) Default(ctx context.Context, obj runtime.Objec } if set.Spec.RevisionHistoryLimit == nil { - set.Spec.RevisionHistoryLimit = utilpointer.Int32(10) + set.Spec.RevisionHistoryLimit = utilpointer.To[int32](10) klog.V(4).Info("defaulting YurtAppSet.Spec.RevisionHistoryLimit to 10") } - klog.V(5).Info("received a YurtAppSet: %v", obj) + klog.V(5).Infof("received a YurtAppSet: %v", obj) return nil } diff --git a/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default_test.go b/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default_test.go index 675febfcfa3..44b941328b6 100644 --- a/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default_test.go +++ b/pkg/yurtmanager/webhook/yurtappset/v1beta1/yurtappset_default_test.go @@ -22,7 +22,7 @@ import ( "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/utils/pointer" + "k8s.io/utils/ptr" "github.com/openyurtio/openyurt/pkg/apis/apps/v1beta1" ) @@ -44,17 +44,17 @@ func TestYurtAppSetHandler_Default(t *testing.T) { RevisionHistoryLimit: nil, }, }, - expected: pointer.Int32(10), + expected: ptr.To[int32](10), wantErr: false, }, { name: "should not change RevisionHistoryLimit when it is already set", obj: &v1beta1.YurtAppSet{ Spec: v1beta1.YurtAppSetSpec{ - RevisionHistoryLimit: pointer.Int32(5), + RevisionHistoryLimit: ptr.To[int32](5), }, }, - expected: pointer.Int32(5), + expected: ptr.To[int32](5), wantErr: false, }, { diff --git a/test/e2e/cmd/init/kindoperator.go b/test/e2e/cmd/init/kindoperator.go index 0cb17a68750..19507240fe2 100644 --- a/test/e2e/cmd/init/kindoperator.go +++ b/test/e2e/cmd/init/kindoperator.go @@ -187,7 +187,7 @@ func findKindPath() (string, error) { } else { goBinPath, err := getGoBinPath() if err != nil { - klog.Fatal("failed to get go bin path, %s", err) + klog.Fatalf("failed to get go bin path, %s", err) } if exist, path := checkIfKindAt(goBinPath + "/kind"); exist { diff --git a/test/e2e/yurt/yurtappset.go b/test/e2e/yurt/yurtappset.go index bf4b9636396..b47525c3760 100644 --- a/test/e2e/yurt/yurtappset.go +++ b/test/e2e/yurt/yurtappset.go @@ -30,7 +30,7 @@ package yurt // "k8s.io/apimachinery/pkg/runtime" // "k8s.io/apimachinery/pkg/util/rand" // "k8s.io/apimachinery/pkg/util/sets" -// "k8s.io/utils/pointer" +// "k8s.io/utils/ptr" // "sigs.k8s.io/controller-runtime/pkg/client" // "sigs.k8s.io/yaml" //