open-cluster-management.io/governance-policy-propagator@v0.13.0/test/e2e/e2e_suite_test.go (about)

     1  // Copyright (c) 2020 Red Hat, Inc.
     2  // Copyright Contributors to the Open Cluster Management project
     3  
     4  package e2e
     5  
     6  import (
     7  	"context"
     8  	"flag"
     9  	"fmt"
    10  	"os"
    11  	"os/user"
    12  	"path/filepath"
    13  	"testing"
    14  
    15  	. "github.com/onsi/ginkgo/v2"
    16  	. "github.com/onsi/gomega"
    17  	corev1 "k8s.io/api/core/v1"
    18  	"k8s.io/apimachinery/pkg/api/errors"
    19  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    20  	"k8s.io/apimachinery/pkg/runtime/schema"
    21  	"k8s.io/client-go/dynamic"
    22  	"k8s.io/client-go/kubernetes"
    23  	"k8s.io/client-go/rest"
    24  	"k8s.io/client-go/tools/clientcmd"
    25  	"k8s.io/klog/v2"
    26  
    27  	"open-cluster-management.io/governance-policy-propagator/test/utils"
    28  )
    29  
    30  const (
    31  	IVAnnotation            = "policy.open-cluster-management.io/encryption-iv"
    32  	EncryptionKeySecret     = "policy-encryption-key"
    33  	LastRotatedAnnotation   = "policy.open-cluster-management.io/last-rotated"
    34  	RootPolicyLabel         = "policy.open-cluster-management.io/root-policy"
    35  	TriggerUpdateAnnotation = "policy.open-cluster-management.io/trigger-update"
    36  )
    37  
    38  var (
    39  	testNamespace         string
    40  	clientHub             kubernetes.Interface
    41  	clientHubDynamic      dynamic.Interface
    42  	kubeconfigHub         string
    43  	complianceAPIPort     uint
    44  	gvrPolicy             schema.GroupVersionResource
    45  	gvrPolicyAutomation   schema.GroupVersionResource
    46  	gvrPolicySet          schema.GroupVersionResource
    47  	gvrPlacementBinding   schema.GroupVersionResource
    48  	gvrPlacementRule      schema.GroupVersionResource
    49  	gvrPlacement          schema.GroupVersionResource
    50  	gvrPlacementDecision  schema.GroupVersionResource
    51  	gvrSecret             schema.GroupVersionResource
    52  	gvrAnsibleJob         schema.GroupVersionResource
    53  	gvrNamespace          schema.GroupVersionResource
    54  	defaultTimeoutSeconds int
    55  	defaultImageRegistry  string
    56  	clientToken           string
    57  )
    58  
    59  func TestE2e(t *testing.T) {
    60  	RegisterFailHandler(Fail)
    61  	RunSpecs(t, "Policy Propagator e2e Suite")
    62  }
    63  
    64  func init() {
    65  	klog.SetOutput(GinkgoWriter)
    66  	klog.InitFlags(nil)
    67  	flag.StringVar(&kubeconfigHub, "kubeconfig_hub", "../../kubeconfig_hub_e2e",
    68  		"Location of the kubeconfig to use; defaults to current kubeconfig if set to an empty string")
    69  	flag.UintVar(
    70  		&complianceAPIPort,
    71  		"compliance-api-port",
    72  		8384,
    73  		"The port of the Compliance API port; override when running the API locally and with a running Kind cluster "+
    74  			"to avoid port conflicts",
    75  	)
    76  }
    77  
    78  var _ = BeforeSuite(func() {
    79  	By("Setup Hub client")
    80  	gvrPolicy = schema.GroupVersionResource{
    81  		Group: "policy.open-cluster-management.io", Version: "v1", Resource: "policies",
    82  	}
    83  	gvrPolicySet = schema.GroupVersionResource{
    84  		Group: "policy.open-cluster-management.io", Version: "v1beta1", Resource: "policysets",
    85  	}
    86  	gvrPlacementBinding = schema.GroupVersionResource{
    87  		Group: "policy.open-cluster-management.io", Version: "v1", Resource: "placementbindings",
    88  	}
    89  	gvrPlacementRule = schema.GroupVersionResource{
    90  		Group: "apps.open-cluster-management.io", Version: "v1", Resource: "placementrules",
    91  	}
    92  	gvrPlacement = schema.GroupVersionResource{
    93  		Group: "cluster.open-cluster-management.io", Version: "v1beta1", Resource: "placements",
    94  	}
    95  	gvrPlacementDecision = schema.GroupVersionResource{
    96  		Group: "cluster.open-cluster-management.io", Version: "v1beta1", Resource: "placementdecisions",
    97  	}
    98  	gvrSecret = schema.GroupVersionResource{
    99  		Group: "", Version: "v1", Resource: "secrets",
   100  	}
   101  	gvrPolicyAutomation = schema.GroupVersionResource{
   102  		Group: "policy.open-cluster-management.io", Version: "v1beta1", Resource: "policyautomations",
   103  	}
   104  	gvrAnsibleJob = schema.GroupVersionResource{
   105  		Group: "tower.ansible.com", Version: "v1alpha1", Resource: "ansiblejobs",
   106  	}
   107  	gvrNamespace = schema.GroupVersionResource{
   108  		Group: "", Version: "v1", Resource: "namespaces",
   109  	}
   110  	clientHub = NewKubeClient("", kubeconfigHub, "")
   111  	clientHubDynamic = NewKubeClientDynamic("", kubeconfigHub, "")
   112  	defaultImageRegistry = "quay.io/open-cluster-management"
   113  	testNamespace = "policy-propagator-test"
   114  	defaultTimeoutSeconds = 30
   115  
   116  	k8sConfig, err := LoadConfig("", "", "")
   117  	Expect(err).ToNot(HaveOccurred())
   118  	clientToken = k8sConfig.BearerToken
   119  
   120  	By("Create Namespace if needed")
   121  	namespaces := clientHub.CoreV1().Namespaces()
   122  	if _, err := namespaces.Get(
   123  		context.TODO(), testNamespace, metav1.GetOptions{},
   124  	); err != nil && errors.IsNotFound(err) {
   125  		Expect(namespaces.Create(context.TODO(), &corev1.Namespace{
   126  			ObjectMeta: metav1.ObjectMeta{
   127  				Name: testNamespace,
   128  			},
   129  		}, metav1.CreateOptions{})).NotTo(BeNil())
   130  	}
   131  	Expect(namespaces.Get(context.TODO(), testNamespace, metav1.GetOptions{})).NotTo(BeNil())
   132  })
   133  
   134  var _ = AfterSuite(func() {
   135  	By("Collecting workqueue_adds_total metrics")
   136  	wqAddsLines, err := utils.MetricsLines("workqueue_adds_total")
   137  	if err != nil {
   138  		GinkgoWriter.Println("Error getting workqueue_adds_total metrics: ", err)
   139  	}
   140  
   141  	GinkgoWriter.Println(wqAddsLines)
   142  
   143  	By("Collecting controller_runtime_reconcile_total metrics")
   144  	ctrlReconcileTotalLines, err := utils.MetricsLines("controller_runtime_reconcile_total")
   145  	if err != nil {
   146  		GinkgoWriter.Println("Error getting controller_runtime_reconcile_total metrics: ", err)
   147  	}
   148  
   149  	GinkgoWriter.Println(ctrlReconcileTotalLines)
   150  
   151  	By("Collecting controller_runtime_reconcile_time_seconds_sum metrics")
   152  	ctrlReconcileTimeLines, err := utils.MetricsLines("controller_runtime_reconcile_time_seconds_sum")
   153  	if err != nil {
   154  		GinkgoWriter.Println("Error getting controller_runtime_reconcile_time_seconds_sum metrics: ", err)
   155  	}
   156  
   157  	GinkgoWriter.Println(ctrlReconcileTimeLines)
   158  })
   159  
   160  func NewKubeClient(url, kubeconfig, context string) kubernetes.Interface {
   161  	klog.V(5).Infof("Create kubeclient for url %s using kubeconfig path %s\n", url, kubeconfig)
   162  
   163  	config, err := LoadConfig(url, kubeconfig, context)
   164  	if err != nil {
   165  		panic(err)
   166  	}
   167  
   168  	clientset, err := kubernetes.NewForConfig(config)
   169  	if err != nil {
   170  		panic(err)
   171  	}
   172  
   173  	return clientset
   174  }
   175  
   176  func NewKubeClientDynamic(url, kubeconfig, context string) dynamic.Interface {
   177  	klog.V(5).Infof("Create kubeclient dynamic for url %s using kubeconfig path %s\n", url, kubeconfig)
   178  
   179  	config, err := LoadConfig(url, kubeconfig, context)
   180  	if err != nil {
   181  		panic(err)
   182  	}
   183  
   184  	clientset, err := dynamic.NewForConfig(config)
   185  	if err != nil {
   186  		panic(err)
   187  	}
   188  
   189  	return clientset
   190  }
   191  
   192  func LoadConfig(url, kubeconfig, context string) (*rest.Config, error) {
   193  	if kubeconfig == "" {
   194  		kubeconfig = os.Getenv("KUBECONFIG")
   195  	}
   196  
   197  	klog.V(5).Infof("Kubeconfig path %s\n", kubeconfig)
   198  
   199  	// If we have an explicit indication of where the kubernetes config lives, read that.
   200  	if kubeconfig != "" {
   201  		if context == "" {
   202  			return clientcmd.BuildConfigFromFlags(url, kubeconfig)
   203  		}
   204  
   205  		return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
   206  			&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
   207  			&clientcmd.ConfigOverrides{
   208  				CurrentContext: context,
   209  			}).ClientConfig()
   210  	}
   211  
   212  	// If not, try the in-cluster config.
   213  	if c, err := rest.InClusterConfig(); err == nil {
   214  		return c, nil
   215  	}
   216  
   217  	// If no in-cluster config, try the default location in the user's home directory.
   218  	if usr, err := user.Current(); err == nil {
   219  		klog.V(5).Infof(
   220  			"clientcmd.BuildConfigFromFlags for url %s using %s\n",
   221  			url,
   222  			filepath.Join(usr.HomeDir, ".kube", "config"),
   223  		)
   224  
   225  		if c, err := clientcmd.BuildConfigFromFlags("", filepath.Join(usr.HomeDir, ".kube", "config")); err == nil {
   226  			return c, nil
   227  		}
   228  	}
   229  
   230  	return nil, fmt.Errorf("could not create a valid kubeconfig")
   231  }