This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 561
/
pod.go
304 lines (281 loc) · 8.14 KB
/
pod.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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package pod
import (
"context"
"encoding/json"
"fmt"
"log"
"os/exec"
"regexp"
"time"
)
// List is a container that holds all pods returned from doing a kubectl get pods
type List struct {
Pods []Pod `json:"items"`
}
// Pod is used to parse data from kubectl get pods
type Pod struct {
Metadata Metadata `json:"metadata"`
Spec Spec `json:"spec"`
Status Status `json:"status"`
}
// Metadata holds information like name, createdat, labels, and namespace
type Metadata struct {
CreatedAt time.Time `json:"creationTimestamp"`
Labels map[string]string `json:"labels"`
Name string `json:"name"`
Namespace string `json:"namespace"`
}
// Spec holds information like containers
type Spec struct {
Containers []Container `json:"containers"`
}
// Container holds information like image and ports
type Container struct {
Image string `json:"image"`
Ports []Port `json:"ports"`
}
// Port represents a container port definition
type Port struct {
ContainerPort int `json:"containerPort"`
HostPort int `json:"hostPort"`
}
// Status holds information like hostIP and phase
type Status struct {
HostIP string `json:"hostIP"`
Phase string `json:"phase"`
PodIP string `json:"podIP"`
StartTime time.Time `json:"startTime"`
}
// GetAll will return all pods in a given namespace
func GetAll(namespace string) (*List, error) {
out, err := exec.Command("kubectl", "get", "pods", "-n", namespace, "-o", "json").CombinedOutput()
if err != nil {
return nil, err
}
pl := List{}
err = json.Unmarshal(out, &pl)
if err != nil {
log.Printf("Error unmarshalling nodes json:%s\n", err)
return nil, err
}
return &pl, nil
}
// Get will return a pod with a given name and namespace
func Get(podName, namespace string) (*Pod, error) {
out, err := exec.Command("kubectl", "get", "pods", podName, "-n", namespace, "-o", "json").CombinedOutput()
if err != nil {
return nil, err
}
p := Pod{}
err = json.Unmarshal(out, &p)
if err != nil {
log.Printf("Error unmarshalling nodes json:%s\n", err)
return nil, err
}
return &p, nil
}
// GetAllByPrefix will return all pods in a given namespace that match a prefix
func GetAllByPrefix(prefix, namespace string) ([]Pod, error) {
pl, err := GetAll(namespace)
if err != nil {
return nil, err
}
pods := []Pod{}
for _, p := range pl.Pods {
matched, err := regexp.MatchString(prefix+"-.*", p.Metadata.Name)
if err != nil {
log.Printf("Error trying to match pod name:%s\n", err)
return nil, err
}
if matched {
pods = append(pods, p)
}
}
return pods, nil
}
// AreAllPodsRunning will return true if all pods are in a Running State
func AreAllPodsRunning(podPrefix, namespace string) (bool, error) {
pl, err := GetAll(namespace)
if err != nil {
return false, err
}
var status []bool
for _, pod := range pl.Pods {
matched, err := regexp.MatchString(podPrefix+"-.*", pod.Metadata.Name)
if err != nil {
log.Printf("Error trying to match pod name:%s\n", err)
return false, err
}
if matched {
if pod.Status.Phase != "Running" {
status = append(status, false)
} else {
status = append(status, true)
}
}
}
if len(status) == 0 {
return false, nil
}
for _, s := range status {
if s == false {
return false, nil
}
}
return true, nil
}
// WaitOnReady will block until all nodes are in ready state
func WaitOnReady(podPrefix, namespace string, sleep, duration time.Duration) (bool, error) {
readyCh := make(chan bool, 1)
errCh := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
errCh <- fmt.Errorf("Timeout exceeded (%s) while waiting for Pods (%s) to become ready in namespace (%s)", duration.String(), podPrefix, namespace)
default:
ready, _ := AreAllPodsRunning(podPrefix, namespace)
if ready == true {
readyCh <- true
} else {
time.Sleep(sleep)
}
}
}
}()
for {
select {
case err := <-errCh:
return false, err
case ready := <-readyCh:
return ready, nil
}
}
}
// Exec will execute the given command in the pod
func (p *Pod) Exec(cmd ...string) ([]byte, error) {
execCmd := []string{"exec", p.Metadata.Name, "-n", p.Metadata.Namespace}
for _, s := range cmd {
execCmd = append(execCmd, s)
}
out, err := exec.Command("kubectl", execCmd...).CombinedOutput()
if err != nil {
log.Printf("Error trying to run 'kubectl exec':%s\n", string(out))
log.Printf("Command:kubectl exec %s -n %s %s \n", p.Metadata.Name, p.Metadata.Namespace, cmd)
return nil, err
}
return out, nil
}
// CheckLinuxOutboundConnection will keep retrying the check if an error is received until the timeout occurs or it passes. This helps us when DNS may not be available for some time after a pod starts.
func (p *Pod) CheckLinuxOutboundConnection(sleep, duration time.Duration) (bool, error) {
exp, err := regexp.Compile("200 OK")
if err != nil {
log.Printf("Error while trying to create regex for linux outbound check:%s\n", err)
return false, err
}
readyCh := make(chan bool, 1)
errCh := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
errCh <- fmt.Errorf("Timeout exceeded (%s) while waiting for Pod (%s) to check outbound internet connection", duration.String(), p.Metadata.Name)
default:
_, err := p.Exec("--", "/usr/bin/apt", "update")
if err != nil {
break
}
_, err = p.Exec("--", "/usr/bin/apt", "install", "-y", "curl")
if err != nil {
break
}
out, err := p.Exec("--", "curl", "-I", "http://www.bing.com")
if err == nil {
matched := exp.MatchString(string(out))
if matched {
readyCh <- true
} else {
readyCh <- false
}
} else {
log.Printf("Error:%s\n", err)
log.Printf("Out:%s\n", out)
}
}
}
}()
for {
select {
case err := <-errCh:
return false, err
case ready := <-readyCh:
return ready, nil
}
}
}
// CheckWindowsOutboundConnection will keep retrying the check if an error is received until the timeout occurs or it passes. This helps us when DNS may not be available for some time after a pod starts.
func (p *Pod) CheckWindowsOutboundConnection(sleep, duration time.Duration) (bool, error) {
exp, err := regexp.Compile("(StatusCode\\s*:\\s*200)")
if err != nil {
log.Printf("Error while trying to create regex for windows outbound check:%s\n", err)
return false, err
}
readyCh := make(chan bool, 1)
errCh := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
errCh <- fmt.Errorf("Timeout exceeded (%s) while waiting for Pod (%s) to check outbound internet connection", duration.String(), p.Metadata.Name)
default:
out, err := p.Exec("--", "powershell", "iwr", "-UseBasicParsing", "-TimeoutSec", "60", "www.bing.com")
if err == nil {
matched := exp.MatchString(string(out))
if matched {
readyCh <- true
} else {
readyCh <- false
}
} else {
log.Printf("Error:%s\n", err)
log.Printf("Out:%s\n", out)
}
}
}
}()
for {
select {
case err := <-errCh:
return false, err
case ready := <-readyCh:
return ready, nil
}
}
}
// ValidateHostPort will attempt to run curl against the POD's hostIP and hostPort
func (p *Pod) ValidateHostPort(check string, attempts int, sleep time.Duration, master, sshKeyPath string) bool {
hostIP := p.Status.HostIP
if len(p.Spec.Containers) == 0 || len(p.Spec.Containers[0].Ports) == 0 {
log.Printf("Unexpectd POD container spec: %v. Should have hostPort.\n", p.Spec)
return false
}
hostPort := p.Spec.Containers[0].Ports[0].HostPort
url := fmt.Sprintf("http://%s:%d", hostIP, hostPort)
curlCMD := fmt.Sprintf("curl --max-time 60 %s", url)
for i := 0; i < attempts; i++ {
resp, err := exec.Command("ssh", "-i", sshKeyPath, "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", master, curlCMD).CombinedOutput()
if err == nil {
matched, _ := regexp.MatchString(check, string(resp))
if matched == true {
return true
}
}
}
return false
}