-
Notifications
You must be signed in to change notification settings - Fork 4
/
kubernetes.go
128 lines (92 loc) · 1.73 KB
/
kubernetes.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package kubernetes
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
type Client interface {
kubernetes.Interface
ConfigPath() string
Config() *rest.Config
Namespace() string
}
func New() (Client, error) {
return NewFromConfig("")
}
func NewFromConfig(path string) (Client, error) {
if path == "" {
path = ConfigPath()
}
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
config, err := clientcmd.NewClientConfigFromBytes(data)
if err != nil {
return nil, err
}
c, err := config.ClientConfig()
if err != nil {
return nil, err
}
ns, _, _ := config.Namespace()
if ns == "" {
ns = "default"
}
cs, err := kubernetes.NewForConfig(c)
if err != nil {
return nil, err
}
client := &client{
path: path,
config: c,
namespace: ns,
Interface: cs,
}
return client, nil
}
type client struct {
kubernetes.Interface
path string
config *rest.Config
namespace string
}
func ConfigPath() string {
path := os.Getenv("KUBECONFIG")
if len(path) > 0 {
return path
}
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, ".kube", "config")
}
return ""
}
func (c *client) ConfigPath() string {
return c.path
}
func (c *client) Config() *rest.Config {
return c.config
}
func (c *client) Namespace() string {
return c.namespace
}
func (c *client) ExportConfig(path string) error {
source, err := os.Open(c.path)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(path)
if err != nil {
return err
}
defer destination.Close()
if _, err := io.Copy(destination, source); err != nil {
return err
}
return nil
}