github.com/oam-dev/kubevela@v1.9.11/pkg/multicluster/virtual_cluster_test.go (about)

     1  /*
     2  Copyright 2020-2022 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package multicluster
    18  
    19  import (
    20  	"context"
    21  
    22  	. "github.com/onsi/ginkgo/v2"
    23  	. "github.com/onsi/gomega"
    24  	v1 "k8s.io/api/core/v1"
    25  	"k8s.io/apimachinery/pkg/api/errors"
    26  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    27  	"k8s.io/apimachinery/pkg/runtime"
    28  	"k8s.io/apimachinery/pkg/runtime/schema"
    29  	clusterv1 "open-cluster-management.io/api/cluster/v1"
    30  	"sigs.k8s.io/controller-runtime/pkg/client"
    31  
    32  	"github.com/oam-dev/cluster-gateway/pkg/apis/cluster/v1alpha1"
    33  	clustercommon "github.com/oam-dev/cluster-gateway/pkg/common"
    34  
    35  	"github.com/oam-dev/kubevela/apis/types"
    36  )
    37  
    38  var _ = Describe("Test Virtual Cluster", func() {
    39  
    40  	It("Test Virtual Cluster", func() {
    41  		ClusterGatewaySecretNamespace = "vela-system"
    42  		ctx := context.Background()
    43  		Expect(k8sClient.Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ClusterGatewaySecretNamespace}})).Should(Succeed())
    44  
    45  		By("Initialize Secrets")
    46  		Expect(k8sClient.Create(ctx, &v1.Secret{
    47  			ObjectMeta: metav1.ObjectMeta{
    48  				Name:      "test-cluster",
    49  				Namespace: ClusterGatewaySecretNamespace,
    50  				Labels: map[string]string{
    51  					clustercommon.LabelKeyClusterCredentialType: string(v1alpha1.CredentialTypeX509Certificate),
    52  					clustercommon.LabelKeyClusterEndpointType:   string(v1alpha1.ClusterEndpointTypeConst),
    53  					"key": "value",
    54  				},
    55  				Annotations: map[string]string{v1alpha1.AnnotationClusterAlias: "test-alias"},
    56  			},
    57  		})).Should(Succeed())
    58  		Expect(k8sClient.Create(ctx, &v1.Secret{
    59  			ObjectMeta: metav1.ObjectMeta{
    60  				Name:      "cluster-no-label",
    61  				Namespace: ClusterGatewaySecretNamespace,
    62  				Labels: map[string]string{
    63  					clustercommon.LabelKeyClusterCredentialType: string(v1alpha1.CredentialTypeX509Certificate),
    64  				},
    65  			},
    66  		})).Should(Succeed())
    67  		Expect(k8sClient.Create(ctx, &v1.Secret{
    68  			ObjectMeta: metav1.ObjectMeta{
    69  				Name:      "cluster-invalid",
    70  				Namespace: ClusterGatewaySecretNamespace,
    71  			},
    72  		})).Should(Succeed())
    73  
    74  		By("Test Get Virtual Cluster From Cluster Secret")
    75  		vc, err := GetVirtualCluster(ctx, k8sClient, "test-cluster")
    76  		Expect(err).Should(Succeed())
    77  		Expect(vc.Type).Should(Equal(v1alpha1.CredentialTypeX509Certificate))
    78  		Expect(vc.Labels["key"]).Should(Equal("value"))
    79  
    80  		_, err = GetVirtualCluster(ctx, k8sClient, "cluster-not-found")
    81  		Expect(err).ShouldNot(Succeed())
    82  		Expect(err.Error()).Should(ContainSubstring("no such cluster"))
    83  
    84  		_, err = GetVirtualCluster(ctx, k8sClient, "cluster-invalid")
    85  		Expect(err).ShouldNot(Succeed())
    86  		Expect(err.Error()).Should(ContainSubstring("not a valid cluster"))
    87  
    88  		By("Add OCM ManagedCluster")
    89  		Expect(k8sClient.Create(ctx, &clusterv1.ManagedCluster{
    90  			ObjectMeta: metav1.ObjectMeta{
    91  				Name:      "ocm-bad-cluster",
    92  				Namespace: ClusterGatewaySecretNamespace,
    93  			},
    94  		})).Should(Succeed())
    95  		Expect(k8sClient.Create(ctx, &clusterv1.ManagedCluster{
    96  			ObjectMeta: metav1.ObjectMeta{
    97  				Name:        "ocm-cluster",
    98  				Namespace:   ClusterGatewaySecretNamespace,
    99  				Labels:      map[string]string{"key": "value"},
   100  				Annotations: map[string]string{v1alpha1.AnnotationClusterAlias: "ocm-alias"},
   101  			},
   102  			Spec: clusterv1.ManagedClusterSpec{
   103  				ManagedClusterClientConfigs: []clusterv1.ClientConfig{{URL: "test-url"}},
   104  			},
   105  		})).Should(Succeed())
   106  
   107  		By("Test Get Virtual Cluster From OCM")
   108  
   109  		_, err = GetVirtualCluster(ctx, k8sClient, "ocm-bad-cluster")
   110  		Expect(err).ShouldNot(Succeed())
   111  		Expect(err.Error()).Should(ContainSubstring("has no client config"))
   112  
   113  		vc, err = GetVirtualCluster(ctx, k8sClient, "ocm-cluster")
   114  		Expect(err).Should(Succeed())
   115  		Expect(vc.Type).Should(Equal(types.CredentialTypeOCMManagedCluster))
   116  
   117  		By("Test List Virtual Clusters")
   118  
   119  		vcs, err := ListVirtualClusters(ctx, k8sClient)
   120  		Expect(err).Should(Succeed())
   121  		Expect(len(vcs)).Should(Equal(4))
   122  
   123  		vcs, err = FindVirtualClustersByLabels(ctx, k8sClient, map[string]string{"key": "value"})
   124  		Expect(err).Should(Succeed())
   125  		Expect(len(vcs)).Should(Equal(2))
   126  
   127  		By("Test virtual cluster list for clusterNameMapper")
   128  		cli := fakeClient{Client: k8sClient}
   129  		cnm, err := NewClusterNameMapper(ctx, cli)
   130  		Expect(err).Should(Succeed())
   131  		Expect(cnm.GetClusterName("example")).Should(Equal("example (example-alias)"))
   132  		Expect(cnm.GetClusterName("no-alias")).Should(Equal("no-alias"))
   133  		cli.returnBadRequest = true
   134  		_, err = NewClusterNameMapper(ctx, cli)
   135  		Expect(err).Should(Satisfy(errors.IsBadRequest))
   136  		cli.returnBadRequest = false
   137  		cli.virtualClusterNotRegistered = true
   138  		cnm, err = NewClusterNameMapper(ctx, cli)
   139  		Expect(err).Should(Succeed())
   140  		Expect(cnm.GetClusterName("example")).Should(Equal("example"))
   141  		Expect(cnm.GetClusterName("test-cluster")).Should(Equal("test-cluster (test-alias)"))
   142  		Expect(cnm.GetClusterName("ocm-cluster")).Should(Equal("ocm-cluster (ocm-alias)"))
   143  		cli.returnBadRequest = true
   144  		cli.virtualClusterNotRegistered = true
   145  		_, err = NewClusterNameMapper(ctx, cli)
   146  		Expect(err).ShouldNot(Succeed())
   147  	})
   148  	It("Test Cluster Version Get and Set", func() {
   149  		ClusterGatewaySecretNamespace = "vela-system2"
   150  		ctx := context.Background()
   151  		Expect(k8sClient.Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ClusterGatewaySecretNamespace}})).Should(Succeed())
   152  		cv, err := GetVersionInfoFromCluster(ctx, "local", cfg)
   153  		Expect(err).Should(BeNil())
   154  		Expect(cv.Minor).Should(Not(BeEquivalentTo("")))
   155  		Expect(cv.Major).Should(BeEquivalentTo("1"))
   156  	})
   157  
   158  })
   159  
   160  type fakeClient struct {
   161  	client.Client
   162  	returnBadRequest            bool
   163  	virtualClusterNotRegistered bool
   164  }
   165  
   166  func (c fakeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
   167  	if !c.virtualClusterNotRegistered && c.returnBadRequest {
   168  		return errors.NewBadRequest("")
   169  	}
   170  	if src, ok := list.(*v1alpha1.VirtualClusterList); ok {
   171  		if c.virtualClusterNotRegistered {
   172  			return runtime.NewNotRegisteredErrForKind("", schema.GroupVersionKind{})
   173  		}
   174  		objs := &v1alpha1.VirtualClusterList{Items: []v1alpha1.VirtualCluster{{
   175  			ObjectMeta: metav1.ObjectMeta{Name: "example"},
   176  			Spec:       v1alpha1.VirtualClusterSpec{Alias: "example-alias"},
   177  		}, {
   178  			ObjectMeta: metav1.ObjectMeta{Name: "no-alias"},
   179  		}}}
   180  		objs.DeepCopyInto(src)
   181  		return nil
   182  	}
   183  	if c.returnBadRequest {
   184  		return errors.NewBadRequest("")
   185  	}
   186  	return c.Client.List(ctx, list, opts...)
   187  }