Skip to content

Commit

Permalink
fix: golang lint
Browse files Browse the repository at this point in the history
feat: update klog related code
feat: add logconstructor for controller
  • Loading branch information
vie-serendipity committed Nov 7, 2024
1 parent 42bcf6a commit 0d24c5a
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 43 deletions.
14 changes: 10 additions & 4 deletions cmd/yurt-iot-dock/app/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package app

import (
"context"
"flag"
"fmt"
"net/http"
"os"
Expand All @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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{
Expand Down
4 changes: 2 additions & 2 deletions cmd/yurt-manager/app/client/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 {
Expand Down
11 changes: 9 additions & 2 deletions cmd/yurt-manager/app/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package app

import (
"flag"
"fmt"
"net/http"
"os"
Expand All @@ -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"
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions pkg/apis/apps/v1alpha1/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/util/iptables/testing/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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"},
},
},
Expand Down Expand Up @@ -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"},
},
},
Expand Down
2 changes: 1 addition & 1 deletion pkg/yurthub/proxy/pool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/yurtiotdock/clients/edgex-foundry/v3/device_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
12 changes: 2 additions & 10 deletions pkg/yurtmanager/controller/internal/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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(...).
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
17 changes: 17 additions & 0 deletions pkg/yurtmanager/controller/util/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/yurtmanager/controller/yurtappset/revision.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -274,7 +274,7 @@ var (
},
HostNetwork: true,
PriorityClassName: "system-node-critical",
Priority: utilpointer.Int32(2000001000),
Priority: utilpointer.To[int32](2000001000),
},
},
},
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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
}

0 comments on commit 0d24c5a

Please sign in to comment.