gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/gvisor_k8s_tool/provider/kubectl/kubectl.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package kubectl contains functions to interact with Kubernetes clusters
    16  // controlled using kubectl configurations.
    17  package kubectl
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"os/user"
    23  	"path"
    24  
    25  	"gvisor.dev/gvisor/pkg/log"
    26  	"gvisor.dev/gvisor/tools/gvisor_k8s_tool/cluster"
    27  	"k8s.io/client-go/tools/clientcmd"
    28  )
    29  
    30  // getKubeConfigPath returns the path to the kubectl config.
    31  func getKubeConfigPath() (string, error) {
    32  	if envPath, ok := os.LookupEnv("KUBECONFIG"); ok {
    33  		return envPath, nil
    34  	}
    35  	me, err := user.Current()
    36  	if err != nil {
    37  		return "", fmt.Errorf("cannot get current user information: %w", err)
    38  	}
    39  	return path.Join(me.HomeDir, ".kube/config"), nil
    40  }
    41  
    42  // NewCluster creates a new cluster client for the given context name and
    43  // using the kubectl config defined in the KUBECONFIG environment variable.
    44  // If the context name is empty, the default ("current") context is used.
    45  func NewCluster(contextName string) (*cluster.Cluster, error) {
    46  	cfgPath, err := getKubeConfigPath()
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	cfg, err := clientcmd.LoadFromFile(cfgPath)
    51  	if err != nil {
    52  		return nil, fmt.Errorf("cannot load kubectl config at %q: %w", cfgPath, err)
    53  	}
    54  	if contextName == "" {
    55  		contextName = cfg.CurrentContext
    56  		log.Infof("Using default kubectl context: %q", contextName)
    57  	}
    58  	restClient, err := clientcmd.NewNonInteractiveClientConfig(*cfg, contextName, nil, clientcmd.NewDefaultClientConfigLoadingRules()).ClientConfig()
    59  	if err != nil {
    60  		return nil, fmt.Errorf("cannot create REST client: %w", err)
    61  	}
    62  	return cluster.New(restClient)
    63  }