github.com/oam-dev/cluster-gateway@v1.9.0/pkg/util/cluster/cluster.go (about) 1 package cluster 2 3 import ( 4 "context" 5 "fmt" 6 7 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 8 "k8s.io/apimachinery/pkg/labels" 9 "k8s.io/apimachinery/pkg/runtime/schema" 10 ocmclient "open-cluster-management.io/api/client/cluster/clientset/versioned" 11 clusterv1Lister "open-cluster-management.io/api/client/cluster/listers/cluster/v1" 12 clusterv1 "open-cluster-management.io/api/cluster/v1" 13 ) 14 15 type OCMClusterControl interface { 16 Get(ctx context.Context, name string) (*clusterv1.ManagedCluster, error) 17 List(ctx context.Context) ([]*clusterv1.ManagedCluster, error) 18 } 19 20 var _ OCMClusterControl = &directOCMClusterControl{} 21 22 type directOCMClusterControl struct { 23 ocmClient ocmclient.Interface 24 } 25 26 func NewDirectOCMClusterControl(ocmClient ocmclient.Interface) OCMClusterControl { 27 return &directOCMClusterControl{ 28 ocmClient: ocmClient, 29 } 30 } 31 32 func (c *directOCMClusterControl) Get(ctx context.Context, name string) (*clusterv1.ManagedCluster, error) { 33 return c.ocmClient.ClusterV1().ManagedClusters().Get(ctx, name, metav1.GetOptions{}) 34 } 35 36 func (c *directOCMClusterControl) List(ctx context.Context) ([]*clusterv1.ManagedCluster, error) { 37 clusterList, err := c.ocmClient.ClusterV1().ManagedClusters().List(ctx, metav1.ListOptions{}) 38 if err != nil { 39 return nil, err 40 } 41 42 clusters := make([]*clusterv1.ManagedCluster, len(clusterList.Items)) 43 for _, item := range clusters { 44 clusters = append(clusters, item) 45 } 46 47 return clusters, nil 48 } 49 50 var _ OCMClusterControl = &cacheOCMClusterControl{} 51 52 type cacheOCMClusterControl struct { 53 clusterLister clusterv1Lister.ManagedClusterLister 54 } 55 56 func NewCacheOCMClusterControl(clusterLister clusterv1Lister.ManagedClusterLister) OCMClusterControl { 57 return &cacheOCMClusterControl{ 58 clusterLister: clusterLister, 59 } 60 } 61 62 func (c *cacheOCMClusterControl) Get(ctx context.Context, name string) (*clusterv1.ManagedCluster, error) { 63 return c.clusterLister.Get(name) 64 } 65 66 func (c *cacheOCMClusterControl) List(ctx context.Context) ([]*clusterv1.ManagedCluster, error) { 67 return c.clusterLister.List(labels.Everything()) 68 } 69 70 // IsOCMManagedClusterInstalled check if managed cluster is installed in the cluster 71 func IsOCMManagedClusterInstalled(ocmClient ocmclient.Interface) (bool, error) { 72 _, resources, err := ocmClient.Discovery().ServerGroupsAndResources() 73 if err != nil { 74 return false, fmt.Errorf("unable to get api-resources: %w", err) 75 } 76 for _, resource := range resources { 77 if gv, _ := schema.ParseGroupVersion(resource.GroupVersion); gv.Group == clusterv1.GroupName { 78 for _, rsc := range resource.APIResources { 79 if rsc.Kind == "ManagedCluster" { 80 return true, nil 81 } 82 } 83 } 84 } 85 return false, nil 86 }