github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/kubernetes/client.go (about)

     1  package kubernetes
     2  
     3  import (
     4  	"context"
     5  	"path/filepath"
     6  	"time"
     7  
     8  	"github.com/kyma-incubator/compass/components/director/pkg/log"
     9  
    10  	"github.com/pkg/errors"
    11  	"k8s.io/apimachinery/pkg/util/wait"
    12  	"k8s.io/client-go/kubernetes"
    13  	restclient "k8s.io/client-go/rest"
    14  	"k8s.io/client-go/tools/clientcmd"
    15  	"k8s.io/client-go/util/homedir"
    16  )
    17  
    18  // Config missing godoc
    19  type Config struct {
    20  	PollInterval time.Duration `envconfig:"optional,default=2s,APP_KUBERNETES_POLL_INTERVAL"`
    21  	PollTimeout  time.Duration `envconfig:"optional,default=1m,APP_KUBERNETES_POLL_TIMEOUT"`
    22  	Timeout      time.Duration `envconfig:"optional,default=2m,APP_KUBERNETES_TIMEOUT"`
    23  }
    24  
    25  // NewKubernetesClientSet missing godoc
    26  func NewKubernetesClientSet(ctx context.Context, interval, pollingTimeout, timeout time.Duration) (*kubernetes.Clientset, error) {
    27  	kubeConfig, err := restclient.InClusterConfig()
    28  	if err != nil {
    29  		log.C(ctx).WithError(err).Errorf("An error has occurred while trying to read in cluster Config: %v", err)
    30  		log.C(ctx).Debug("Trying to initialize Kubernetes Client with local Config")
    31  		home := homedir.HomeDir()
    32  		kubeConfPath := filepath.Join(home, ".kube", "config")
    33  		kubeConfig, err = clientcmd.BuildConfigFromFlags("", kubeConfPath)
    34  		if err != nil {
    35  			return nil, errors.Errorf("failed to read k8s in-cluster configuration, %s", err.Error())
    36  		}
    37  	}
    38  
    39  	kubeConfig.Timeout = timeout
    40  
    41  	kubeClientSet, err := kubernetes.NewForConfig(kubeConfig)
    42  	if err != nil {
    43  		return nil, errors.Errorf("failed to create k8s core client, %s", err.Error())
    44  	}
    45  
    46  	err = wait.PollImmediate(interval, pollingTimeout, func() (bool, error) {
    47  		_, err := kubeClientSet.ServerVersion()
    48  		if err != nil {
    49  			log.C(ctx).WithError(err).Errorf("An error has occurred while trying to access API Server: %v", err)
    50  			return false, nil
    51  		}
    52  		return true, nil
    53  	})
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	log.C(ctx).Info("Successfully initialized kubernetes client")
    59  	return kubeClientSet, nil
    60  }