forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean.go
363 lines (308 loc) · 7.98 KB
/
clean.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
The cleanup is designed to get a cluster that was imported to Rancher disconnected
and cleanup some objects
Remove the cattle-system namespace which houses the agent used to talk
to Rancher
Remove Rancher labels, finalizers and annotations from all namespaces
If the cluster was imported to Rancher 2.1 or later cleanup roles, rolebindings,
clusterRoles and clusterRoleBindings
*/
package clean
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/rancher/rancher/pkg/controllers/user/helm"
"github.com/rancher/rancher/pkg/controllers/user/nslabels"
"github.com/sirupsen/logrus"
apierror "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
// List of namespace labels that will be removed
nsLabels = []string{
nslabels.ProjectIDFieldLabel,
}
// List of namespace annotations that will be removed
nsAnnotations = []string{
"cattle.io/status",
"field.cattle.io/creatorId",
"field.cattle.io/resourceQuotaTemplateId",
"lifecycle.cattle.io/create.namespace-auth",
nslabels.ProjectIDFieldLabel,
helm.AppIDsLabel,
}
dryRun bool
)
func Cluster() error {
if os.Getenv("DRY_RUN") == "true" {
dryRun = true
}
if os.Getenv("SLEEP_FIRST") == "true" {
// The sleep allows Rancher server time to finish updating ownerReferences
// and close the connection.
logrus.Info("Starting sleep for 1 min to allow server time to disconnect....")
time.Sleep(time.Duration(1) * time.Minute)
}
logrus.Info("Starting cluster cleanup")
config, err := rest.InClusterConfig()
if err != nil {
return err
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return err
}
var errors []error
err = removeCattleNamespace(client)
if err != nil {
errors = append(errors, err)
}
nsErr := cleanupNamespaces(client)
if len(nsErr) > 0 {
errors = append(errors, nsErr...)
}
crbErr := cleanupClusterRoleBindings(client)
if len(crbErr) > 0 {
errors = append(errors, crbErr...)
}
cbErr := cleanupRoleBindings(client)
if len(cbErr) > 0 {
errors = append(errors, cbErr...)
}
crErr := cleanupClusterRoles(client)
if len(crErr) > 0 {
errors = append(errors, crErr...)
}
rErr := cleanupRoles(client)
if len(rErr) > 0 {
errors = append(errors, rErr...)
}
if len(errors) > 0 {
return processErrors(errors)
}
return deleteJob(client)
}
func removeCattleNamespace(client *kubernetes.Clientset) error {
logrus.Info("Attempting to remove cattle-system namespace")
return tryUpdate(func() error {
ns, err := client.CoreV1().Namespaces().Get("cattle-system", metav1.GetOptions{})
if err != nil {
if apierror.IsNotFound(err) {
return nil
}
return err
}
if len(ns.Finalizers) > 0 {
ns.Finalizers = []string{}
}
logrus.Infof("Updating namespace: %v", ns.Name)
if !dryRun {
ns, err = client.CoreV1().Namespaces().Update(ns)
if err != nil {
return err
}
}
logrus.Infof("Deleting namespace: %v", ns.Name)
if !dryRun {
err = client.CoreV1().Namespaces().Delete("cattle-system", &metav1.DeleteOptions{})
if err != nil {
if !apierror.IsNotFound(err) {
return err
}
}
}
return nil
})
}
var listOptions metav1.ListOptions = metav1.ListOptions{
LabelSelector: "cattle.io/creator=norman",
}
func cleanupNamespaces(client *kubernetes.Clientset) []error {
logrus.Info("Starting cleanup of namespaces")
namespaces, err := client.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
return []error{err}
}
var errs []error
for _, ns := range namespaces.Items {
err = tryUpdate(func() error {
nameSpace, err := client.CoreV1().Namespaces().Get(ns.Name, metav1.GetOptions{})
if err != nil {
if apierror.IsNotFound(err) {
return nil
}
return err
}
var updated bool
// Cleanup finalizers
if len(nameSpace.Finalizers) > 0 {
finalizers := []string{}
for _, finalizer := range nameSpace.Finalizers {
if finalizer != "controller.cattle.io/namespace-auth" {
finalizers = append(finalizers, finalizer)
}
}
if len(nameSpace.Finalizers) != len(finalizers) {
updated = true
nameSpace.Finalizers = finalizers
}
}
// Cleanup labels
for _, label := range nsLabels {
if _, ok := nameSpace.Labels[label]; ok {
updated = ok
delete(nameSpace.Labels, label)
}
}
// Cleanup annotations
for _, anno := range nsAnnotations {
if _, ok := nameSpace.Annotations[anno]; ok {
updated = ok
delete(nameSpace.Annotations, anno)
}
}
if updated {
logrus.Infof("Updating namespace: %v", nameSpace.Name)
if !dryRun {
_, err = client.CoreV1().Namespaces().Update(nameSpace)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
errs = append(errs, err)
}
}
return errs
}
func cleanupClusterRoleBindings(client *kubernetes.Clientset) []error {
logrus.Info("Starting cleanup of clusterRoleBindings")
crbs, err := client.RbacV1().ClusterRoleBindings().List(listOptions)
if err != nil {
return []error{err}
}
var errs []error
for _, crb := range crbs.Items {
logrus.Infof("Deleting clusterRoleBinding: %v", crb.Name)
if !dryRun {
err = client.RbacV1().ClusterRoleBindings().Delete(crb.Name, &metav1.DeleteOptions{})
if err != nil {
errs = append(errs, err)
}
}
}
return errs
}
func cleanupRoleBindings(client *kubernetes.Clientset) []error {
logrus.Info("Starting cleanup of roleBindings")
rbs, err := client.RbacV1().RoleBindings("").List(listOptions)
if err != nil {
return []error{err}
}
var errs []error
for _, rb := range rbs.Items {
logrus.Infof("Deleting roleBinding: %v", rb.Name)
if !dryRun {
err = client.RbacV1().RoleBindings(rb.Namespace).Delete(rb.Name, &metav1.DeleteOptions{})
if err != nil {
errs = append(errs, err)
}
}
}
return errs
}
func cleanupClusterRoles(client *kubernetes.Clientset) []error {
logrus.Info("Starting cleanup of clusterRoles")
crs, err := client.RbacV1().ClusterRoles().List(listOptions)
if err != nil {
return []error{err}
}
var errs []error
for _, cr := range crs.Items {
logrus.Infof("Deleting clusterRole: %v", cr.Name)
if !dryRun {
err = client.RbacV1().ClusterRoles().Delete(cr.Name, &metav1.DeleteOptions{})
if err != nil {
errs = append(errs, err)
}
}
}
return errs
}
func cleanupRoles(client *kubernetes.Clientset) []error {
logrus.Info("Starting cleanup of roles")
rs, err := client.RbacV1().Roles("").List(listOptions)
if err != nil {
return []error{err}
}
var errs []error
for _, r := range rs.Items {
logrus.Infof("Deleting role: %v", r.Name)
if !dryRun {
err = client.RbacV1().Roles(r.Namespace).Delete(r.Name, &metav1.DeleteOptions{})
if err != nil {
errs = append(errs, err)
}
}
}
return errs
}
func deleteJob(client *kubernetes.Clientset) error {
logrus.Info("Starting cleanup of jobs")
jobs, err := client.BatchV1().Jobs("default").List(listOptions)
if err != nil {
return err
}
for _, job := range jobs.Items {
prop := metav1.DeletePropagationBackground
if strings.HasPrefix(job.Name, "cattle-cleanup") {
logrus.Infof("Deleting job: %v", job.Name)
if !dryRun {
err = client.BatchV1().Jobs("default").Delete(job.Name, &metav1.DeleteOptions{
PropagationPolicy: &prop,
})
if err != nil {
return err
}
}
}
}
return nil
}
// tryUpdate runs the input func and if the error returned is a conflict error
// from k8s it will sleep and attempt to run the func again. This is useful
// when attempting to update an object.
func tryUpdate(f func() error) error {
sleepTime := 100
tries := 0
var err error
for tries <= 3 {
err = f()
if err != nil {
if apierror.IsConflict(err) {
time.Sleep(time.Duration(sleepTime) * time.Millisecond)
sleepTime *= 2
tries++
continue
}
return err
}
break
}
return err
}
func processErrors(errs []error) error {
errorString := "Errors: "
for _, err := range errs {
errorString += fmt.Sprintf("%s ", err)
}
return errors.New(errorString)
}