/
clients.go
113 lines (94 loc) · 2.68 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package k8s
import (
"path/filepath"
"github.com/rs/zerolog/log"
"k8s.io/client-go/kubernetes"
// enable all authentication methods
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"github.com/dyrector-io/dyrectorio/golang/pkg/crane/config"
)
type Client struct {
appConfig *config.Configuration
InClusterConfig func() (*rest.Config, error)
BuildConfigFromFlags func(masterUrl, kubeconfigPath string) (*rest.Config, error)
}
func NewClient(cfg *config.Configuration) *Client {
client := &Client{
appConfig: cfg,
InClusterConfig: rest.InClusterConfig,
BuildConfigFromFlags: clientcmd.BuildConfigFromFlags,
}
return client
}
func (c *Client) GetRestConfig() (*rest.Config, error) {
if c.appConfig.CraneInCluster {
return rest.InClusterConfig()
}
return c.getLocalKubeConf()
}
func (c *Client) GetClientSet() (*kubernetes.Clientset, error) {
if c.appConfig.CraneInCluster {
return c.inClusterAuth()
}
return c.outClusterAuth()
}
func (c *Client) inClusterAuth() (*kubernetes.Clientset, error) {
clusterConfig, err := c.InClusterConfig()
if err != nil {
log.Error().Err(err).Stack().Send()
return nil, err
}
clusterConfig.Timeout = c.appConfig.DefaultKubeTimeout
clientset, err := kubernetes.NewForConfig(clusterConfig)
return clientset, err
}
func (c *Client) getLocalKubeConf() (*rest.Config, error) {
var kubeconfig *string
if configPathFromEnv := c.appConfig.KubeConfig; configPathFromEnv != "" {
kubeconfig = &configPathFromEnv
} else if home := homedir.HomeDir(); home != "" {
cfgPath := filepath.Join(home, ".kube", "config")
kubeconfig = &cfgPath
}
configFromFlags, err := c.BuildConfigFromFlags("", *kubeconfig)
if configFromFlags != nil {
configFromFlags.Timeout = c.appConfig.DefaultKubeTimeout
}
return configFromFlags, err
}
func (c *Client) outClusterAuth() (*kubernetes.Clientset, error) {
localConfig, err := c.getLocalKubeConf()
if err != nil {
return nil, err
}
// create the clientset
clientset, err := kubernetes.NewForConfig(localConfig)
if err != nil {
log.Error().Err(err).Stack().Msg("Could not create client set")
}
return clientset, err
}
func (c *Client) VerifyAPIResourceExists(targetGroup, targetKind string) bool {
found := false
clientSet, err := c.GetClientSet()
if err != nil {
log.Err(err)
}
_, apiResources, err := clientSet.ServerGroupsAndResources()
if err != nil {
log.Err(err).Send()
}
for _, res := range apiResources {
if res.GroupVersion == targetGroup {
for i := range res.APIResources {
if res.APIResources[i].Kind == targetKind {
return true
}
}
}
}
return found
}