/
namespace_controller.go
453 lines (385 loc) · 13.9 KB
/
namespace_controller.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"os"
"strings"
"time"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/builder"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/watch"
"github.com/go-logr/logr"
"github.com/minio/madmin-go/v3"
v1 "github.com/labring/sealos/controllers/account/api/v1"
objectstoragev1 "github/labring/sealos/controllers/objectstorage/api/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// NamespaceReconciler reconciles a Namespace object
type NamespaceReconciler struct {
Client client.WithWatch
Log logr.Logger
Scheme *runtime.Scheme
OSAdminClient *madmin.AdminClient
OSNamespace string
OSAdminSecret string
InternalEndpoint string
}
const (
DebtLimit0Name = "debt-limit0"
OSAccessKey = "CONSOLE_ACCESS_KEY"
OSSecretKey = "CONSOLE_SECRET_KEY"
Disabled = "disabled"
Enabled = "enabled"
OSInternalEndpointEnv = "OSInternalEndpoint"
OSNamespace = "OSNamespace"
OSAdminSecret = "OSAdminSecret"
)
//+kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=namespaces/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=core,resources=namespaces/finalizers,verbs=update
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Namespace object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.11.2/pkg/reconcile
func (r *NamespaceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := r.Log.WithValues("Namespace", req.Namespace, "Name", req.NamespacedName)
ns := corev1.Namespace{}
if err := r.Client.Get(ctx, req.NamespacedName, &ns); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
debtStatus, ok := ns.Annotations[v1.DebtNamespaceAnnoStatusKey]
if !ok {
logger.Error(fmt.Errorf("no debt status"), "no debt status")
return ctrl.Result{}, nil
}
logger.Info("debt status", "status", debtStatus)
switch debtStatus {
case v1.SuspendDebtNamespaceAnnoStatus:
logger.Info("suspend namespace resources")
if err := r.SuspendUserResource(ctx, req.NamespacedName.Name); err != nil {
logger.Error(err, "suspend namespace resources failed")
return ctrl.Result{}, err
}
case v1.ResumeDebtNamespaceAnnoStatus:
logger.Info("resume namespace resources")
if err := r.ResumeUserResource(ctx, req.NamespacedName.Name); err != nil {
logger.Error(err, "resume namespace resources failed")
return ctrl.Result{}, err
}
ns.Annotations[v1.DebtNamespaceAnnoStatusKey] = v1.NormalDebtNamespaceAnnoStatus
if err := r.Client.Update(ctx, &ns); err != nil {
logger.Error(err, "update namespace status failed")
return ctrl.Result{}, err
}
case v1.NormalDebtNamespaceAnnoStatus:
default:
logger.Error(fmt.Errorf("unknown namespace debt status, change to normal"), "", "debt status", ns.Annotations[v1.DebtNamespaceAnnoStatusKey])
ns.Annotations[v1.DebtNamespaceAnnoStatusKey] = v1.NormalDebtNamespaceAnnoStatus
if err := r.Client.Update(ctx, &ns); err != nil {
logger.Error(err, "update namespace status failed")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
func (r *NamespaceReconciler) SuspendUserResource(ctx context.Context, namespace string) error {
// limit0 resource quota
// suspend pod: deploy pod && clone unmanaged pod
// delete infra cr
pipelines := []func(context.Context, string) error{
r.suspendOrphanPod,
r.limitResourceQuotaCreate,
r.deleteControlledPod,
//TODO how to suspend infra cr or delete infra cr
//r.suspendInfraResources,
r.suspendObjectStorage,
}
for _, fn := range pipelines {
if err := fn(ctx, namespace); err != nil {
return err
}
}
return nil
}
func (r *NamespaceReconciler) ResumeUserResource(ctx context.Context, namespace string) error {
// delete limit0 resource quota
// resume pod
pipelines := []func(context.Context, string) error{
r.limitResourceQuotaDelete,
r.resumePod,
r.resumeObjectStorage,
}
for _, fn := range pipelines {
if err := fn(ctx, namespace); err != nil {
return err
}
}
return nil
}
func (r *NamespaceReconciler) limitResourceQuotaCreate(ctx context.Context, namespace string) error {
limitQuota := GetLimit0ResourceQuota(namespace)
_, err := ctrl.CreateOrUpdate(ctx, r.Client, limitQuota, func() error {
return nil
})
return err
}
func (r *NamespaceReconciler) limitResourceQuotaDelete(ctx context.Context, namespace string) error {
limitQuota := GetLimit0ResourceQuota(namespace)
err := r.Client.Delete(ctx, limitQuota)
return client.IgnoreNotFound(err)
}
func GetLimit0ResourceQuota(namespace string) *corev1.ResourceQuota {
quota := corev1.ResourceQuota{}
quota.Name = "debt-limit0"
quota.Namespace = namespace
quota.Spec.Hard = corev1.ResourceList{
corev1.ResourceLimitsCPU: resource.MustParse("0"),
corev1.ResourceLimitsMemory: resource.MustParse("0"),
corev1.ResourceRequestsStorage: resource.MustParse("0"),
}
return "a
}
func (r *NamespaceReconciler) suspendOrphanPod(ctx context.Context, namespace string) error {
podList := corev1.PodList{}
if err := r.Client.List(ctx, &podList, client.InNamespace(namespace)); err != nil {
return err
}
for _, pod := range podList.Items {
if pod.Spec.SchedulerName == v1.DebtSchedulerName || len(pod.ObjectMeta.OwnerReferences) > 0 {
continue
}
/*Orphan pod is backed up separately*/
clone := pod.DeepCopy()
// We won't be able to create the object with the same resource version
clone.ObjectMeta.ResourceVersion = ""
// Remove assigned node to avoid scheduling
clone.Spec.NodeName = ""
// Reset status, not needed as its ignored but nice
clone.Status = corev1.PodStatus{}
// Assign our own scheduler to avoid the default scheduler interfer with the workload
clone.Spec.SchedulerName = v1.DebtSchedulerName
if clone.Annotations == nil {
clone.Annotations = make(map[string]string)
}
clone.Annotations[v1.PreviousSchedulerName] = pod.Spec.SchedulerName
err := r.recreatePod(ctx, pod, clone)
if err != nil {
return fmt.Errorf("recrete unowned pod `%s` failed: %w", pod.Name, err)
}
}
return nil
}
func (r *NamespaceReconciler) deleteControlledPod(ctx context.Context, namespace string) error {
podList := corev1.PodList{}
if err := r.Client.List(ctx, &podList, client.InNamespace(namespace)); err != nil {
return err
}
for _, pod := range podList.Items {
if pod.Spec.SchedulerName == v1.DebtSchedulerName || len(pod.ObjectMeta.OwnerReferences) == 0 {
r.Log.Info("skip pod", "pod", pod.Name)
continue
}
r.Log.Info("delete pod", "pod", pod.Name)
err := r.Client.Delete(ctx, &pod)
if err != nil {
return err
}
}
return nil
}
func (r *NamespaceReconciler) resumePod(ctx context.Context, namespace string) error {
var list corev1.PodList
if err := r.Client.List(ctx, &list, client.InNamespace(namespace)); err != nil {
return err
}
deleteCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
for _, pod := range list.Items {
if pod.Status.Phase != v1.PodPhaseSuspended || pod.Spec.SchedulerName != v1.DebtSchedulerName {
continue
}
if len(pod.ObjectMeta.OwnerReferences) > 0 {
err := r.Client.Delete(deleteCtx, &pod)
if err != nil {
return fmt.Errorf("delete pod %s failed: %v", pod.Name, err)
}
} else {
clone := pod.DeepCopy()
// We won't be able to create the object with the same resource version
clone.ObjectMeta.ResourceVersion = ""
// Remove assigned node to avoid scheduling
clone.Spec.NodeName = ""
// Reset status, not needed as its ignored but nice
clone.Status = corev1.PodStatus{}
if scheduler, ok := clone.Annotations[v1.PreviousSchedulerName]; ok {
clone.Spec.SchedulerName = scheduler
delete(clone.Annotations, v1.PreviousSchedulerName)
} else {
clone.Spec.SchedulerName = ""
}
err := r.recreatePod(deleteCtx, pod, clone)
if err != nil {
return fmt.Errorf("recrete unowned pod %s failed: %v", pod.Name, err)
}
}
}
return nil
}
func (r *NamespaceReconciler) recreatePod(ctx context.Context, oldPod corev1.Pod, newPod *corev1.Pod) error {
list := corev1.PodList{}
watcher, err := r.Client.Watch(ctx, &list)
if err != nil {
return fmt.Errorf("failed to start watch stream for pod %s: %w", oldPod.Name, err)
}
ch := watcher.ResultChan()
err = r.Client.Delete(ctx, &oldPod)
if err != nil {
return fmt.Errorf("failed to delete pod %s: %w", oldPod.Name, err)
}
// Wait for delete event before we can attempt create the clone
for event := range ch {
if event.Type == watch.Deleted {
if val, ok := event.Object.(*corev1.Pod); ok && val.Name == oldPod.Name {
err = r.Client.Create(ctx, newPod)
if err != nil {
return fmt.Errorf("failed to recreate pod %s: %w", newPod.Name, err)
}
watcher.Stop()
break
}
}
}
return nil
}
func (r *NamespaceReconciler) suspendObjectStorage(ctx context.Context, namespace string) error {
split := strings.Split(namespace, "-")
user := split[1]
err := r.setOSUserStatus(ctx, user, Disabled)
if err != nil {
r.Log.Error(err, "failed to suspend object storage", "user", user)
return err
}
r.Log.Info("suspend object storage", "user", user)
return nil
}
func (r *NamespaceReconciler) resumeObjectStorage(ctx context.Context, namespace string) error {
split := strings.Split(namespace, "-")
user := split[1]
err := r.setOSUserStatus(ctx, user, Enabled)
if err != nil {
r.Log.Error(err, "failed to resume object storage", "user", user)
return err
}
r.Log.Info("resume object storage", "user", user)
return nil
}
func (r *NamespaceReconciler) setOSUserStatus(ctx context.Context, user string, status string) error {
if r.InternalEndpoint == "" || r.OSNamespace == "" || r.OSAdminSecret == "" {
r.Log.V(1).Info("the endpoint or namespace or admin secret env of object storage is nil")
return nil
}
if r.OSAdminClient == nil {
secret := &corev1.Secret{}
if err := r.Client.Get(ctx, client.ObjectKey{Name: r.OSAdminSecret, Namespace: r.OSNamespace}, secret); err != nil {
r.Log.Error(err, "failed to get secret", "name", r.OSAdminSecret, "namespace", r.OSNamespace)
return err
}
accessKey := string(secret.Data[OSAccessKey])
secretKey := string(secret.Data[OSSecretKey])
oSAdminClient, err := objectstoragev1.NewOSAdminClient(r.InternalEndpoint, accessKey, secretKey)
if err != nil {
r.Log.Error(err, "failed to new object storage admin client")
return err
}
r.OSAdminClient = oSAdminClient
}
users, err := r.OSAdminClient.ListUsers(ctx)
if err != nil {
r.Log.Error(err, "failed to list minio user", "user", user)
return err
}
if _, ok := users[user]; !ok {
return nil
}
err = r.OSAdminClient.SetUserStatus(ctx, user, madmin.AccountStatus(status))
if err != nil {
r.Log.Error(err, "failed to set user status", "user", user, "status", status)
return err
}
return nil
}
//func (r *NamespaceReconciler) deleteInfraResources(ctx context.Context, namespace string) error {
//
// u := unstructured.UnstructuredList{}
// u.SetGroupVersionKind(schema.GroupVersionKind{
// Group: "infra.sealos.io",
// Version: "v1",
// Kind: "infra",
// })
// if err := r.Client.List(ctx, &u, client.InNamespace(namespace)); err != nil {
// return client.IgnoreNotFound(err)
// }
// for _, item := range u.Items {
// r.Log.Info("delete resource", "resource name:", item.GetName(), "get GVK", item.GroupVersionKind())
// if err := r.Client.Delete(ctx, &item); err != nil {
// return client.IgnoreNotFound(err)
// }
// }
// return nil
//}
// SetupWithManager sets up the controller with the Manager.
func (r *NamespaceReconciler) SetupWithManager(mgr ctrl.Manager) error {
r.Log = ctrl.Log.WithName("controllers").WithName("Namespace")
r.OSAdminSecret = os.Getenv(OSAdminSecret)
r.InternalEndpoint = os.Getenv(OSInternalEndpointEnv)
r.OSNamespace = os.Getenv(OSNamespace)
if r.OSAdminSecret == "" || r.InternalEndpoint == "" || r.OSNamespace == "" {
r.Log.V(1).Info("failed to get the endpoint or namespace or admin secret env of object storage")
}
return ctrl.NewControllerManagedBy(mgr).
For(&corev1.Namespace{}, builder.WithPredicates(AnnotationChangedPredicate{})).
Complete(r)
}
type AnnotationChangedPredicate struct {
predicate.Funcs
}
func (AnnotationChangedPredicate) Update(e event.UpdateEvent) bool {
oldObj, _ok1 := e.ObjectOld.(*corev1.Namespace)
newObj, _ok2 := e.ObjectNew.(*corev1.Namespace)
if !_ok1 || !_ok2 || newObj.Annotations == nil {
return false
}
oldStatus := ""
if oldAno := oldObj.Annotations; oldAno != nil {
oldStatus = oldAno[v1.DebtNamespaceAnnoStatusKey]
}
newStatus, ok := newObj.Annotations[v1.DebtNamespaceAnnoStatusKey]
return ok && oldStatus != newStatus
}
func (AnnotationChangedPredicate) Create(e event.CreateEvent) bool {
_, ok := e.Object.GetAnnotations()[v1.DebtNamespaceAnnoStatusKey]
return ok
}