-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
256 lines (215 loc) · 7.51 KB
/
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
package nfshacontroller
import (
"context"
"fmt"
"sync"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/clock"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/record"
)
// Options to pass when creating a new nfscontroller
type Option func(nfsc *NfshaController)
// Set an EventRecorder that will be notified of any events that occur
func WithEventRecorder(ev record.EventRecorder) Option {
return func(nfsc *NfshaController) {
nfsc.evRecorder = ev
}
}
// Create a new nfscontroller with the given Name, Kubernetes client and opts
// Can be customized by adding Option(s).
func NewNFSHAController(name string, kubeClient kubernetes.Interface, opts ...Option) *NfshaController {
nsfhaController := &NfshaController{
name: name,
kubeClient: kubeClient,
watchBackoff: wait.NewExponentialBackoffManager(100*time.Millisecond, 20*time.Second, 1*time.Minute, 2.0, 1.0, &clock.RealClock{}),
}
for _, opt := range opts {
opt(nsfhaController)
}
return nsfhaController
}
// Start monitoring the Kubernetes API for changes to the Pod objects
func (nfsc *NfshaController) Run(ctx context.Context, wg *sync.WaitGroup) error {
defer wg.Done()
podUpdates, err := nfsc.watchPods(ctx)
if err != nil {
return fmt.Errorf("failed to set up Pod watch: %w", err)
}
for {
var err error
select {
case <-ctx.Done():
log.Debug("context done")
return ctx.Err()
case podEv, ok := <-podUpdates:
if !ok {
return &unexpectedChannelClose{"Pod updates"}
}
err = nfsc.HandlePodWatchEvent(ctx, podEv)
}
if err != nil {
log.WithError(err).Info("error processing event: %w", err)
}
}
}
type NfshaController struct {
// Required settings
name string
kubeClient kubernetes.Interface
// optional settings
podListOpts metav1.ListOptions
evRecorder record.EventRecorder
watchBackoff wait.BackoffManager
}
func (nfsc *NfshaController) watchPods(ctx context.Context) (<-chan watch.Event, error) {
initialPods, err := nfsc.kubeClient.CoreV1().Pods(metav1.NamespaceAll).List(ctx, nfsc.podListOpts)
if err != nil {
return nil, err
}
watchOpts := *nfsc.podListOpts.DeepCopy()
watchOpts.ResourceVersion = initialPods.ResourceVersion
watchOpts.AllowWatchBookmarks = true
watchChan := make(chan watch.Event)
podWatch := func() {
log.WithField("resource-version", watchOpts.ResourceVersion).Debug("(re-)starting Pod watch")
w, err := nfsc.kubeClient.CoreV1().Pods(metav1.NamespaceAll).Watch(ctx, watchOpts)
if err != nil {
log.WithError(err).Info("Pod watch failed, restarting...")
return
}
defer w.Stop()
for item := range w.ResultChan() {
if item.Type == watch.Bookmark {
watchOpts.ResourceVersion = item.Object.(*corev1.Pod).ResourceVersion
log.WithField("resource-version", watchOpts.ResourceVersion).Debug("Pod watch resource version updated")
continue
}
watchChan <- item
}
}
go wait.BackoffUntil(podWatch, nfsc.watchBackoff, true, ctx.Done())
return watchChan, nil
}
func (nfsc *NfshaController) HandlePodWatchEvent(ctx context.Context, ev watch.Event) error {
switch ev.Type {
case watch.Error:
return fmt.Errorf("watch error: %v", ev.Object)
case watch.Modified:
// log the event and the pod name
pod := ev.Object.(*corev1.Pod)
log.WithFields(log.Fields{
"event": ev.Type,
"pod": pod.Name,
}).Info("Pod event received")
nfsc.deleteFromPod(ctx, ev.Object.(*corev1.Pod))
}
return nil
}
// deleteFromPod force deletes the given pod if the node status is not ready
func (nfsc *NfshaController) deleteFromPod(ctx context.Context, pod *corev1.Pod) {
// return if the pod doesn't exist
_, err := nfsc.kubeClient.CoreV1().Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{})
if errors.IsNotFound(err) {
return
}
// check if the node is not ready
node, err := nfsc.kubeClient.CoreV1().Nodes().Get(ctx, pod.Spec.NodeName, metav1.GetOptions{})
if err != nil {
log.WithError(err).Errorf("Error getting pod %s/%s", pod.Namespace, pod.Name)
return
}
// search the node.Status.Conditions array for the condition type "Ready"
for i := range node.Status.Conditions {
if node.Status.Conditions[i].Type == "Ready" {
if node.Status.Conditions[i].Status == "True" {
// node is ready, do nothing
log.WithField("pod", pod.Name).Debug("Not deleting pod, node is ready")
return
}
}
}
nodeNotReadyEvent := false
// If it's a test just find the event through a loop as FieldSelector does not work on the fake client
if nfsc.name == "test" {
events, _ := nfsc.kubeClient.CoreV1().Events(pod.Namespace).List(ctx, metav1.ListOptions{})
for _, event := range events.Items {
if event.InvolvedObject.Name == pod.Name && event.InvolvedObject.Kind == "Pod" && event.Reason == "NodeNotReady" {
nodeNotReadyEvent = true
break
}
}
} else {
events, _ := nfsc.kubeClient.CoreV1().Events(pod.Namespace).List(ctx, metav1.ListOptions{FieldSelector: "involvedObject.name=" + pod.Name, TypeMeta: metav1.TypeMeta{Kind: "Pod"}})
for _, item := range events.Items {
if item.Reason == "NodeNotReady" {
nodeNotReadyEvent = true
break
}
}
}
if !nodeNotReadyEvent {
log.WithField("pod", pod.Name).Debug("Not deleting pod, node is ready")
return
}
provisionerName := "openebs.io/nfsrwx"
// Get the list of PVCs from the pod
pvcNameList := []string{}
for _, volume := range pod.Spec.Volumes {
if volume.PersistentVolumeClaim != nil {
pvcNameList = append(pvcNameList, volume.PersistentVolumeClaim.ClaimName)
}
}
// Get the list of PVCs from the pvcNameList
pvcListWithAnnotation := &corev1.PersistentVolumeClaimList{}
for _, pvcName := range pvcNameList {
pvc, err := nfsc.kubeClient.CoreV1().PersistentVolumeClaims(pod.Namespace).Get(ctx, pvcName, metav1.GetOptions{})
if err != nil {
log.WithError(err).Errorf("Error deleting pod %s/%s", pod.Namespace, pod)
return
}
annotations := pvc.GetAnnotations()
for key, value := range annotations {
if key == "volume.kubernetes.io/storage-provisioner" && value == provisionerName {
log.WithField("pvc", pvc.Name).Debug("Found pvc with provisioner annotation")
pvcListWithAnnotation.Items = append(pvcListWithAnnotation.Items, *pvc)
}
}
}
if len(pvcListWithAnnotation.Items) == 0 {
log.WithField("pod", pod.Name).Debug("Not deleting pod, no pvc found")
return
}
log.WithField("pod", pod.Name).Debug("Force deleting pod")
// Force delete the pod
noGracePeriod := int64(0)
err = nfsc.kubeClient.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{GracePeriodSeconds: &noGracePeriod})
if err != nil && !errors.IsNotFound(err) {
if err != nil {
log.WithError(err).Errorf("Error deleting pod %s/%s", pod.Namespace, pod.Name)
return
}
}
nfsc.eventf(pod, corev1.EventTypeWarning, "ForceDeleted", "pod deleted because node is not ready and needs to be rescheduled")
}
// submit a new event originating from this controller to the k8s API, if configured.
func (nfsc *NfshaController) eventf(obj runtime.Object, eventtype string, reason string, messageFmt string, args ...interface{}) {
if nfsc.evRecorder == nil {
return
}
nfsc.evRecorder.Eventf(obj, eventtype, reason, messageFmt, args...)
}
// a channel was closed unexpectedly
type unexpectedChannelClose struct {
channelName string
}
func (u *unexpectedChannelClose) Error() string {
return fmt.Sprintf("%s closed unexpectedly", u.channelName)
}