-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkubectl.go
More file actions
254 lines (227 loc) · 5.89 KB
/
kubectl.go
File metadata and controls
254 lines (227 loc) · 5.89 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
var (
tempKubeconfigPath string
)
func withKubeConfig(noTempKubeConfig bool, f func() error) error {
if !noTempKubeConfig {
realKubeconfigPath := os.Getenv("KUBECONFIG")
if !fileExists(realKubeconfigPath) {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("get user home dir: %w", err)
}
realKubeconfigPath = filepath.Join(userHomeDir, ".kube", "config")
if !fileExists(realKubeconfigPath) {
return fmt.Errorf("no local kubeconfig file found. try using the --no-temp-kubeconfig flag")
}
}
tmpFile, err := os.CreateTemp(os.TempDir(), "testpod-kubeconfig-*.yaml")
if err != nil {
return fmt.Errorf("create temp kubeconfig: %w", err)
}
tmpFile.Close()
tempKubeconfigPath = tmpFile.Name()
fmt.Println("clone kubeconfig", realKubeconfigPath, "to", tempKubeconfigPath)
data, err := os.ReadFile(realKubeconfigPath)
if err != nil {
return fmt.Errorf("read kubeconfig: %w", err)
}
if err := os.WriteFile(tempKubeconfigPath, data, os.ModePerm); err != nil {
return fmt.Errorf("write temp kubeconfig: %w", err)
}
defer func() {
if err := os.Remove(tempKubeconfigPath); err != nil {
fmt.Println("WARN: failed to delete temp kubeconfig file", tempKubeconfigPath+":", err)
} else {
fmt.Println("temp kubeconfig file", tempKubeconfigPath, "deleted")
}
}()
}
return f()
}
func fileExists(path string) bool {
if len(path) == 0 {
return false
}
fi, err := os.Stat(path)
return err == nil && !fi.IsDir()
}
func kubectlListPods(matchLabels map[string]string) error {
args := []string{"get", "pods", "-L", "app.kubernetes.io/managed-by"}
for k, v := range matchLabels {
args = append(args, "-l", k+"="+v)
}
return kubectl(options{
Args: args,
})
}
func kubectlGetPodNames(matchLabels map[string]string) ([]string, error) {
var obj struct {
Items []struct {
Metadata struct {
Name string `json:"name"`
} `json:"metadata"`
} `json:"items"`
}
args := []string{"get", "pods", "-o", "json"}
for k, v := range matchLabels {
args = append(args, "-l", k+"="+v)
}
if err := kubectl(options{
Args: args,
ParseJSON: &obj,
}); err != nil {
return nil, err
}
podNames := make([]string, 0)
for _, item := range obj.Items {
podNames = append(podNames, item.Metadata.Name)
}
return podNames, nil
}
func kubectlGetWorkerNodes() ([]Node, error) {
var obj struct {
Items []struct {
Metadata struct {
Name string `json:"name"`
CreationTimestamp time.Time `json:"creationTimestamp"`
} `json:"metadata"`
Spec struct {
Taints []struct {
Key string `json:"key"`
} `json:"taints"`
} `json:"spec"`
Status struct {
NodeInfo struct {
KubeletVersion string `json:"kubeletVersion"`
} `json:"nodeInfo"`
} `json:"status"`
} `json:"items"`
}
args := []string{"get", "nodes", "-o", "json"}
if err := kubectl(options{
Args: args,
ParseJSON: &obj,
}); err != nil {
return nil, err
}
nodes := make([]Node, 0)
for _, node := range obj.Items {
isControlPlane := false
for _, t := range node.Spec.Taints {
if t.Key == "node-role.kubernetes.io/control-plane" {
isControlPlane = true
break
}
}
if !isControlPlane {
nodes = append(nodes, Node{
Name: node.Metadata.Name,
Age: time.Since(node.Metadata.CreationTimestamp),
Version: node.Status.NodeInfo.KubeletVersion,
})
}
}
return nodes, nil
}
func kubectlGetNodeLabels(nodeName string, ignoredLabels map[string]bool) (map[string]string, error) {
var obj struct {
Metadata struct {
Labels map[string]string `json:"labels"`
} `json:"metadata"`
}
args := []string{"get", "node", nodeName, "-o", "json"}
if err := kubectl(options{
Args: args,
ParseJSON: &obj,
}); err != nil {
return nil, err
}
nodeLabels := make(map[string]string)
for k, v := range obj.Metadata.Labels {
if !ignoredLabels[k] {
nodeLabels[k] = v
}
}
return nodeLabels, nil
}
func kubectlApply(manifestData string) error {
return kubectl(options{
Args: []string{"apply", "-f", "-"},
StdIn: manifestData,
})
}
func kubectlWaitForPod(podName string) error {
return kubectl(options{
Args: []string{"wait", "--for=condition=ready", "--timeout=30s", "pod/" + podName},
})
}
func kubectlExec(podName string, shell string) error {
return kubectl(options{
Args: []string{"exec", "-it", podName, "--", shell},
PipeAll: true,
})
}
func kubectlDeletePod(podName string) error {
return kubectl(options{
Args: []string{"delete", "--wait=false", "pod", podName},
})
}
func kubectlDeleteNetworkPolicy(name string) error {
return kubectl(options{
Args: []string{"delete", "--wait=false", "netpol", name},
})
}
type options struct {
Args []string
PipeAll bool
Silent bool
StdIn string
ParseJSON interface{}
}
func kubectl(options options) error {
_, err := kubectlGetOutput(options)
return err
}
func kubectlGetOutput(options options) (string, error) {
if options.PipeAll && len(options.StdIn) > 0 {
return "", fmt.Errorf("cannot set PipeAll and StdIn at the same time")
}
if options.PipeAll && options.ParseJSON != nil {
return "", fmt.Errorf("cannot set PipeAll and ParseJSON at the same time")
}
cmd := exec.Command("kubectl", options.Args...)
if len(tempKubeconfigPath) > 0 {
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "KUBECONFIG="+tempKubeconfigPath)
}
if options.PipeAll {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return "", cmd.Run()
}
if len(options.StdIn) > 0 {
cmd.Stdin = strings.NewReader(options.StdIn)
}
out, err := cmd.CombinedOutput()
if options.ParseJSON != nil {
if err := json.Unmarshal(out, options.ParseJSON); err != nil {
return "", fmt.Errorf("parse json: %w", err)
}
} else {
if !options.Silent {
fmt.Println(strings.TrimSpace(string(out)))
}
}
return string(out), err
}