github.com/oam-dev/cluster-gateway@v1.9.0/examples/dynamic-multicluster-client/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	multicluster "github.com/oam-dev/cluster-gateway/pkg/apis/cluster/transport"
     8  	"github.com/spf13/cobra"
     9  	corev1 "k8s.io/api/core/v1"
    10  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    11  	"k8s.io/apimachinery/pkg/types"
    12  	"k8s.io/client-go/kubernetes"
    13  	"k8s.io/client-go/tools/clientcmd"
    14  	"sigs.k8s.io/controller-runtime/pkg/client"
    15  )
    16  
    17  var kubeconfig string
    18  var clusterName string
    19  
    20  func main() {
    21  
    22  	cmd := cobra.Command{
    23  		RunE: func(cmd *cobra.Command, args []string) error {
    24  			cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
    25  			if err != nil {
    26  				return err
    27  			}
    28  			cfg.Wrap(multicluster.NewClusterGatewayRoundTripper)
    29  
    30  			// Native kubernetes client example
    31  			nativeClient := kubernetes.NewForConfigOrDie(cfg)
    32  			defaultNs, err := nativeClient.CoreV1().Namespaces().Get(
    33  				multicluster.WithMultiClusterContext(context.TODO(), clusterName),
    34  				"default",
    35  				metav1.GetOptions{})
    36  			fmt.Printf("Native client get default namespace: %v\n", defaultNs)
    37  
    38  			// Controller-runtime client example
    39  			controllerRuntimeClient, err := client.New(cfg, client.Options{})
    40  			if err != nil {
    41  				panic(err)
    42  			}
    43  			ns := &corev1.Namespace{}
    44  			err = controllerRuntimeClient.Get(
    45  				multicluster.WithMultiClusterContext(context.TODO(), clusterName),
    46  				types.NamespacedName{Name: "default"},
    47  				ns)
    48  			if err != nil {
    49  				panic(err)
    50  			}
    51  			fmt.Printf("Controller-runtime client get default namespace: %v\n", ns)
    52  			return nil
    53  		},
    54  	}
    55  
    56  	cmd.Flags().StringVarP(&kubeconfig, "kubeconfig", "", "", "the client kubeconfig")
    57  	cmd.Flags().StringVarP(&clusterName, "cluster-name", "", "", "the target cluster name")
    58  
    59  	if err := cmd.Execute(); err != nil {
    60  		panic(err)
    61  	}
    62  }