From 4bd641459e5bba87f0875fb99f029d7d00e5f645 Mon Sep 17 00:00:00 2001 From: rambohe Date: Thu, 17 Aug 2023 12:13:23 +0800 Subject: [PATCH] remove some client global vars (#1655) Signed-off-by: rambohe-ch --- cmd/yurt-manager/app/manager.go | 9 -- pkg/client/generic_client.go | 57 ------------ pkg/client/registry.go | 56 ------------ .../daemon_pod_updater_controller.go | 7 +- .../platformadmin/platformadmin_controller.go | 13 ++- .../gateway_pickup_controller.go | 15 ++- .../endpoints/endpoints_controller.go | 5 - .../yurtappdaemon/yurtappdaemon_controller.go | 11 +-- .../yurtappset/yurtappset_controller.go | 13 +-- .../yurtstaticset/yurtstaticset_controller.go | 13 ++- pkg/profile/profile_test.go | 53 ++++++++--- pkg/util/client/client.go | 34 ------- pkg/util/discovery/discovery.go | 91 ------------------- .../util/controller/webhook_controller.go | 7 +- 14 files changed, 74 insertions(+), 310 deletions(-) delete mode 100644 pkg/client/generic_client.go delete mode 100644 pkg/client/registry.go delete mode 100644 pkg/util/client/client.go delete mode 100644 pkg/util/discovery/discovery.go diff --git a/cmd/yurt-manager/app/manager.go b/cmd/yurt-manager/app/manager.go index fd328f28674..f615dfd103a 100644 --- a/cmd/yurt-manager/app/manager.go +++ b/cmd/yurt-manager/app/manager.go @@ -37,7 +37,6 @@ import ( "github.com/openyurtio/openyurt/cmd/yurt-manager/app/config" "github.com/openyurtio/openyurt/cmd/yurt-manager/app/options" "github.com/openyurtio/openyurt/pkg/apis" - extclient "github.com/openyurtio/openyurt/pkg/client" "github.com/openyurtio/openyurt/pkg/controller" "github.com/openyurtio/openyurt/pkg/profile" "github.com/openyurtio/openyurt/pkg/projectinfo" @@ -151,16 +150,8 @@ func Run(c *config.CompletedConfig, stopCh <-chan struct{}) error { ctx := ctrl.SetupSignalHandler() cfg := ctrl.GetConfigOrDie() - setRestConfig(cfg, c) - setupLog.Info("new clientset registry") - err := extclient.NewRegistry(cfg) - if err != nil { - setupLog.Error(err, "unable to init yurt-manager clientset and informer") - os.Exit(1) - } - mgr, err := ctrl.NewManager(cfg, ctrl.Options{ Scheme: scheme, MetricsBindAddress: c.ComponentConfig.Generic.MetricsAddr, diff --git a/pkg/client/generic_client.go b/pkg/client/generic_client.go deleted file mode 100644 index 1ee4a106d8d..00000000000 --- a/pkg/client/generic_client.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2023 The OpenYurt Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package client - -import ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/discovery" - kubeclientset "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" -) - -// GenericClientset defines a generic client -type GenericClientset struct { - DiscoveryClient discovery.DiscoveryInterface - KubeClient kubeclientset.Interface -} - -// newForConfig creates a new Clientset for the given config. -func newForConfig(c *rest.Config) (*GenericClientset, error) { - cWithProtobuf := rest.CopyConfig(c) - cWithProtobuf.ContentType = runtime.ContentTypeProtobuf - discoveryClient, err := discovery.NewDiscoveryClientForConfig(cWithProtobuf) - if err != nil { - return nil, err - } - kubeClient, err := kubeclientset.NewForConfig(cWithProtobuf) - if err != nil { - return nil, err - } - return &GenericClientset{ - DiscoveryClient: discoveryClient, - KubeClient: kubeClient, - }, nil -} - -// newForConfig creates a new Clientset for the given config. -func newForConfigOrDie(c *rest.Config) *GenericClientset { - gc, err := newForConfig(c) - if err != nil { - panic(err) - } - return gc -} diff --git a/pkg/client/registry.go b/pkg/client/registry.go deleted file mode 100644 index c94aace5eff..00000000000 --- a/pkg/client/registry.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2023 The OpenYurt Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package client - -import ( - "fmt" - - "k8s.io/client-go/rest" -) - -var ( - cfg *rest.Config - - defaultGenericClient *GenericClientset -) - -// NewRegistry creates clientset by client-go -func NewRegistry(c *rest.Config) error { - var err error - defaultGenericClient, err = newForConfig(c) - if err != nil { - return err - } - cfgCopy := *c - cfg = &cfgCopy - return nil -} - -// GetGenericClient returns default clientset -func GetGenericClient() *GenericClientset { - return defaultGenericClient -} - -// GetGenericClientWithName returns clientset with given name as user-agent -func GetGenericClientWithName(name string) *GenericClientset { - if cfg == nil { - return nil - } - newCfg := *cfg - newCfg.UserAgent = fmt.Sprintf("%s/%s", cfg.UserAgent, name) - return newForConfigOrDie(&newCfg) -} diff --git a/pkg/controller/daemonpodupdater/daemon_pod_updater_controller.go b/pkg/controller/daemonpodupdater/daemon_pod_updater_controller.go index 6c06ea36e19..95e27645a13 100644 --- a/pkg/controller/daemonpodupdater/daemon_pod_updater_controller.go +++ b/pkg/controller/daemonpodupdater/daemon_pod_updater_controller.go @@ -50,8 +50,6 @@ import ( appconfig "github.com/openyurtio/openyurt/cmd/yurt-manager/app/config" k8sutil "github.com/openyurtio/openyurt/pkg/controller/daemonpodupdater/kubernetes" - utilclient "github.com/openyurtio/openyurt/pkg/util/client" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) func init() { @@ -103,9 +101,6 @@ func Format(format string, args ...interface{}) string { // Add creates a new Daemonpodupdater Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *appconfig.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - return nil - } klog.Infof("daemonupdater-controller add controller %s", controllerKind.String()) return add(mgr, newReconciler(c, mgr)) } @@ -123,7 +118,7 @@ type ReconcileDaemonpodupdater struct { // newReconciler returns a new reconcile.Reconciler func newReconciler(_ *appconfig.CompletedConfig, mgr manager.Manager) reconcile.Reconciler { return &ReconcileDaemonpodupdater{ - Client: utilclient.NewClientFromManager(mgr, ControllerName), + Client: mgr.GetClient(), expectations: k8sutil.NewControllerExpectations(), recorder: mgr.GetEventRecorderFor(ControllerName), } diff --git a/pkg/controller/platformadmin/platformadmin_controller.go b/pkg/controller/platformadmin/platformadmin_controller.go index dddb4178a9e..1edc362cfa1 100644 --- a/pkg/controller/platformadmin/platformadmin_controller.go +++ b/pkg/controller/platformadmin/platformadmin_controller.go @@ -49,8 +49,6 @@ import ( iotv1alpha2 "github.com/openyurtio/openyurt/pkg/apis/iot/v1alpha2" "github.com/openyurtio/openyurt/pkg/controller/platformadmin/config" util "github.com/openyurtio/openyurt/pkg/controller/platformadmin/utils" - utilclient "github.com/openyurtio/openyurt/pkg/util/client" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) func init() { @@ -64,7 +62,7 @@ func Format(format string, args ...interface{}) string { var ( concurrentReconciles = 3 - controllerKind = iotv1alpha2.SchemeGroupVersion.WithKind("PlatformAdmin") + controllerResource = iotv1alpha2.SchemeGroupVersion.WithResource("platformadmins") ) const ( @@ -121,18 +119,19 @@ var _ reconcile.Reconciler = &ReconcilePlatformAdmin{} // Add creates a new PlatformAdmin Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *appconfig.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - return nil + if _, err := mgr.GetRESTMapper().KindFor(controllerResource); err != nil { + klog.Infof("resource %s doesn't exist", controllerResource.String()) + return err } - klog.Infof("platformadmin-controller add controller %s", controllerKind.String()) + klog.Infof("platformadmin-controller add controller %s", controllerResource.String()) return add(mgr, newReconciler(c, mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(c *appconfig.CompletedConfig, mgr manager.Manager) reconcile.Reconciler { return &ReconcilePlatformAdmin{ - Client: utilclient.NewClientFromManager(mgr, ControllerName), + Client: mgr.GetClient(), scheme: mgr.GetScheme(), recorder: mgr.GetEventRecorderFor(ControllerName), yamlSerializer: kjson.NewSerializerWithOptions(kjson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, kjson.SerializerOptions{Yaml: true, Pretty: true}), diff --git a/pkg/controller/raven/gatewaypickup/gateway_pickup_controller.go b/pkg/controller/raven/gatewaypickup/gateway_pickup_controller.go index 75d26b9477d..24d8337a21a 100644 --- a/pkg/controller/raven/gatewaypickup/gateway_pickup_controller.go +++ b/pkg/controller/raven/gatewaypickup/gateway_pickup_controller.go @@ -46,12 +46,10 @@ import ( "github.com/openyurtio/openyurt/pkg/controller/raven/gatewaypickup/config" "github.com/openyurtio/openyurt/pkg/controller/raven/utils" nodeutil "github.com/openyurtio/openyurt/pkg/controller/util/node" - utilclient "github.com/openyurtio/openyurt/pkg/util/client" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) var ( - controllerKind = ravenv1beta1.SchemeGroupVersion.WithKind("Gateway") + controllerResource = ravenv1beta1.SchemeGroupVersion.WithResource("gateways") ) func Format(format string, args ...interface{}) string { @@ -68,10 +66,11 @@ const ( // Add creates a new Gateway Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *appconfig.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - return nil + if _, err := mgr.GetRESTMapper().KindFor(controllerResource); err != nil { + klog.Infof("resource %s doesn't exist", controllerResource.String()) + return err } - klog.Infof("raven-gateway-controller add controller %s", controllerKind.String()) + klog.Infof("raven-gateway-controller add controller %s", controllerResource.String()) return add(mgr, newReconciler(c, mgr)) } @@ -88,7 +87,7 @@ type ReconcileGateway struct { // newReconciler returns a new reconcile.Reconciler func newReconciler(c *appconfig.CompletedConfig, mgr manager.Manager) reconcile.Reconciler { return &ReconcileGateway{ - Client: utilclient.NewClientFromManager(mgr, common.GatewayPickupControllerName), + Client: mgr.GetClient(), scheme: mgr.GetScheme(), recorder: mgr.GetEventRecorderFor(common.GatewayPickupControllerName), Configration: c.ComponentConfig.GatewayPickupController, @@ -117,7 +116,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { return err } - err = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &EnqueueGatewayForRavenConfig{client: utilclient.NewClientFromManager(mgr, "raven-config")}, predicate.NewPredicateFuncs( + err = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &EnqueueGatewayForRavenConfig{client: mgr.GetClient()}, predicate.NewPredicateFuncs( func(object client.Object) bool { cm, ok := object.(*corev1.ConfigMap) if !ok { diff --git a/pkg/controller/servicetopology/endpoints/endpoints_controller.go b/pkg/controller/servicetopology/endpoints/endpoints_controller.go index ed1c15ad370..e35426e662f 100644 --- a/pkg/controller/servicetopology/endpoints/endpoints_controller.go +++ b/pkg/controller/servicetopology/endpoints/endpoints_controller.go @@ -33,7 +33,6 @@ import ( appconfig "github.com/openyurtio/openyurt/cmd/yurt-manager/app/config" common "github.com/openyurtio/openyurt/pkg/controller/servicetopology" "github.com/openyurtio/openyurt/pkg/controller/servicetopology/adapter" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) func init() { @@ -53,10 +52,6 @@ func Format(format string, args ...interface{}) string { // Add creates a new Servicetopology endpoints Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *appconfig.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - return nil - } - klog.Infof("servicetopology-endpoints-controller add controller %s", controllerKind.String()) return add(mgr, newReconciler(c, mgr)) } diff --git a/pkg/controller/yurtappdaemon/yurtappdaemon_controller.go b/pkg/controller/yurtappdaemon/yurtappdaemon_controller.go index 9d5cff753f8..0434ec7b70f 100644 --- a/pkg/controller/yurtappdaemon/yurtappdaemon_controller.go +++ b/pkg/controller/yurtappdaemon/yurtappdaemon_controller.go @@ -41,12 +41,11 @@ import ( unitv1alpha1 "github.com/openyurtio/openyurt/pkg/apis/apps/v1alpha1" "github.com/openyurtio/openyurt/pkg/controller/util" "github.com/openyurtio/openyurt/pkg/controller/yurtappdaemon/workloadcontroller" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) var ( concurrentReconciles = 3 - controllerKind = unitv1alpha1.SchemeGroupVersion.WithKind("YurtAppDaemon") + controllerResource = unitv1alpha1.SchemeGroupVersion.WithResource("yurtappdaemons") ) const ( @@ -74,12 +73,12 @@ func Format(format string, args ...interface{}) string { // The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *config.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - klog.Errorf(Format("DiscoverGVK error")) - return nil + if _, err := mgr.GetRESTMapper().KindFor(controllerResource); err != nil { + klog.Infof("resource %s doesn't exist", controllerResource.String()) + return err } - klog.Infof("yurtappdaemon-controller add controller %s", controllerKind.String()) + klog.Infof("yurtappdaemon-controller add controller %s", controllerResource.String()) return add(mgr, newReconciler(mgr)) } diff --git a/pkg/controller/yurtappset/yurtappset_controller.go b/pkg/controller/yurtappset/yurtappset_controller.go index 572403328f1..eeeb4c79e49 100644 --- a/pkg/controller/yurtappset/yurtappset_controller.go +++ b/pkg/controller/yurtappset/yurtappset_controller.go @@ -43,7 +43,6 @@ import ( "github.com/openyurtio/openyurt/cmd/yurt-manager/app/config" unitv1alpha1 "github.com/openyurtio/openyurt/pkg/apis/apps/v1alpha1" "github.com/openyurtio/openyurt/pkg/controller/yurtappset/adapter" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) func init() { @@ -52,7 +51,7 @@ func init() { var ( concurrentReconciles = 3 - controllerKind = unitv1alpha1.SchemeGroupVersion.WithKind("YurtAppSet") + controllerResource = unitv1alpha1.SchemeGroupVersion.WithResource("yurtappsets") ) const ( @@ -75,19 +74,17 @@ func Format(format string, args ...interface{}) string { // Add creates a new YurtAppSet Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *config.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - klog.Errorf(Format("DiscoverGVK error")) - return nil + if _, err := mgr.GetRESTMapper().KindFor(controllerResource); err != nil { + klog.Infof("resource %s doesn't exist", controllerResource.String()) + return err } - klog.Infof("yurtappset-controller add controller %s", controllerKind.String()) + klog.Infof("yurtappset-controller add controller %s", controllerResource.String()) return add(mgr, newReconciler(c, mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(c *config.CompletedConfig, mgr manager.Manager) reconcile.Reconciler { - klog.Infof("yurtappset-controller newReconciler %s", controllerKind.String()) - return &ReconcileYurtAppSet{ Client: mgr.GetClient(), scheme: mgr.GetScheme(), diff --git a/pkg/controller/yurtstaticset/yurtstaticset_controller.go b/pkg/controller/yurtstaticset/yurtstaticset_controller.go index c3469a05645..2047b64a051 100644 --- a/pkg/controller/yurtstaticset/yurtstaticset_controller.go +++ b/pkg/controller/yurtstaticset/yurtstaticset_controller.go @@ -45,8 +45,6 @@ import ( "github.com/openyurtio/openyurt/pkg/controller/yurtstaticset/config" "github.com/openyurtio/openyurt/pkg/controller/yurtstaticset/upgradeinfo" "github.com/openyurtio/openyurt/pkg/controller/yurtstaticset/util" - utilclient "github.com/openyurtio/openyurt/pkg/util/client" - utildiscovery "github.com/openyurtio/openyurt/pkg/util/discovery" ) func init() { @@ -55,7 +53,7 @@ func init() { var ( concurrentReconciles = 3 - controllerKind = appsv1alpha1.SchemeGroupVersion.WithKind("YurtStaticSet") + controllerResource = appsv1alpha1.SchemeGroupVersion.WithResource("yurtstaticsets") True = true ) @@ -128,11 +126,12 @@ func Format(format string, args ...interface{}) string { // Add creates a new YurtStaticSet Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(c *appconfig.CompletedConfig, mgr manager.Manager) error { - if !utildiscovery.DiscoverGVK(controllerKind) { - return nil + if _, err := mgr.GetRESTMapper().KindFor(controllerResource); err != nil { + klog.Infof("resource %s doesn't exist", controllerResource.String()) + return err } - klog.Infof("yurtstaticset-controller add controller %s", controllerKind.String()) + klog.Infof("yurtstaticset-controller add controller %s", controllerResource.String()) return add(mgr, newReconciler(c, mgr)) } @@ -149,7 +148,7 @@ type ReconcileYurtStaticSet struct { // newReconciler returns a new reconcile.Reconciler func newReconciler(c *appconfig.CompletedConfig, mgr manager.Manager) reconcile.Reconciler { return &ReconcileYurtStaticSet{ - Client: utilclient.NewClientFromManager(mgr, ControllerName), + Client: mgr.GetClient(), scheme: mgr.GetScheme(), recorder: mgr.GetEventRecorderFor(ControllerName), Configuration: c.ComponentConfig.YurtStaticSetController, diff --git a/pkg/profile/profile_test.go b/pkg/profile/profile_test.go index cfb7f2e7e78..998b6f91a75 100644 --- a/pkg/profile/profile_test.go +++ b/pkg/profile/profile_test.go @@ -18,28 +18,53 @@ package profile import ( "net/http" + "net/http/httptest" "testing" "github.com/gorilla/mux" ) -func fakeServer(h http.Handler) error { - err := http.ListenAndServe(":9090", h) - return err -} - +// TestInstall checks Install function correctly sets up routes func TestInstall(t *testing.T) { - t.Run("TestInstall", func(t *testing.T) { - m := mux.NewRouter() - Install(m) - go fakeServer(m) - r, err := http.Get("http://localhost:9090/debug/pprof/") + router := mux.NewRouter() + Install(router) + + // Define the routes we expect to exist and their expected handlers + expectedRoutes := map[string]string{ + "/debug/pprof/profile": "profile", + "/debug/pprof/symbol": "symbol", + "/debug/pprof/trace": "trace", + } + + // For each route, make a request and check the handler that's called + for route := range expectedRoutes { + req, err := http.NewRequest("GET", route, nil) if err != nil { - t.Errorf("failed to send request to fake server, %v", err) + t.Fatal(err) } + rr := httptest.NewRecorder() + router.ServeHTTP(rr, req) - if r.StatusCode != http.StatusOK { - t.Error(err) + if rr.Code != http.StatusOK { + t.Errorf("handler(%s) returned wrong status code: got %v want %v", route, rr.Code, http.StatusOK) } - }) + } +} + +// TestRedirectTo checks redirect to the desired location +func TestRedirectTo(t *testing.T) { + destination := "/destination" + redirect := redirectTo(destination) + + req, err := http.NewRequest("GET", "/", nil) + if err != nil { + t.Fatal(err) + } + rr := httptest.NewRecorder() + + redirect(rr, req) + + if location := rr.Header().Get("Location"); location != destination { + t.Errorf("expected redirect to %s, got %s", destination, location) + } } diff --git a/pkg/util/client/client.go b/pkg/util/client/client.go deleted file mode 100644 index 46f8e9b181f..00000000000 --- a/pkg/util/client/client.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright 2023 The OpenYurt Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package client - -import ( - "fmt" - - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -func NewClientFromManager(mgr manager.Manager, name string) client.Client { - cfg := rest.CopyConfig(mgr.GetConfig()) - cfg.UserAgent = fmt.Sprintf("yurt-manager/%s", name) - - delegatingClient, _ := cluster.DefaultNewClient(mgr.GetCache(), cfg, client.Options{Scheme: mgr.GetScheme(), Mapper: mgr.GetRESTMapper()}) - return delegatingClient -} diff --git a/pkg/util/discovery/discovery.go b/pkg/util/discovery/discovery.go deleted file mode 100644 index de75f164e26..00000000000 --- a/pkg/util/discovery/discovery.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2023 The OpenYurt Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package discovery - -import ( - "fmt" - "time" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/util/retry" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client/apiutil" - - "github.com/openyurtio/openyurt/pkg/apis" - "github.com/openyurtio/openyurt/pkg/client" -) - -var ( - internalScheme = runtime.NewScheme() - - errKindNotFound = fmt.Errorf("kind not found in group version resources") - backOff = wait.Backoff{ - Steps: 4, - Duration: 500 * time.Millisecond, - Factor: 5.0, - Jitter: 0.1, - } -) - -func init() { - _ = apis.AddToScheme(internalScheme) -} - -func DiscoverGVK(gvk schema.GroupVersionKind) bool { - genericClient := client.GetGenericClient() - if genericClient == nil { - return true - } - discoveryClient := genericClient.DiscoveryClient - - startTime := time.Now() - err := retry.OnError(backOff, func(err error) bool { return true }, func() error { - resourceList, err := discoveryClient.ServerResourcesForGroupVersion(gvk.GroupVersion().String()) - if err != nil { - return err - } - for _, r := range resourceList.APIResources { - if r.Kind == gvk.Kind { - return nil - } - } - return errKindNotFound - }) - - if err != nil { - if err == errKindNotFound { - klog.Warningf("Not found kind %s in group version %s, waiting time %s", gvk.Kind, gvk.GroupVersion().String(), time.Since(startTime)) - return false - } - - // This might be caused by abnormal apiserver or etcd, ignore it - klog.Errorf("Failed to find resources in group version %s: %v, waiting time %s", gvk.GroupVersion().String(), err, time.Since(startTime)) - } - - return true -} - -func DiscoverObject(obj runtime.Object) bool { - gvk, err := apiutil.GVKForObject(obj, internalScheme) - if err != nil { - klog.Warningf("Not recognized object %T in scheme: %v", obj, err) - return false - } - return DiscoverGVK(gvk) -} diff --git a/pkg/webhook/util/controller/webhook_controller.go b/pkg/webhook/util/controller/webhook_controller.go index 5ca3e807bbf..2734dad20e9 100644 --- a/pkg/webhook/util/controller/webhook_controller.go +++ b/pkg/webhook/util/controller/webhook_controller.go @@ -43,7 +43,6 @@ import ( "k8s.io/klog/v2" "github.com/openyurtio/openyurt/cmd/yurt-manager/app/config" - extclient "github.com/openyurtio/openyurt/pkg/client" webhookutil "github.com/openyurtio/openyurt/pkg/webhook/util" "github.com/openyurtio/openyurt/pkg/webhook/util/configuration" "github.com/openyurtio/openyurt/pkg/webhook/util/generator" @@ -80,8 +79,12 @@ type Controller struct { } func New(handlers map[string]struct{}, cc *config.CompletedConfig, restCfg *rest.Config) (*Controller, error) { + kubeClient, err := clientset.NewForConfig(restCfg) + if err != nil { + return nil, err + } c := &Controller{ - kubeClient: extclient.GetGenericClientWithName("webhook-controller").KubeClient, + kubeClient: kubeClient, handlers: handlers, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "webhook-controller"), webhookPort: cc.ComponentConfig.Generic.WebhookPort,