-
Notifications
You must be signed in to change notification settings - Fork 10
/
poddeletion_controller.go
168 lines (142 loc) · 5.71 KB
/
poddeletion_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
/*
Copyright 2023 The KusionStack Authors.
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 poddeletion
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"kusionstack.io/operating/apis/apps/v1alpha1"
appsv1alpha1 "kusionstack.io/operating/apis/apps/v1alpha1"
"kusionstack.io/operating/pkg/controllers/collaset/pvccontrol"
"kusionstack.io/operating/pkg/controllers/utils/expectations"
"kusionstack.io/operating/pkg/controllers/utils/podopslifecycle"
"kusionstack.io/operating/pkg/utils/mixin"
)
const (
controllerName = "poddeletion-controller"
)
// PodDeletionReconciler reconciles and reclaims a Pod object
type PodDeletionReconciler struct {
*mixin.ReconcilerMixin
pvcControl pvccontrol.Interface
}
func Add(mgr ctrl.Manager) error {
return AddToMgr(mgr, NewReconciler(mgr))
}
// NewReconciler returns a new reconcile.Reconciler
func NewReconciler(mgr ctrl.Manager) reconcile.Reconciler {
mixin := mixin.NewReconcilerMixin(controllerName, mgr)
InitExpectations(mixin.Client)
return &PodDeletionReconciler{
ReconcilerMixin: mixin,
pvcControl: pvccontrol.NewRealPvcControl(mixin.Client, mixin.Scheme),
}
}
func AddToMgr(mgr ctrl.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New(controllerName, mgr, controller.Options{
MaxConcurrentReconciles: 5,
Reconciler: r,
})
if err != nil {
return err
}
err = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForObject{}, &PredicateDeletionIndicatedPod{})
if err != nil {
return err
}
return nil
}
// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=core,resources=events,verbs=create;update;patch
// Reconcile aims to delete Pod through PodOpsLifecycle. It will watch Pod with deleting indication label.
// If a Pod is labeled, controller will first trigger a deletion PodOpsLifecycle. If all conditions are satisfied,
// it will then delete Pod.
func (r *PodDeletionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := r.Logger.WithValues("pod", req.String())
instance := &corev1.Pod{}
if err := r.Client.Get(ctx, req.NamespacedName, instance); err != nil {
if !errors.IsNotFound(err) {
logger.Error(err, "failed to find pod")
return reconcile.Result{}, err
}
logger.V(2).Info("pod is deleted")
return ctrl.Result{}, activeExpectations.Delete(req.Namespace, req.Name)
}
// if expectation not satisfied, shortcut this reconciling till informer cache is updated.
if satisfied, err := activeExpectations.IsSatisfied(instance); err != nil {
return ctrl.Result{}, err
} else if !satisfied {
logger.Info("pod is not satisfied to reconcile")
return ctrl.Result{}, nil
}
if instance.DeletionTimestamp != nil {
return ctrl.Result{}, nil
}
// if Pod is not begin a deletion PodOpsLifecycle, trigger it
if !podopslifecycle.IsDuringOps(OpsLifecycleAdapter, instance) {
if updated, err := podopslifecycle.Begin(r.Client, OpsLifecycleAdapter, instance); err != nil {
return ctrl.Result{}, fmt.Errorf("fail to begin PodOpsLifecycle to delete Pod %s: %s", req, err)
} else if updated {
if err := activeExpectations.ExpectUpdate(instance, expectations.Pod, instance.Name, instance.ResourceVersion); err != nil {
return ctrl.Result{}, fmt.Errorf("fail to expect Pod updated after beginning PodOpsLifecycle to delete Pod %s: %s", req, err)
}
}
}
// if Pod is allowed to operate, delete it
if _, allowed := podopslifecycle.AllowOps(OpsLifecycleAdapter, 0, instance); allowed {
logger.Info("try to delete Pod with deletion indication")
if err := r.Client.Delete(context.TODO(), instance); err != nil {
return ctrl.Result{}, fmt.Errorf("fail to delete Pod %s with deletion indication: %s", req, err)
} else {
r.Recorder.Event(instance, corev1.EventTypeNormal, v1alpha1.PodDeletionEvent, "Deleted pod")
if err := activeExpectations.ExpectDelete(instance, expectations.Pod, instance.Name); err != nil {
return ctrl.Result{}, fmt.Errorf("fail to expect Pod %s to be deleted: %s", req, err)
}
}
// if this pod in replaced update, delete pvcs
if _, exist := instance.Labels[appsv1alpha1.PodReplaceIndicationLabelKey]; exist {
err := r.deleteReplacedPodPvcs(ctx, instance)
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
func (r *PodDeletionReconciler) deleteReplacedPodPvcs(ctx context.Context, pod *corev1.Pod) error {
ownerRefs := pod.GetOwnerReferences()
cls := &appsv1alpha1.CollaSet{}
for _, ref := range ownerRefs {
if ref.Kind == "CollaSet" {
if err := r.Client.Get(ctx, types.NamespacedName{Namespace: pod.Namespace, Name: ref.Name}, cls); err != nil {
return err
}
break
}
}
if cls.Spec.VolumeClaimTemplates == nil {
return nil
}
pvcs, err := r.pvcControl.GetFilteredPvcs(ctx, cls)
if err != nil {
return err
}
return r.pvcControl.DeletePodPvcs(ctx, cls, pod, pvcs)
}