sigs.k8s.io/prow@v0.0.0-20240503223140-c5e374dc7eb1/pkg/kube/cluster.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 kube 18 19 import ( 20 "fmt" 21 22 "github.com/sirupsen/logrus" 23 24 "k8s.io/client-go/kubernetes" 25 "k8s.io/client-go/rest" 26 "k8s.io/client-go/tools/clientcmd" 27 28 prowjobclientset "sigs.k8s.io/prow/pkg/client/clientset/versioned" 29 30 _ "k8s.io/client-go/plugin/pkg/client/auth" 31 ) 32 33 // loadClusterConfig loads connection configuration 34 // for the cluster we're deploying to. We prefer to 35 // use in-cluster configuration if possible, but will 36 // fall back to using default rules otherwise. 37 func loadClusterConfig(masterURL, kubeConfig string) (*rest.Config, error) { 38 clusterConfig, err := clientcmd.BuildConfigFromFlags(masterURL, kubeConfig) 39 if err == nil { 40 return clusterConfig, nil 41 } 42 43 credentials, err := clientcmd.NewDefaultClientConfigLoadingRules().Load() 44 if err != nil { 45 return nil, fmt.Errorf("could not load credentials from config: %w", err) 46 } 47 48 clusterConfig, err = clientcmd.NewDefaultClientConfig(*credentials, &clientcmd.ConfigOverrides{}).ClientConfig() 49 if err != nil { 50 return nil, fmt.Errorf("could not load client configuration: %w", err) 51 } 52 return clusterConfig, nil 53 } 54 55 // GetKubernetesClient retrieves the Kubernetes cluster 56 // client from within the cluster 57 func GetKubernetesClient(masterURL, kubeConfig string) (kubernetes.Interface, error) { 58 config, err := loadClusterConfig(masterURL, kubeConfig) 59 if err != nil { 60 return nil, err 61 } 62 63 // generate the client based off of the config 64 client, err := kubernetes.NewForConfig(config) 65 if err != nil { 66 return nil, err 67 } 68 69 logrus.Info("Successfully constructed k8s client") 70 return client, nil 71 } 72 73 // GetKubernetesClient retrieves the Kubernetes cluster 74 // client from within the cluster 75 func GetProwJobClient(masterURL, kubeConfig string) (prowjobclientset.Interface, error) { 76 config, err := loadClusterConfig(masterURL, kubeConfig) 77 if err != nil { 78 return nil, err 79 } 80 81 prowjobClient, err := prowjobclientset.NewForConfig(config) 82 if err != nil { 83 return nil, err 84 } 85 86 logrus.Info("Successfully constructed k8s client") 87 return prowjobClient, nil 88 }