-
Notifications
You must be signed in to change notification settings - Fork 25
/
clients.go
78 lines (70 loc) · 2.06 KB
/
clients.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Copyright 2020 VMware, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package pkg
import (
"fmt"
"os"
"path/filepath"
vsphere "github.com/vmware-tanzu/sources-for-knative/pkg/client/clientset/versioned"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
type Clients struct {
ClientConfig clientcmd.ClientConfig
ClientSet kubernetes.Interface
VSphereClientSet vsphere.Interface
}
func NewClients(kubeConfigPath string) (*Clients, error) {
clientConfig, err := getClientConfig(kubeConfigPath)
if err != nil {
return nil, err
}
restConfig, err := clientConfig.ClientConfig()
if err != nil {
return nil, err
}
vSphereConfig, err := vsphere.NewForConfig(restConfig)
if err != nil {
return nil, err
}
clientSet, err := kubernetes.NewForConfig(restConfig)
if err != nil {
fmt.Println("failed to create Clients:", err)
os.Exit(1)
}
return &Clients{
ClientSet: clientSet,
ClientConfig: clientConfig,
VSphereClientSet: vSphereConfig,
}, nil
}
func (c *Clients) GetExplicitOrDefaultNamespace(ns string) (string, error) {
if ns != "" {
return ns, nil
}
namespace, _, err := c.ClientConfig.Namespace()
if err != nil {
return "", err
}
return namespace, nil
}
func getClientConfig(kubeConfigPath string) (clientcmd.ClientConfig, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if len(kubeConfigPath) == 0 {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}), nil
}
_, err := os.Stat(kubeConfigPath)
if err == nil {
loadingRules.ExplicitPath = kubeConfigPath
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}), nil
}
if !os.IsNotExist(err) {
return nil, err
}
if len(filepath.SplitList(kubeConfigPath)) > 1 {
return nil, fmt.Errorf("can not find config file. '%s' looks like a path. Please use the env var KUBECONFIG if you want to check for multiple configuration files", kubeConfigPath)
}
return nil, fmt.Errorf("config file '%s' can not be found", kubeConfigPath)
}