-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
252 lines (218 loc) · 9.35 KB
/
main.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
package main
import (
"fmt"
"strconv"
"time"
v1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
deploymentsDeleted = 0
ingressesDeleted = 0
servicesDeleted = 0
hpasDeleted = 0
)
type bin int
func (b bin) String() string {
return fmt.Sprintf("%b", b)
}
func Find(slice []string, val string) (int, bool) {
for i, item := range slice {
if item == val {
return i, true
}
}
return -1, false
}
// Determines which delete function to use
type DeleteFunc func(clientset *kubernetes.Clientset, deployment *v1.Deployment, restarts int, restartThreshold int) (bool, error)
// Pod is in a CrashLoopBackOff state
// Check if restart number meets or exceeds the restart threshold
// The restart threshold will be 0 if not specified in the config, so have to handle that case
func DeleteCrash(clientset *kubernetes.Clientset, deployment *v1.Deployment, restarts int, restartThreshold int) (bool, error) {
if restartThreshold > 0 && restarts >= restartThreshold {
return DeleteGeneric(clientset, deployment, restarts, restartThreshold)
} else {
fmt.Printf("%s/%s is in a CrashLoopBackOff state, but doesn't meet the restart threshold. "+
"Restarts/Threshold = %v/%v\n", deployment.Namespace, deployment.Name, restarts, restartThreshold)
return false, nil
}
}
// Pod is in a state defined in config.yaml
func DeleteGeneric(clientset *kubernetes.Clientset, deployment *v1.Deployment, restarts int, restartThreshold int) (bool, error) {
policy := metav1.DeletePropagationForeground
gracePeriodSeconds := int64(0)
fmt.Printf("About to delete %s/%s and its associated resources.\n", deployment.Namespace, deployment.Name)
err := clientset.AppsV1().Deployments(deployment.Namespace).Delete(deployment.Name, &metav1.DeleteOptions{PropagationPolicy: &policy, GracePeriodSeconds: &gracePeriodSeconds})
if err != nil {
fmt.Printf("%s/%s, Error: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
deploymentsDeleted++
_, err = DeleteLeftoverResources(clientset, deployment)
if err != nil {
fmt.Printf("%s/%s, Error: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
fmt.Printf("Deleted %s/%s and its associated resources.\n", deployment.Namespace, deployment.Name)
return true, nil
}
// Delete--if desired--Ingresses, Services, and HorizontalPodAutoscalers
func DeleteLeftoverResources(clientset *kubernetes.Clientset, deployment *v1.Deployment) (bool, error) {
var kleanerConfig = ConfigObj
if kleanerConfig.DeleteIngresses {
_, err := DeleteIngress(clientset, deployment)
if err != nil {
fmt.Printf("%s/%s, Error calling DeleteIngress: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
ingressesDeleted++
}
if kleanerConfig.DeleteServices {
_, err := DeleteService(clientset, deployment)
if err != nil {
fmt.Printf("%s/%s, Error calling DeleteService: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
servicesDeleted++
}
if kleanerConfig.DeleteHpas {
_, err := DeleteHpa(clientset, deployment)
if err != nil {
fmt.Printf("%s/%s, Error calling DeleteHpa: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
hpasDeleted++
}
return true, nil
}
// Delete Ingress resource associated with Deployment
func DeleteIngress(clientset *kubernetes.Clientset, deployment *v1.Deployment) (bool, error) {
policy := metav1.DeletePropagationForeground
gracePeriodSeconds := int64(0)
fmt.Printf("About to delete the ingress of %s/%s.\n", deployment.Namespace, deployment.Name)
err := clientset.ExtensionsV1beta1().Ingresses(deployment.Namespace).Delete(deployment.Name, &metav1.DeleteOptions{PropagationPolicy: &policy, GracePeriodSeconds: &gracePeriodSeconds})
if err != nil {
fmt.Printf("%s/%s, Error deleting ingress: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
fmt.Printf("Deleted the ingress of %s/%s.\n", deployment.Namespace, deployment.Name)
return true, nil
}
// Delete Service resource associated with Deployment
func DeleteService(clientset *kubernetes.Clientset, deployment *v1.Deployment) (bool, error) {
policy := metav1.DeletePropagationForeground
gracePeriodSeconds := int64(0)
fmt.Printf("About to delete the service of %s/%s.\n", deployment.Namespace, deployment.Name)
err := clientset.CoreV1().Services(deployment.Namespace).Delete(deployment.Name, &metav1.DeleteOptions{PropagationPolicy: &policy, GracePeriodSeconds: &gracePeriodSeconds})
if err != nil {
fmt.Printf("%s/%s, Error deleting service: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
fmt.Printf("Deleted the service of %s/%s.\n", deployment.Namespace, deployment.Name)
return true, nil
}
// Delete HorizontalPodAutoscaler resource associated with Deployment
func DeleteHpa(clientset *kubernetes.Clientset, deployment *v1.Deployment) (bool, error) {
policy := metav1.DeletePropagationForeground
gracePeriodSeconds := int64(0)
fmt.Printf("About to delete the HPA of %s/%s.\n", deployment.Namespace, deployment.Name)
err := clientset.AutoscalingV1().HorizontalPodAutoscalers(deployment.Namespace).Delete(deployment.Name, &metav1.DeleteOptions{PropagationPolicy: &policy, GracePeriodSeconds: &gracePeriodSeconds})
if err != nil {
fmt.Printf("%s/%s, Error deleting HPA: %s \n", deployment.Namespace, deployment.Name, err.Error())
return false, err
}
fmt.Printf("Deleted the HPA of %s/%s.\n", deployment.Namespace, deployment.Name)
return true, nil
}
func main() {
var kleanerConfig = ConfigObj // initialize the config, from yaml or environment variables
var waitingReasons = make(map[string]SweeperConfigDetails) // create the map that will hold the reasons and the config object
for _, conf := range kleanerConfig.Reasons { // fill the map
waitingReasons[conf.Reason] = conf
}
config, err := rest.InClusterConfig() // fail fast if not in the cluster
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
fmt.Println("\n+============ Beginning the sweep. ============+")
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{}) // get a list of pods for all namespaces
if err != nil {
panic(err.Error())
}
for _, pod := range pods.Items {
StatusLoop:
for _, status := range pod.Status.ContainerStatuses {
_, found := Find(kleanerConfig.ExcludedNamespaces, pod.Namespace) // CHECK #1: Deployment age
if found {
fmt.Println("Pod's namespace is excluded from deletion.")
continue
}
rs, err := clientset.AppsV1().ReplicaSets(pod.Namespace).Get(pod.OwnerReferences[0].Name, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error retrieving ReplicaSets. Error: %s\n", err.Error())
continue StatusLoop
}
deploy, err := clientset.AppsV1().Deployments(pod.Namespace).Get(rs.OwnerReferences[0].Name, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error retrieving Deployments. Error: %s\n", err.Error())
continue StatusLoop
}
if deploy != nil && deploy.Name != "" {
fmt.Println(deploy.GetNamespace() + "/" + deploy.GetName())
fmt.Println(deploy.GetCreationTimestamp())
if pod.GetCreationTimestamp().AddDate(0, 0, kleanerConfig.DayLimit).Before(time.Now()) {
fmt.Println("I found an old deployment past " + strconv.Itoa(kleanerConfig.DayLimit) + " days!")
_, err = DeleteGeneric(clientset, deploy, int(status.RestartCount), 0)
}
}
waiting := status.State.Waiting // CHECK #2: Pod "Waiting" state
if waiting != nil { // There is a bad pod state
reason := waiting.Reason
if SweeperConfigDetails, ok := waitingReasons[reason]; ok {
fmt.Printf("Waiting reason match. %s/%s has a waiting reason of: %s\n", pod.Namespace,
pod.OwnerReferences[0].Name, reason)
rs, err := clientset.AppsV1().ReplicaSets(pod.Namespace).Get(pod.OwnerReferences[0].Name, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error retrieving ReplicaSets. Error: %s\n", err.Error())
continue StatusLoop
}
if rs.OwnerReferences != nil {
deploy, err := clientset.AppsV1().Deployments(pod.Namespace).Get(rs.OwnerReferences[0].Name, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error retrieving Deployments. Error: %s\n", err.Error())
continue StatusLoop
}
if deploy != nil && deploy.Name != "" { // indicates something to be deleted
_, err = SweeperConfigDetails.DeleteFunction(clientset, deploy, int(status.RestartCount), SweeperConfigDetails.RestartThreshold)
if err != nil {
fmt.Printf("Error deleting Deployment. Error: %s\n", err.Error())
continue StatusLoop
}
} else {
fmt.Println("No deployment found.")
}
} else {
fmt.Println("No replica set owner reference.")
}
}
}
}
}
fmt.Println("\n+============ KUBESWEEPER SUMMARY ============+")
fmt.Println("\nNumber of deployments, replica sets, and pods deleted: " + strconv.Itoa(deploymentsDeleted))
fmt.Println("\nNumber of ingresses deleted: " + strconv.Itoa(ingressesDeleted))
fmt.Println("\nNumber of services deleted: " + strconv.Itoa(servicesDeleted))
fmt.Println("\nNumber of HPAs deleted: " + strconv.Itoa(hpasDeleted))
fmt.Println("\n+==============================================+")
deploymentsDeleted = 0
ingressesDeleted = 0
servicesDeleted = 0
hpasDeleted = 0
}