github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/flagutil/k8s_client.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes 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 flagutil
    18  
    19  import (
    20  	"errors"
    21  	"flag"
    22  	"fmt"
    23  	"net/url"
    24  	"os"
    25  
    26  	"k8s.io/client-go/kubernetes"
    27  	"sigs.k8s.io/prow/pkg/client/clientset/versioned"
    28  	"sigs.k8s.io/prow/pkg/kube"
    29  )
    30  
    31  // KubernetesClientOptions holds options for interacting with Kubernetes.
    32  type KubernetesClientOptions struct {
    33  	masterURL  string
    34  	kubeConfig string
    35  }
    36  
    37  // AddFlags injects Kubernetes options into the given FlagSet.
    38  func (o *KubernetesClientOptions) AddFlags(fs *flag.FlagSet) {
    39  	fs.StringVar(&o.masterURL, "masterurl", "", "URL to k8s master")
    40  	fs.StringVar(&o.kubeConfig, "kubeconfig", "", "Cluster config for the cluster you want to connect to")
    41  }
    42  
    43  // Validate validates Kubernetes options.
    44  func (o *KubernetesClientOptions) Validate(dryRun bool) error {
    45  	if dryRun && o.masterURL == "" {
    46  		return errors.New("a dry-run was requested but required flag -masterurl was unset")
    47  	}
    48  
    49  	if o.masterURL != "" {
    50  		if _, err := url.ParseRequestURI(o.masterURL); err != nil {
    51  			return fmt.Errorf("invalid -masterurl URI: %q", o.masterURL)
    52  		}
    53  	}
    54  	if o.kubeConfig != "" {
    55  		if _, err := os.Stat(o.kubeConfig); err != nil {
    56  			return err
    57  		}
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  // KubeClient returns a Kubernetes client.
    64  func (o *KubernetesClientOptions) KubeClient() (kubernetes.Interface, error) {
    65  	return kube.GetKubernetesClient(o.masterURL, o.kubeConfig)
    66  }
    67  
    68  // ProwJobClient returns a Kubernetes client.
    69  func (o *KubernetesClientOptions) ProwJobClient() (versioned.Interface, error) {
    70  	return kube.GetProwJobClient(o.masterURL, o.kubeConfig)
    71  }