github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/prow/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  	"k8s.io/test-infra/prow/client/clientset/versioned"
    28  	"k8s.io/test-infra/prow/kube"
    29  )
    30  
    31  // KubernetesOptions 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  
    39  func (o *KubernetesClientOptions) AddFlags(fs *flag.FlagSet) {
    40  	fs.StringVar(&o.masterURL, "masterurl", "", "URL to k8s master")
    41  	fs.StringVar(&o.kubeConfig, "kubeconfig", "", "Cluster config for the cluster you want to connect to")
    42  }
    43  
    44  // Validate validates Kubernetes options.
    45  func (o *KubernetesClientOptions) Validate(dryRun bool) error {
    46  	if dryRun && o.masterURL == "" {
    47  		return errors.New("a dry-run was requested but required flag -masterurl was unset")
    48  	}
    49  
    50  	if o.masterURL != "" {
    51  		if _, err := url.ParseRequestURI(o.masterURL); err != nil {
    52  			return fmt.Errorf("invalid -masterurl URI: %q", o.masterURL)
    53  		}
    54  	}
    55  	if o.kubeConfig != "" {
    56  		if _, err := os.Stat(o.kubeConfig); err != nil {
    57  			return err
    58  		}
    59  	}
    60  
    61  	return nil
    62  }
    63  
    64  // Client returns a Kubernetes client.
    65  func (o *KubernetesClientOptions) KubeClient() (kubernetes.Interface, error) {
    66  	return kube.GetKubernetesClient(o.masterURL, o.kubeConfig)
    67  }
    68  
    69  // Client returns a Kubernetes client.
    70  func (o *KubernetesClientOptions) ProwJobClient() (versioned.Interface, error) {
    71  	return kube.GetProwJobClient(o.masterURL, o.kubeConfig)
    72  }