-
Notifications
You must be signed in to change notification settings - Fork 7
/
kubernetes_tools.go
265 lines (232 loc) · 7.91 KB
/
kubernetes_tools.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
// Package maestro implements Maestro's methods.
package maestro
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/Azure/go-autorest/autorest/to"
"helm.sh/helm/v3/pkg/action"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/flomesh-io/fsm/pkg/cli"
)
// GetPodLogs returns pod logs.
func GetPodLogs(kubeClient kubernetes.Interface, namespace string, podName string, containerName string, timeSince time.Duration) string {
sinceTime := metav1.NewTime(time.Now().Add(-timeSince))
options := &corev1.PodLogOptions{
Container: containerName,
Follow: false,
SinceTime: &sinceTime,
}
logStream, err := kubeClient.CoreV1().Pods(namespace).GetLogs(podName, options).Stream(context.Background())
if err != nil {
fmt.Println("Error in opening stream: ", err)
os.Exit(1)
}
//nolint: errcheck
//#nosec G307
defer logStream.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(logStream)
if err != nil {
log.Error().Err(err).Msg("Error reading from pod logs stream")
}
return buf.String()
}
// DeleteNamespaces deletes the namespaces listed and any Helm releases within
// them.
func DeleteNamespaces(client *kubernetes.Clientset, namespaces ...string) {
env := cli.New()
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: to.Int64Ptr(0),
}
for _, ns := range namespaces {
// Delete all helm releases in the namespace
helmCfg := &action.Configuration{}
if err := helmCfg.Init(env.RESTClientGetter(), ns, "secret", log.Info().Msgf); err != nil {
log.Warn().Err(err).Msg("Failed to initialize Helm, skipping release cleanup")
} else {
uninstall := action.NewUninstall(helmCfg)
list := action.NewList(helmCfg)
list.All = true
releases, err := list.Run()
if err != nil {
log.Warn().Err(err).Msgf("Failed to list releases in namespace %s, skipping release cleanup", ns)
} else {
for _, release := range releases {
if _, err := uninstall.Run(release.Name); err != nil {
log.Warn().Err(err).Msgf("Failed to uninstall release %s in namespace %s", release.Name, ns)
}
}
}
}
if err := client.CoreV1().Namespaces().Delete(context.Background(), ns, deleteOptions); err != nil {
log.Error().Err(err).Msgf("Error deleting namespace %s", ns)
continue
}
log.Info().Msgf("Deleted namespace: %s", ns)
}
}
// DeleteWebhookConfiguration deletes the mutatingwebhookconfiguration by name
func DeleteWebhookConfiguration(client *kubernetes.Clientset, webhookConfigName string) {
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: to.Int64Ptr(0),
}
_, err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Get(context.Background(), webhookConfigName, metav1.GetOptions{})
if err != nil {
log.Error().Err(err).Msgf("Error getting mutatingwebhookconfiguration %s", webhookConfigName)
return
}
if err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.Background(), webhookConfigName, deleteOptions); err != nil {
log.Error().Err(err).Msgf("Error deleting mutatingwebhookconfiguration %s", webhookConfigName)
} else {
log.Info().Msgf("Deleted mutatingwebhookconfiguration: %s", webhookConfigName)
}
}
// GetPodName returns the name of the pod for the given selector.
func GetPodName(kubeClient kubernetes.Interface, namespace, selector string) (string, error) {
podList, err := kubeClient.CoreV1().Pods(namespace).List(context.Background(), metav1.ListOptions{LabelSelector: selector})
if err != nil {
return "", err
}
if len(podList.Items) == 0 {
log.Error().Msgf("Zero pods found for selector %s in namespace %s", selector, namespace)
return "", errNoPodsFound
}
sort.SliceStable(podList.Items, func(i, j int) bool {
p1 := podList.Items[i].CreationTimestamp.UnixNano()
p2 := podList.Items[j].CreationTimestamp.UnixNano()
return p1 > p2
})
return podList.Items[0].Name, nil
}
// SearchLogsForSuccess tails logs until success enum is found.
// The pod/container we are observing is responsible for sending the SUCCESS/FAIL token based on local heuristic.
func SearchLogsForSuccess(kubeClient kubernetes.Interface, namespace string, podName string, containerName string, totalWait time.Duration, result chan string, successToken, failureToken string) {
sinceTime := metav1.NewTime(time.Now().Add(-PollLogsFromTimeSince))
options := &corev1.PodLogOptions{
Container: containerName,
Follow: true,
SinceTime: &sinceTime,
}
logStream, err := kubeClient.CoreV1().Pods(namespace).GetLogs(podName, options).Stream(context.Background())
if err != nil {
fmt.Println("Error in opening stream: ", err)
os.Exit(1)
}
go func() {
defer close(result)
//nolint: errcheck
//#nosec G307
defer logStream.Close()
r := bufio.NewReader(logStream)
type readResult struct {
line string
err error
}
readRes := make(chan readResult)
go func() {
for {
line, err := r.ReadString('\n')
readRes <- readResult{line, err}
}
}()
timeout := time.After(totalWait)
for {
select {
case <-timeout:
log.Error().Err(err).Msgf("Timed out trying to read from pod %s/%s", namespace, podName)
result <- TestsTimedOut
case readres := <-readRes:
line := readres.line
err := readres.err
switch {
// If we detect EOF before success - this must have been a failure
case err == io.EOF:
log.Error().Err(err).Msgf("EOF reading from pod %s/%s", namespace, podName)
result <- TestsFailed
return
// Any other error fails the test
case err != nil:
log.Error().Err(err).Msgf("Error reading from pod %s/%s", namespace, podName)
result <- TestsFailed
return
// Finally search for SUCCESS or FAILURE
// The container itself has the heuristic on when to emit these.
default:
if strings.Contains(line, successToken) {
log.Info().Msgf("[%s] Found %s", containerName, successToken)
result <- TestsPassed
return
}
if strings.Contains(line, failureToken) {
log.Info().Msgf("[%s] Found %s", containerName, failureToken)
result <- TestsFailed
return
}
}
}
}
}()
}
// GetKubernetesClient returns a k8s client.
func GetKubernetesClient() *kubernetes.Clientset {
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{},
)
kubeConfig, err := clientConfig.ClientConfig()
if err != nil {
fmt.Println("error loading kube config:", err)
os.Exit(1)
}
clientset, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
fmt.Println("error in getting access to K8S")
os.Exit(1)
}
return clientset
}
// WaitForPodToBeReady waits for a pod by selector to be ready.
func WaitForPodToBeReady(kubeClient kubernetes.Interface, totalWait time.Duration, namespace, selector string, wg *sync.WaitGroup) {
startedWaiting := time.Now()
for {
if time.Since(startedWaiting) >= totalWait {
log.Error().Msgf("Waited for pod %q to become ready for %+v; Didn't happen", selector, totalWait)
os.Exit(1)
}
podName, err := GetPodName(kubeClient, namespace, selector)
if err != nil {
log.Error().Err(err).Msgf("Error getting Pod w/ selector %q", selector)
time.Sleep(WaitForPod)
// Pod might not be up yet, try again
continue
}
pod, err := kubeClient.CoreV1().Pods(namespace).Get(context.Background(), podName, metav1.GetOptions{})
if err != nil {
log.Error().Err(err).Msgf("Error getting pod %s/%s", namespace, podName)
os.Exit(1)
}
for _, condition := range pod.Status.Conditions {
if condition.Type != corev1.PodReady {
continue
}
if condition.Status == corev1.ConditionTrue {
log.Info().Msgf("Pod %q is ready!", podName)
wg.Done()
return
}
fmt.Printf("Pod %s/%s is still initializing; Waiting %+v (%+v/%+v)\n", namespace, podName, WaitForPod, time.Since(startedWaiting), totalWait)
time.Sleep(WaitForPod)
}
}
}