From 98ce2b25d922e066bad038c1000fd0b92bfe1f44 Mon Sep 17 00:00:00 2001 From: Yin Da Date: Tue, 28 Mar 2023 16:30:02 +0800 Subject: [PATCH] Feat: skip ocm cluster watch when not installed Signed-off-by: Yin Da --- pkg/util/cluster/cluster.go | 21 +++++++++++++++++++++ pkg/util/singleton/loopback.go | 8 +++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/pkg/util/cluster/cluster.go b/pkg/util/cluster/cluster.go index 2764f474..d2c538a6 100644 --- a/pkg/util/cluster/cluster.go +++ b/pkg/util/cluster/cluster.go @@ -2,8 +2,11 @@ package cluster import ( "context" + "fmt" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" ocmclient "open-cluster-management.io/api/client/cluster/clientset/versioned" clusterv1Lister "open-cluster-management.io/api/client/cluster/listers/cluster/v1" clusterv1 "open-cluster-management.io/api/cluster/v1" @@ -63,3 +66,21 @@ func (c *cacheOCMClusterControl) Get(ctx context.Context, name string) (*cluster func (c *cacheOCMClusterControl) List(ctx context.Context) ([]*clusterv1.ManagedCluster, error) { return c.clusterLister.List(labels.Everything()) } + +// IsOCMManagedClusterInstalled check if managed cluster is installed in the cluster +func IsOCMManagedClusterInstalled(ocmClient ocmclient.Interface) (bool, error) { + _, resources, err := ocmClient.Discovery().ServerGroupsAndResources() + if err != nil { + return false, fmt.Errorf("unable to get api-resources: %w", err) + } + for _, resource := range resources { + if gv, _ := schema.ParseGroupVersion(resource.GroupVersion); gv.Group == clusterv1.GroupName { + for _, rsc := range resource.APIResources { + if rsc.Kind == "ManagedCluster" { + return true, nil + } + } + } + } + return false, nil +} diff --git a/pkg/util/singleton/loopback.go b/pkg/util/singleton/loopback.go index fe284264..4ffa507b 100644 --- a/pkg/util/singleton/loopback.go +++ b/pkg/util/singleton/loopback.go @@ -3,6 +3,7 @@ package singleton import ( "time" + "k8s.io/klog/v2" controllerruntimeconfig "sigs.k8s.io/controller-runtime/pkg/client/config" "github.com/oam-dev/cluster-gateway/pkg/config" @@ -77,7 +78,12 @@ func InitLoopbackClient(ctx server.PostStartHookContext) error { } if utilfeature.DefaultMutableFeatureGate.Enabled(featuregates.OCMClusterCache) { - if err := setOCMClusterInformer(ocmClient, ctx.StopCh); err != nil { + installed, err := clusterutil.IsOCMManagedClusterInstalled(ocmClient) + if err != nil { + klog.Error(err) + } else if !installed { + klog.Infof("OCM ManagedCluster CRD not installed, skip bootstrapping informer for OCM ManagedCluster") + } else if err := setOCMClusterInformer(ocmClient, ctx.StopCh); err != nil { return err } clusterControl = clusterutil.NewCacheOCMClusterControl(clusterLister)