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 c7d9f1e
Show file tree
Hide file tree
Showing 30 changed files with 95 additions and 73 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
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
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
4 changes: 2 additions & 2 deletions pkg/yurthub/filter/forwardkubesvctraffic/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
6 changes: 3 additions & 3 deletions pkg/yurthub/healthchecker/node_lease.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions pkg/yurthub/proxy/autonomy/autonomy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -60,7 +60,7 @@ func NewAutonomyProxy(
return &AutonomyProxy{
restConfigMgr: restConfigMgr,
cacheMgr: cacheMgr,
cacheFailedCount: pointer.Int32(0),
cacheFailedCount: ptr.To[int32](0),
}
}

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
4 changes: 2 additions & 2 deletions pkg/yurthub/server/nonresource.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions pkg/yurthub/yurtcoordinator/coordinator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions pkg/yurthub/yurtcoordinator/informer_lease.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
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 @@ -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"
Expand All @@ -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,
},
}
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
Loading

0 comments on commit c7d9f1e

Please sign in to comment.