-
Notifications
You must be signed in to change notification settings - Fork 430
/
qos_policy.go
537 lines (485 loc) · 15.1 KB
/
qos_policy.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package controller
import (
"context"
"fmt"
"net"
"reflect"
"sort"
"strings"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
"github.com/kubeovn/kube-ovn/pkg/util"
)
func (c *Controller) enqueueAddQoSPolicy(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
klog.V(3).Infof("enqueue add qos policy %s", key)
c.addQoSPolicyQueue.Add(key)
}
func compareQoSPolicyBandwidthLimitRules(old, new kubeovnv1.QoSPolicyBandwidthLimitRules) bool {
if len(old) != len(new) {
return false
}
sort.Slice(new, func(i, j int) bool {
return new[i].Name < new[j].Name
})
return reflect.DeepEqual(old, new)
}
func (c *Controller) enqueueUpdateQoSPolicy(old, new interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(new); err != nil {
utilruntime.HandleError(err)
return
}
oldQos := old.(*kubeovnv1.QoSPolicy)
newQos := new.(*kubeovnv1.QoSPolicy)
if !newQos.DeletionTimestamp.IsZero() {
klog.V(3).Infof("enqueue update to clean qos %s", key)
c.updateQoSPolicyQueue.Add(key)
return
}
if oldQos.Status.Shared != newQos.Spec.Shared ||
oldQos.Status.BindingType != newQos.Spec.BindingType ||
!compareQoSPolicyBandwidthLimitRules(oldQos.Status.BandwidthLimitRules,
newQos.Spec.BandwidthLimitRules) {
klog.V(3).Infof("enqueue update qos %s", key)
c.updateQoSPolicyQueue.Add(key)
return
}
}
func (c *Controller) enqueueDelQoSPolicy(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
c.delQoSPolicyQueue.Add(key)
}
func (c *Controller) runAddQoSPolicyWorker() {
for c.processNextAddQoSPolicyWorkItem() {
}
}
func (c *Controller) runUpdateQoSPolicyWorker() {
for c.processNextUpdateQoSPolicyWorkItem() {
}
}
func (c *Controller) runDelQoSPolicyWorker() {
for c.processNextDeleteQoSPolicyWorkItem() {
}
}
func (c *Controller) processNextAddQoSPolicyWorkItem() bool {
obj, shutdown := c.addQoSPolicyQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.addQoSPolicyQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.addQoSPolicyQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleAddQoSPolicy(key); err != nil {
c.addQoSPolicyQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.addQoSPolicyQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextUpdateQoSPolicyWorkItem() bool {
obj, shutdown := c.updateQoSPolicyQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.updateQoSPolicyQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.updateQoSPolicyQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleUpdateQoSPolicy(key); err != nil {
c.updateQoSPolicyQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.updateQoSPolicyQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextDeleteQoSPolicyWorkItem() bool {
obj, shutdown := c.delQoSPolicyQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.delQoSPolicyQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.delQoSPolicyQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected qos in workqueue but got %#v", obj))
return nil
}
if err := c.handleDelQoSPolicy(key); err != nil {
c.delQoSPolicyQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.delQoSPolicyQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) handleAddQoSPolicy(key string) error {
c.vpcNatGwKeyMutex.LockKey(key)
defer func() { _ = c.vpcNatGwKeyMutex.UnlockKey(key) }()
klog.Infof("handle add QoS policy %s", key)
cachedQoS, err := c.qosPoliciesLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
sortedNewRules := cachedQoS.Spec.BandwidthLimitRules
sort.Slice(sortedNewRules, func(i, j int) bool {
return sortedNewRules[i].Name < sortedNewRules[j].Name
})
if reflect.DeepEqual(cachedQoS.Status.BandwidthLimitRules,
sortedNewRules) &&
cachedQoS.Status.Shared == cachedQoS.Spec.Shared &&
cachedQoS.Status.BindingType == cachedQoS.Spec.BindingType {
// already ok
return nil
}
klog.V(3).Infof("handle add qos %s", key)
if err := c.validateQosPolicy(cachedQoS); err != nil {
klog.Errorf("failed to validate qos %s, %v", key, err)
return err
}
if err = c.patchQoSStatus(key, cachedQoS.Spec.Shared, cachedQoS.Spec.BindingType, sortedNewRules); err != nil {
klog.Errorf("failed to patch status for qos %s, %v", key, err)
return err
}
return nil
}
func (c *Controller) patchQoSStatus(
key string, shared bool, qosType kubeovnv1.QoSPolicyBindingType, bandwidthRules kubeovnv1.QoSPolicyBandwidthLimitRules) error {
oriQoS, err := c.qosPoliciesLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
qos := oriQoS.DeepCopy()
qos.Status.Shared = shared
qos.Status.BindingType = qosType
qos.Status.BandwidthLimitRules = bandwidthRules
bytes, err := qos.Status.Bytes()
if err != nil {
return err
}
if _, err = c.config.KubeOvnClient.KubeovnV1().QoSPolicies().Patch(context.Background(), qos.Name,
types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Errorf("failed to patch qos %s, %v", qos.Name, err)
return err
}
return nil
}
func (c *Controller) handleDelQoSPoliciesFinalizer(key string) error {
cachedQoSPolicies, err := c.qosPoliciesLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if len(cachedQoSPolicies.Finalizers) == 0 {
return nil
}
newQoSPolicies := cachedQoSPolicies.DeepCopy()
controllerutil.RemoveFinalizer(newQoSPolicies, util.ControllerName)
patch, err := util.GenerateMergePatchPayload(cachedQoSPolicies, newQoSPolicies)
if err != nil {
klog.Errorf("failed to generate patch payload for qos '%s', %v", cachedQoSPolicies.Name, err)
return err
}
if _, err := c.config.KubeOvnClient.KubeovnV1().QoSPolicies().Patch(context.Background(), cachedQoSPolicies.Name,
types.MergePatchType, patch, metav1.PatchOptions{}, ""); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Errorf("failed to remove finalizer from qos '%s', %v", cachedQoSPolicies.Name, err)
return err
}
return nil
}
func diffQoSPolicyBandwidthLimitRules(oldList, newList kubeovnv1.QoSPolicyBandwidthLimitRules) (added, deleted, updated kubeovnv1.QoSPolicyBandwidthLimitRules) {
added = kubeovnv1.QoSPolicyBandwidthLimitRules{}
deleted = kubeovnv1.QoSPolicyBandwidthLimitRules{}
updated = kubeovnv1.QoSPolicyBandwidthLimitRules{}
// Create a map of old rules indexed by name for efficient lookup
oldMap := make(map[string]*kubeovnv1.QoSPolicyBandwidthLimitRule)
for _, s := range oldList {
oldMap[s.Name] = s
}
// Loop through new rules and compare with old rules
for _, s := range newList {
if old, ok := oldMap[s.Name]; !ok {
// add the rule
added = append(added, s)
} else if !reflect.DeepEqual(old, s) {
// updated the rule
updated = append(updated, s)
}
// keep the rule not changed
delete(oldMap, s.Name)
}
// Remaining rules in oldMap are deleted
for _, s := range oldMap {
deleted = append(deleted, s)
}
return added, deleted, updated
}
func (c *Controller) reconcileEIPBandtithLimitRules(
eip *kubeovnv1.IptablesEIP,
added kubeovnv1.QoSPolicyBandwidthLimitRules,
deleted kubeovnv1.QoSPolicyBandwidthLimitRules,
updated kubeovnv1.QoSPolicyBandwidthLimitRules) error {
var err error
// in this case, we must delete rules first, then add or update rules
if len(deleted) > 0 {
if err = c.delEIPBandtithLimitRules(eip, eip.Status.IP, deleted); err != nil {
klog.Errorf("failed to delete eip %s bandwidth limit rules, %v", eip.Name, err)
return err
}
}
if len(added) > 0 {
if err = c.addOrUpdateEIPBandtithLimitRules(eip, eip.Status.IP, added); err != nil {
klog.Errorf("failed to add eip %s bandwidth limit rules, %v", eip.Name, err)
return err
}
}
if len(updated) > 0 {
if err = c.addOrUpdateEIPBandtithLimitRules(eip, eip.Status.IP, updated); err != nil {
klog.Errorf("failed to update eip %s bandwidth limit rules, %v", eip.Name, err)
return err
}
}
return nil
}
func validateIPMatchValue(matachValue string) bool {
parts := strings.Split(matachValue, " ")
if len(parts) != 2 {
klog.Errorf("invalid ip MatchValue %s", matachValue)
return false
}
direction := parts[0]
if direction != "src" && direction != "dst" {
klog.Errorf("invalid direction %s, must be src or dst", direction)
return false
}
cidr := parts[1]
if _, _, err := net.ParseCIDR(cidr); err != nil {
klog.Errorf("invalid cidr %s", cidr)
return false
}
// invalid cidr
return true
}
func (c *Controller) validateQosPolicy(qosPolicy *kubeovnv1.QoSPolicy) error {
var err error
if qosPolicy.Spec.BandwidthLimitRules != nil {
for _, rule := range qosPolicy.Spec.BandwidthLimitRules {
if rule.MatchType == "ip" {
if !validateIPMatchValue(rule.MatchValue) {
err = fmt.Errorf("invalid ip MatchValue %s", rule.MatchValue)
klog.Error(err)
return err
}
}
}
}
if !qosPolicy.Spec.Shared && qosPolicy.Spec.BindingType == kubeovnv1.QoSBindingTypeNatGw {
err = fmt.Errorf("qos policy %s is not shared, but binding to nat gateway", qosPolicy.Name)
klog.Error(err)
return err
}
return nil
}
func (c *Controller) handleUpdateQoSPolicy(key string) error {
c.vpcNatGwKeyMutex.LockKey(key)
defer func() { _ = c.vpcNatGwKeyMutex.UnlockKey(key) }()
klog.Infof("handle update QoS policy %s", key)
cachedQos, err := c.qosPoliciesLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
// should delete
if !cachedQos.DeletionTimestamp.IsZero() {
if cachedQos.Spec.BindingType == kubeovnv1.QoSBindingTypeEIP {
eips, err := c.iptablesEipsLister.List(
labels.SelectorFromSet(labels.Set{util.QoSLabel: key}))
// when eip is not found, we should delete finalizer
if err != nil && !k8serrors.IsNotFound(err) {
klog.Errorf("failed to get eip list, %v", err)
return err
}
if len(eips) != 0 {
err = fmt.Errorf("qos policy %s is being used", key)
klog.Error(err)
return err
}
}
if cachedQos.Spec.BindingType == kubeovnv1.QoSBindingTypeNatGw {
gws, err := c.vpcNatGatewayLister.List(
labels.SelectorFromSet(labels.Set{util.QoSLabel: key}))
// when nat gw is not found, we should delete finalizer
if err != nil && !k8serrors.IsNotFound(err) {
klog.Errorf("failed to get gw list, %v", err)
return err
}
if len(gws) != 0 {
err = fmt.Errorf("qos policy %s is being used", key)
klog.Error(err)
return err
}
}
if err = c.handleDelQoSPoliciesFinalizer(key); err != nil {
klog.Errorf("failed to handle del finalizer for qos %s, %v", key, err)
return err
}
return nil
}
if err = c.handleAddQoSPolicyFinalizer(key); err != nil {
klog.Errorf("failed to handle add finalizer for qos, %v", err)
return err
}
if cachedQos.Status.Shared != cachedQos.Spec.Shared ||
cachedQos.Status.BindingType != cachedQos.Spec.BindingType {
err := fmt.Errorf("not support qos %s change shared", key)
klog.Error(err)
return err
}
if err := c.validateQosPolicy(cachedQos); err != nil {
klog.Errorf("failed to validate qos %s, %v", key, err)
return err
}
added, deleted, updated := diffQoSPolicyBandwidthLimitRules(cachedQos.Status.BandwidthLimitRules, cachedQos.Spec.BandwidthLimitRules)
bandwidthRulesChanged := len(added) > 0 || len(deleted) > 0 || len(updated) > 0
if bandwidthRulesChanged {
klog.V(3).Infof(
"bandwidth limit rules is changed for qos %s, added: %s, deleted: %s, updated: %s",
key, added.Strings(), deleted.Strings(), updated.Strings())
if cachedQos.Status.Shared {
err := fmt.Errorf("not support shared qos %s change rule ", key)
klog.Error(err)
return err
} else {
if cachedQos.Status.BindingType == kubeovnv1.QoSBindingTypeEIP {
// filter to eip
eips, err := c.iptablesEipsLister.List(
labels.SelectorFromSet(labels.Set{util.QoSLabel: key}))
if err != nil {
klog.Errorf("failed to get eip list, %v", err)
return err
}
if len(eips) == 0 {
// not thing to do
} else if len(eips) == 1 {
eip := eips[0]
if err = c.reconcileEIPBandtithLimitRules(eip, added, deleted, updated); err != nil {
klog.Errorf("failed to reconcile eip %s bandwidth limit rules, %v", eip.Name, err)
return err
}
} else {
err := fmt.Errorf("not support qos %s change rule, related eip more than one", key)
klog.Error(err)
return err
}
}
sortedNewRules := cachedQos.Spec.BandwidthLimitRules
sort.Slice(sortedNewRules, func(i, j int) bool {
return sortedNewRules[i].Name < sortedNewRules[j].Name
})
// .Status.Shared and .Status.BindingType are not supported to change
if err = c.patchQoSStatus(key, cachedQos.Status.Shared, cachedQos.Status.BindingType, sortedNewRules); err != nil {
klog.Errorf("failed to patch status for qos %s, %v", key, err)
return err
}
}
}
return nil
}
func (c *Controller) handleDelQoSPolicy(key string) error {
klog.V(3).Infof("deleted qos policy %s", key)
return nil
}
func (c *Controller) handleAddQoSPolicyFinalizer(key string) error {
cachedQoSPolicy, err := c.qosPoliciesLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if cachedQoSPolicy.DeletionTimestamp.IsZero() {
if util.ContainsString(cachedQoSPolicy.Finalizers, util.ControllerName) {
return nil
}
}
newQoSPolicy := cachedQoSPolicy.DeepCopy()
controllerutil.AddFinalizer(newQoSPolicy, util.ControllerName)
patch, err := util.GenerateMergePatchPayload(cachedQoSPolicy, newQoSPolicy)
if err != nil {
klog.Errorf("failed to generate patch payload for qos '%s', %v", cachedQoSPolicy.Name, err)
return err
}
if _, err := c.config.KubeOvnClient.KubeovnV1().QoSPolicies().Patch(context.Background(), cachedQoSPolicy.Name,
types.MergePatchType, patch, metav1.PatchOptions{}, ""); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Errorf("failed to add finalizer for qos '%s', %v", cachedQoSPolicy.Name, err)
return err
}
return nil
}