/
crr_daemon_controller.go
454 lines (395 loc) · 15.4 KB
/
crr_daemon_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
454
/*
Copyright 2021 The Kruise 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 containerrecreate
import (
"context"
"fmt"
"math/rand"
"net/http"
"reflect"
"sort"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
kubeletcontainer "k8s.io/kubernetes/pkg/kubelet/container"
runtimeclient "sigs.k8s.io/controller-runtime/pkg/client"
appsv1alpha1 "github.com/openkruise/kruise/apis/apps/v1alpha1"
"github.com/openkruise/kruise/pkg/client"
kruiseclient "github.com/openkruise/kruise/pkg/client/clientset/versioned"
listersalpha1 "github.com/openkruise/kruise/pkg/client/listers/apps/v1alpha1"
daemonruntime "github.com/openkruise/kruise/pkg/daemon/criruntime"
"github.com/openkruise/kruise/pkg/daemon/kuberuntime"
daemonoptions "github.com/openkruise/kruise/pkg/daemon/options"
"github.com/openkruise/kruise/pkg/util"
"github.com/openkruise/kruise/pkg/util/expectations"
)
const (
// TODO: make it a configurable flag
workers = 32
maxExpectationWaitDuration = 10 * time.Second
)
var (
resourceVersionExpectation = expectations.NewResourceVersionExpectation()
)
type Controller struct {
queue workqueue.RateLimitingInterface
runtimeClient runtimeclient.Client
crrInformer cache.SharedIndexInformer
crrLister listersalpha1.ContainerRecreateRequestLister
eventRecorder record.EventRecorder
runtimeFactory daemonruntime.Factory
}
// NewController returns the controller for CRR
func NewController(opts daemonoptions.Options) (*Controller, error) {
genericClient := client.GetGenericClientWithName("kruise-daemon-crr")
informer := newCRRInformer(genericClient.KruiseClient, opts.NodeName)
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: genericClient.KubeClient.CoreV1().Events("")})
recorder := eventBroadcaster.NewRecorder(opts.Scheme, v1.EventSource{Component: "kruise-daemon-crr", Host: opts.NodeName})
queue := workqueue.NewNamedRateLimitingQueue(
// Backoff duration from 500ms to 50~55s
workqueue.NewItemExponentialFailureRateLimiter(500*time.Millisecond, 50*time.Second+time.Millisecond*time.Duration(rand.Intn(5000))),
"crr",
)
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
crr, ok := obj.(*appsv1alpha1.ContainerRecreateRequest)
if ok {
enqueue(queue, crr)
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
crr, ok := newObj.(*appsv1alpha1.ContainerRecreateRequest)
if ok {
enqueue(queue, crr)
}
},
DeleteFunc: func(obj interface{}) {
crr, ok := obj.(*appsv1alpha1.ContainerRecreateRequest)
if ok {
resourceVersionExpectation.Delete(crr)
}
},
})
opts.Healthz.RegisterFunc("crrInformerSynced", func(_ *http.Request) error {
if !informer.HasSynced() {
return fmt.Errorf("not synced")
}
return nil
})
return &Controller{
queue: queue,
runtimeClient: opts.RuntimeClient,
crrInformer: informer,
crrLister: listersalpha1.NewContainerRecreateRequestLister(informer.GetIndexer()),
eventRecorder: recorder,
runtimeFactory: opts.RuntimeFactory,
}, nil
}
func newCRRInformer(client kruiseclient.Interface, nodeName string) cache.SharedIndexInformer {
tweakListOptionsFunc := func(opt *metav1.ListOptions) {
opt.LabelSelector = fmt.Sprintf("%s=%s,%s=%s",
appsv1alpha1.ContainerRecreateRequestNodeNameKey, nodeName,
appsv1alpha1.ContainerRecreateRequestActiveKey, "true",
)
}
im := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
tweakListOptionsFunc(&options)
return client.AppsV1alpha1().ContainerRecreateRequests(v1.NamespaceAll).List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
tweakListOptionsFunc(&options)
return client.AppsV1alpha1().ContainerRecreateRequests(v1.NamespaceAll).Watch(context.TODO(), options)
},
},
&appsv1alpha1.ContainerRecreateRequest{},
0, // do not resync
cache.Indexers{CRRPodNameIndex: SpecPodNameIndexFunc, cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
return im
}
func enqueue(queue workqueue.Interface, obj *appsv1alpha1.ContainerRecreateRequest) {
if obj.DeletionTimestamp != nil || obj.Status.CompletionTime != nil {
return
}
queue.Add(objectKey(obj))
}
func objectKey(obj *appsv1alpha1.ContainerRecreateRequest) string {
return obj.Namespace + "/" + obj.Spec.PodName
}
func (c *Controller) Run(stop <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
klog.Info("Starting informer for ContainerRecreateRequest")
go c.crrInformer.Run(stop)
if !cache.WaitForCacheSync(stop, c.crrInformer.HasSynced) {
return
}
klog.Infof("Starting crr daemon controller")
for i := 0; i < workers; i++ {
go wait.Until(func() {
for c.processNextWorkItem() {
}
}, time.Second, stop)
}
klog.Info("Started crr daemon controller successfully")
<-stop
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextWorkItem() bool {
// pull the next work item from queue. It should be a key we use to lookup
// something in a cache
key, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(key)
err := c.sync(key.(string))
if err == nil {
// No error, tell the queue to stop tracking history
c.queue.Forget(key)
} else {
// requeue the item to work on later
c.queue.AddRateLimited(key)
}
return true
}
func (c *Controller) sync(key string) (retErr error) {
namespace, podName, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
klog.Warningf("Invalid key: %s", key)
return nil
}
objectList, err := c.crrInformer.GetIndexer().ByIndex(CRRPodNameIndex, podName)
if err != nil {
return err
}
crrList := make([]*appsv1alpha1.ContainerRecreateRequest, 0, len(objectList))
for _, obj := range objectList {
crr, ok := obj.(*appsv1alpha1.ContainerRecreateRequest)
if ok && crr != nil && crr.Namespace == namespace {
crrList = append(crrList, crr)
}
}
if len(crrList) == 0 {
return nil
}
crr, err := c.pickRecreateRequest(crrList)
if err != nil || crr == nil {
return err
}
klog.V(3).Infof("Start syncing for %s/%s", namespace, crr.Name)
defer func() {
if retErr != nil {
klog.Errorf("Failed to sync for %s/%s: %v", namespace, crr.Name, retErr)
} else {
klog.V(3).Infof("Finished syncing for %s/%s", namespace, crr.Name)
}
}()
// once first update its phase to recreating
if crr.Status.Phase != appsv1alpha1.ContainerRecreateRequestRecreating {
return c.updateCRRPhase(crr, appsv1alpha1.ContainerRecreateRequestRecreating)
}
if crr.Spec.Strategy.UnreadyGracePeriodSeconds != nil {
unreadyTimeStr := crr.Annotations[appsv1alpha1.ContainerRecreateRequestUnreadyAcquiredKey]
if unreadyTimeStr == "" {
klog.Infof("CRR %s/%s is waiting for unready acquirement.", crr.Namespace, crr.Name)
return nil
}
unreadyTime, err := time.Parse(time.RFC3339, unreadyTimeStr)
if err != nil {
klog.Errorf("CRR %s/%s failed to parse unready time %s: %v", crr.Namespace, crr.Name, unreadyTimeStr, err)
return c.completeCRRStatus(crr, fmt.Sprintf("failed to parse unready time %s: %v", unreadyTimeStr, err))
}
leftTime := time.Duration(*crr.Spec.Strategy.UnreadyGracePeriodSeconds)*time.Second - time.Since(unreadyTime)
if leftTime > 0 {
klog.Infof("CRR %s/%s is waiting for unready grace period %v left time.", crr.Namespace, crr.Name, leftTime)
c.queue.AddAfter(crr.Namespace+"/"+crr.Spec.PodName, leftTime+100*time.Millisecond)
return nil
}
}
return c.manage(crr)
}
func (c *Controller) pickRecreateRequest(crrList []*appsv1alpha1.ContainerRecreateRequest) (*appsv1alpha1.ContainerRecreateRequest, error) {
sort.Sort(crrListByPhaseAndCreated(crrList))
var picked *appsv1alpha1.ContainerRecreateRequest
for _, crr := range crrList {
if crr.DeletionTimestamp != nil || crr.Status.CompletionTime != nil {
resourceVersionExpectation.Delete(crr)
continue
}
resourceVersionExpectation.Observe(crr)
if satisfied, duration := resourceVersionExpectation.IsSatisfied(crr); !satisfied {
if duration < maxExpectationWaitDuration {
break
}
klog.Warningf("Wait for CRR %s/%s resourceVersion expectation over %v", crr.Namespace, crr.Name, duration)
resourceVersionExpectation.Delete(crr)
}
// Only update non-picked CRR to Pending, for the picked one will directly update to Recreating
if picked == nil {
picked = crr
} else if crr.Status.Phase == "" {
if err := c.updateCRRPhase(crr, appsv1alpha1.ContainerRecreateRequestPending); err != nil {
klog.Errorf("Failed to update CRR %s/%s status to Pending: %v", crr.Namespace, crr.Name, err)
return nil, err
}
}
}
return picked, nil
}
func (c *Controller) manage(crr *appsv1alpha1.ContainerRecreateRequest) error {
runtimeManager, err := c.newRuntimeManager(c.runtimeFactory, crr)
if err != nil {
klog.Errorf("Failed to find runtime service for %s/%s: %v", crr.Namespace, crr.Name, err)
return c.completeCRRStatus(crr, fmt.Sprintf("failed to find runtime service: %v", err))
}
pod := convertCRRToPod(crr)
podStatus, err := runtimeManager.GetPodStatus(context.TODO(), pod.UID, pod.Name, pod.Namespace)
if err != nil {
return fmt.Errorf("failed to GetPodStatus %s/%s with uid %s: %v", pod.Namespace, pod.Name, pod.UID, err)
}
klog.V(5).Infof("CRR %s/%s for Pod %s GetPodStatus: %v", crr.Namespace, crr.Name, pod.Name, util.DumpJSON(podStatus))
newCRRContainerRecreateStates := getCurrentCRRContainersRecreateStates(crr, podStatus)
if !reflect.DeepEqual(crr.Status.ContainerRecreateStates, newCRRContainerRecreateStates) {
return c.patchCRRContainerRecreateStates(crr, newCRRContainerRecreateStates)
}
var completedCount int
for i := range newCRRContainerRecreateStates {
state := &newCRRContainerRecreateStates[i]
switch state.Phase {
case appsv1alpha1.ContainerRecreateRequestSucceeded:
completedCount++
continue
case appsv1alpha1.ContainerRecreateRequestFailed:
completedCount++
if crr.Spec.Strategy.FailurePolicy == appsv1alpha1.ContainerRecreateRequestFailurePolicyIgnore {
continue
}
return c.completeCRRStatus(crr, "")
case appsv1alpha1.ContainerRecreateRequestPending, appsv1alpha1.ContainerRecreateRequestRecreating:
}
if state.Phase == appsv1alpha1.ContainerRecreateRequestRecreating {
state.IsKilled = true
if crr.Spec.Strategy.OrderedRecreate {
break
}
continue
}
kubeContainerStatus := podStatus.FindContainerStatusByName(state.Name)
if kubeContainerStatus == nil {
break
}
msg := fmt.Sprintf("Stopping container %s by ContainerRecreateRequest %s", state.Name, crr.Name)
err := runtimeManager.KillContainer(pod, kubeContainerStatus.ID, state.Name, msg, nil)
if err != nil {
klog.Errorf("Failed to kill container %s in Pod %s/%s for CRR %s/%s: %v", state.Name, pod.Namespace, pod.Name, crr.Namespace, crr.Name, err)
state.Phase = appsv1alpha1.ContainerRecreateRequestFailed
state.Message = fmt.Sprintf("kill container error: %v", err)
if crr.Spec.Strategy.FailurePolicy == appsv1alpha1.ContainerRecreateRequestFailurePolicyIgnore {
continue
}
return c.patchCRRContainerRecreateStates(crr, newCRRContainerRecreateStates)
}
state.IsKilled = true
state.Phase = appsv1alpha1.ContainerRecreateRequestRecreating
break
}
if !reflect.DeepEqual(crr.Status.ContainerRecreateStates, newCRRContainerRecreateStates) {
return c.patchCRRContainerRecreateStates(crr, newCRRContainerRecreateStates)
}
// check if all containers have completed
if completedCount == len(newCRRContainerRecreateStates) {
return c.completeCRRStatus(crr, "")
}
if crr.Spec.Strategy != nil && crr.Spec.Strategy.MinStartedSeconds > 0 {
c.queue.AddAfter(objectKey(crr), time.Duration(crr.Spec.Strategy.MinStartedSeconds)*time.Second)
}
return nil
}
func (c *Controller) patchCRRContainerRecreateStates(crr *appsv1alpha1.ContainerRecreateRequest, newCRRContainerRecreateStates []appsv1alpha1.ContainerRecreateRequestContainerRecreateState) error {
klog.V(3).Infof("CRR %s/%s patch containerRecreateStates: %v", crr.Namespace, crr.Name, util.DumpJSON(newCRRContainerRecreateStates))
crr = crr.DeepCopy()
body := fmt.Sprintf(`{"status":{"containerRecreateStates":%s}}`, util.DumpJSON(newCRRContainerRecreateStates))
oldRev := crr.ResourceVersion
defer func() {
if crr.ResourceVersion != oldRev {
resourceVersionExpectation.Expect(crr)
}
}()
return c.runtimeClient.Status().Patch(context.TODO(), crr, runtimeclient.RawPatch(types.MergePatchType, []byte(body)))
}
func (c *Controller) updateCRRPhase(crr *appsv1alpha1.ContainerRecreateRequest, phase appsv1alpha1.ContainerRecreateRequestPhase) error {
crr = crr.DeepCopy()
crr.Status.Phase = phase
oldRev := crr.ResourceVersion
defer func() {
if crr.ResourceVersion != oldRev {
resourceVersionExpectation.Expect(crr)
}
}()
return c.runtimeClient.Status().Update(context.TODO(), crr)
}
func (c *Controller) completeCRRStatus(crr *appsv1alpha1.ContainerRecreateRequest, msg string) error {
crr = crr.DeepCopy()
now := metav1.Now()
crr.Status.Phase = appsv1alpha1.ContainerRecreateRequestCompleted
crr.Status.CompletionTime = &now
crr.Status.Message = msg
oldRev := crr.ResourceVersion
defer func() {
if crr.ResourceVersion != oldRev {
resourceVersionExpectation.Expect(crr)
}
}()
return c.runtimeClient.Status().Update(context.TODO(), crr)
}
func (c *Controller) newRuntimeManager(runtimeFactory daemonruntime.Factory, crr *appsv1alpha1.ContainerRecreateRequest) (kuberuntime.Runtime, error) {
var runtimeName string
for i := range crr.Spec.Containers {
c := &crr.Spec.Containers[i]
if c.StatusContext == nil || c.StatusContext.ContainerID == "" {
return nil, fmt.Errorf("no statusContext or empty containerID in %s container", c.Name)
}
containerID := kubeletcontainer.ContainerID{}
if err := containerID.ParseString(c.StatusContext.ContainerID); err != nil {
return nil, fmt.Errorf("failed to parse containerID %s in %s container: %v", c.StatusContext.ContainerID, c.Name, err)
}
if runtimeName == "" {
runtimeName = containerID.Type
} else if runtimeName != containerID.Type {
return nil, fmt.Errorf("has different runtime types %s, %s in Pod", runtimeName, containerID.Type)
}
}
if runtimeName == "" {
return nil, fmt.Errorf("no runtime type found in Pod")
}
runtimeService := runtimeFactory.GetRuntimeServiceByName(runtimeName)
if runtimeService == nil {
return nil, fmt.Errorf("not found runtime service for %s in daemon", runtimeName)
}
return kuberuntime.NewGenericRuntime(runtimeName, runtimeService, c.eventRecorder, &http.Client{}), nil
}