-
Notifications
You must be signed in to change notification settings - Fork 30
/
clients.go
75 lines (70 loc) · 2.13 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
package kube
import (
"github.com/jenkins-x/jx-kube-client/v3/pkg/kubeclient"
"github.com/pkg/errors"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
// LazyCreateDynamicClient lazily creates the dynamic client if its not defined
func LazyCreateDynamicClient(client dynamic.Interface) (dynamic.Interface, error) {
if client != nil {
return client, nil
}
f := kubeclient.NewFactory()
cfg, err := f.CreateKubeConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to get kubernetes config")
}
client, err = dynamic.NewForConfig(cfg)
if err != nil {
return nil, errors.Wrap(err, "error building dynamic clientset")
}
return client, nil
}
// LazyCreateKubeClient lazy creates the kube client if its not defined
func LazyCreateKubeClient(client kubernetes.Interface) (kubernetes.Interface, error) {
if client != nil {
return client, nil
}
f := kubeclient.NewFactory()
cfg, err := f.CreateKubeConfig()
if err != nil {
return client, errors.Wrap(err, "failed to get kubernetes config")
}
client, err = kubernetes.NewForConfig(cfg)
if err != nil {
return client, errors.Wrap(err, "error building kubernetes clientset")
}
return client, nil
}
// LazyCreateKubeClientAndNamespace lazy creates the kube client and/or the current namespace if not already defined
func LazyCreateKubeClientAndNamespace(client kubernetes.Interface, ns string) (kubernetes.Interface, string, error) {
if client != nil && ns != "" {
return client, ns, nil
}
f := kubeclient.NewFactory()
if client == nil {
cfg, err := f.CreateKubeConfig()
if err != nil {
return client, ns, errors.Wrap(err, "failed to get kubernetes config")
}
client, err = kubernetes.NewForConfig(cfg)
if err != nil {
return client, ns, errors.Wrap(err, "error building kubernetes clientset")
}
}
if ns == "" {
var err error
ns, err = kubeclient.CurrentNamespace()
if err != nil {
return client, ns, errors.Wrap(err, "failed to get current kubernetes namespace")
}
}
return client, ns, nil
}
// IsInCluster tells if we are running incluster
func IsInCluster() bool {
_, err := rest.InClusterConfig()
return err == nil
}