forked from kubeovn/kube-ovn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvip.go
572 lines (536 loc) · 16.1 KB
/
vip.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package controller
import (
"context"
"encoding/json"
"fmt"
"net"
"strings"
kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
"github.com/kubeovn/kube-ovn/pkg/ovs"
"github.com/kubeovn/kube-ovn/pkg/util"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"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"
)
func (c *Controller) enqueueAddVirtualIp(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
c.addVirtualIpQueue.Add(key)
}
func (c *Controller) enqueueUpdateVirtualIp(old, new interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(new); err != nil {
utilruntime.HandleError(err)
return
}
oldVip := old.(*kubeovnv1.Vip)
newVip := new.(*kubeovnv1.Vip)
if !newVip.DeletionTimestamp.IsZero() ||
oldVip.Spec.MacAddress != newVip.Spec.MacAddress ||
oldVip.Spec.ParentMac != newVip.Spec.ParentMac ||
oldVip.Spec.ParentV4ip != newVip.Spec.ParentV4ip ||
oldVip.Spec.V4ip != newVip.Spec.V4ip {
c.updateVirtualIpQueue.Add(key)
}
}
func (c *Controller) enqueueDelVirtualIp(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
c.delVirtualIpQueue.Add(key)
vipObj := obj.(*kubeovnv1.Vip)
c.updateSubnetStatusQueue.Add(vipObj.Spec.Subnet)
}
func (c *Controller) runAddVirtualIpWorker() {
for c.processNextAddVirtualIpWorkItem() {
}
}
func (c *Controller) runUpdateVirtualIpWorker() {
for c.processNextUpdateVirtualIpWorkItem() {
}
}
func (c *Controller) runDelVirtualIpWorker() {
for c.processNextDeleteVirtualIpWorkItem() {
}
}
func (c *Controller) processNextAddVirtualIpWorkItem() bool {
obj, shutdown := c.addVirtualIpQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.addVirtualIpQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.addVirtualIpQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleAddVirtualIp(key); err != nil {
c.addVirtualIpQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.addVirtualIpQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextUpdateVirtualIpWorkItem() bool {
obj, shutdown := c.updateVirtualIpQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.updateVirtualIpQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.updateVirtualIpQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleUpdateVirtualIp(key); err != nil {
c.updateVirtualIpQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.updateVirtualIpQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextDeleteVirtualIpWorkItem() bool {
obj, shutdown := c.delVirtualIpQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.delVirtualIpQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.delVirtualIpQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleDelVirtualIp(key); err != nil {
c.delVirtualIpQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.delVirtualIpQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) handleAddVirtualIp(key string) error {
cachedVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if cachedVip.Status.Mac != "" {
// already ok
return nil
}
klog.V(3).Infof("handle add vip %s", key)
vip := cachedVip.DeepCopy()
var sourceV4Ip, v4ip, v6ip, mac, subnetName string
subnetName = vip.Spec.Subnet
if subnetName == "" {
return fmt.Errorf("failed to create vip '%s', subnet should be set", key)
}
subnet, err := c.subnetsLister.Get(subnetName)
if err != nil {
return err
}
portName := ovs.PodNameToPortName(vip.Name, vip.Namespace, subnet.Spec.Provider)
sourceV4Ip = vip.Spec.V4ip
if sourceV4Ip != "" {
v4ip, v6ip, mac, err = c.acquireStaticIpAddress(subnet.Name, vip.Name, portName, sourceV4Ip)
} else {
// Random allocate
v4ip, v6ip, mac, err = c.acquireIpAddress(subnet.Name, vip.Name, portName)
}
if err != nil {
return err
}
var parentV4ip, parentV6ip, parentMac string
if vip.Spec.ParentMac != "" {
parentV4ip = vip.Spec.ParentV4ip
parentV6ip = vip.Spec.ParentV6ip
parentMac = vip.Spec.ParentMac
}
if err = c.createOrUpdateCrdVip(key, vip.Namespace, subnet.Name, v4ip, v6ip, mac, parentV4ip, parentV6ip, parentMac); err != nil {
klog.Errorf("failed to create or update vip '%s', %v", vip.Name, err)
return err
}
if err = c.subnetCountIp(subnet); err != nil {
klog.Errorf("failed to count vip '%s' in subnet, %v", vip.Name, err)
return err
}
return nil
}
func (c *Controller) handleUpdateVirtualIp(key string) error {
cachedVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
vip := cachedVip.DeepCopy()
// should delete
if !vip.DeletionTimestamp.IsZero() {
// TODO:// clean vip in its parent port aap list
if err = c.handleDelVipFinalizer(key); err != nil {
klog.Errorf("failed to handle vip finalizer %v", err)
return err
}
return nil
}
// not support change ip
if vip.Status.Mac != "" && vip.Status.Mac != vip.Spec.MacAddress ||
vip.Status.V4ip != "" && vip.Status.V4ip != vip.Spec.V4ip ||
vip.Status.V6ip != "" && vip.Status.V6ip != vip.Spec.V6ip {
err = fmt.Errorf("not support change ip of vip")
klog.Errorf("%v", err)
return err
}
// should update
if vip.Status.Mac == "" {
// TODO:// add vip in its parent port aap list
if err = c.createOrUpdateCrdVip(key, vip.Namespace, vip.Spec.Subnet,
vip.Spec.V4ip, vip.Spec.V6ip, vip.Spec.MacAddress,
vip.Spec.ParentV4ip, vip.Spec.ParentV6ip, vip.Spec.MacAddress); err != nil {
return err
}
ready := true
if err = c.patchVipStatus(key, vip.Spec.V4ip, ready); err != nil {
return err
}
if err = c.handleAddVipFinalizer(key); err != nil {
klog.Errorf("failed to handle vip finalizer %v", err)
return err
}
}
return nil
}
func (c *Controller) handleDelVirtualIp(key string) error {
klog.V(3).Infof("release vip %s", key)
c.ipam.ReleaseAddressByPod(key)
return nil
}
func (c *Controller) acquireStaticIpAddress(subnetName, name, nicName, ip string) (string, string, string, error) {
checkConflict := true
var v4ip, v6ip, mac string
var err error
for _, ipStr := range strings.Split(ip, ",") {
if net.ParseIP(ipStr) == nil {
return "", "", "", fmt.Errorf("failed to parse vip ip %s", ipStr)
}
}
if v4ip, v6ip, mac, err = c.ipam.GetStaticAddress(name, nicName, ip, mac, subnetName, checkConflict); err != nil {
klog.Errorf("failed to get static virtual ip '%s', mac '%s', subnet '%s', %v", ip, mac, subnetName, err)
return "", "", "", err
}
return v4ip, v6ip, mac, nil
}
func (c *Controller) acquireIpAddress(subnetName, name, nicName string) (string, string, string, error) {
var skippedAddrs []string
var v4ip, v6ip, mac string
checkConflict := true
var err error
for {
v4ip, v6ip, mac, err = c.ipam.GetRandomAddress(name, nicName, mac, subnetName, skippedAddrs, checkConflict)
if err != nil {
return "", "", "", err
}
ipv4OK, ipv6OK, err := c.validatePodIP(name, subnetName, v4ip, v6ip)
if err != nil {
return "", "", "", err
}
if ipv4OK && ipv6OK {
return v4ip, v6ip, mac, nil
}
if !ipv4OK {
skippedAddrs = append(skippedAddrs, v4ip)
}
if !ipv6OK {
skippedAddrs = append(skippedAddrs, v6ip)
}
}
}
func (c *Controller) subnetCountIp(subnet *kubeovnv1.Subnet) error {
var err error
if util.CheckProtocol(subnet.Spec.CIDRBlock) == kubeovnv1.ProtocolDual {
err = calcDualSubnetStatusIP(subnet, c)
} else {
err = calcSubnetStatusIP(subnet, c)
}
return err
}
func (c *Controller) createOrUpdateCrdVip(key, ns, subnet, v4ip, v6ip, mac, pV4ip, pV6ip, pmac string) error {
vipCr, err := c.config.KubeOvnClient.KubeovnV1().Vips().Get(context.Background(), key, metav1.GetOptions{})
if err != nil {
if k8serrors.IsNotFound(err) {
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Create(context.Background(), &kubeovnv1.Vip{
ObjectMeta: metav1.ObjectMeta{
Name: key,
Labels: map[string]string{
util.SubnetNameLabel: subnet,
util.IpReservedLabel: "",
},
Namespace: ns,
},
Spec: kubeovnv1.VipSpec{
Namespace: ns,
Subnet: subnet,
V4ip: v4ip,
V6ip: v6ip,
MacAddress: mac,
ParentV4ip: pV4ip,
ParentV6ip: pV6ip,
ParentMac: pmac,
},
}, metav1.CreateOptions{}); err != nil {
errMsg := fmt.Errorf("failed to create crd vip '%s', %v", key, err)
klog.Error(errMsg)
return errMsg
}
} else {
errMsg := fmt.Errorf("failed to get crd vip '%s', %v", key, err)
klog.Error(errMsg)
return errMsg
}
} else {
vip := vipCr.DeepCopy()
if vip.Status.Mac == "" && mac != "" {
// vip not support to update, just delete and create
vip.Spec.Namespace = ns
vip.Spec.V4ip = v4ip
vip.Spec.V6ip = v6ip
vip.Spec.MacAddress = mac
vip.Spec.ParentV4ip = pV4ip
vip.Spec.ParentV6ip = pV6ip
vip.Spec.ParentMac = pmac
vip.Status.Ready = true
vip.Status.V4ip = v4ip
vip.Status.V6ip = v6ip
vip.Status.Mac = mac
vip.Status.Pv4ip = pV4ip
vip.Status.Pv6ip = pV6ip
vip.Status.Pmac = pmac
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Update(context.Background(), vip, metav1.UpdateOptions{}); err != nil {
errMsg := fmt.Errorf("failed to update vip '%s', %v", key, err)
klog.Error(errMsg)
return errMsg
}
}
var needUpdateLabel bool
var op string
if len(vip.Labels) == 0 {
op = "add"
vip.Labels = map[string]string{
util.SubnetNameLabel: subnet,
util.IpReservedLabel: "",
}
needUpdateLabel = true
}
if vip.Labels[util.SubnetNameLabel] != subnet {
op = "replace"
vip.Labels[util.SubnetNameLabel] = subnet
needUpdateLabel = true
}
if needUpdateLabel {
patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s }]`
raw, _ := json.Marshal(vip.Labels)
patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw)
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Patch(context.Background(), vip.Name, types.JSONPatchType,
[]byte(patchPayload), metav1.PatchOptions{}); err != nil {
klog.Errorf("failed to patch label for vip '%s', %v", vip.Name, err)
return err
}
}
}
return nil
}
func (c *Controller) patchVipStatus(key, v4ip string, ready bool) error {
oriVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
klog.Errorf("failed to get cached vip '%s', %v", key, err)
return nil
}
return err
}
vip := oriVip.DeepCopy()
var changed bool
if vip.Status.Ready != ready {
vip.Status.Ready = ready
changed = true
}
if ready && v4ip != "" && vip.Status.V4ip != v4ip {
vip.Status.V4ip = v4ip
changed = true
}
if changed {
if _, err = c.config.KubeOvnClient.KubeovnV1().Vips().Update(context.Background(), vip, metav1.UpdateOptions{}); err != nil {
klog.Errorf("failed to update status for vip '%s', %v", key, err)
return err
}
}
return nil
}
func (c *Controller) podReuseVip(key, portName string, keepVIP bool) error {
// when pod use static vip, label vip reserved for pod
oriVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
klog.Errorf("failed to get cached vip '%s', %v", key, err)
return nil
}
return err
}
vip := oriVip.DeepCopy()
var op string
if vip.Labels[util.IpReservedLabel] != "" {
if keepVIP && vip.Labels[util.IpReservedLabel] == portName {
return nil
} else {
return fmt.Errorf("vip '%s' is in use by pod %s", vip.Name, vip.Labels[util.IpReservedLabel])
}
}
op = "replace"
vip.Labels[util.IpReservedLabel] = portName
patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s }]`
raw, _ := json.Marshal(vip.Labels)
patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw)
if _, err = c.config.KubeOvnClient.KubeovnV1().Vips().Patch(context.Background(), vip.Name, types.JSONPatchType, []byte(patchPayload), metav1.PatchOptions{}); err != nil {
klog.Errorf("failed to patch label for vip '%s', %v", vip.Name, err)
return err
}
c.ipam.ReleaseAddressByPod(key)
c.updateSubnetStatusQueue.Add(vip.Spec.Subnet)
return nil
}
func (c *Controller) releaseVip(key string) error {
// clean vip label when pod delete
oriVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
klog.Errorf("failed to get cached vip '%s', %v", key, err)
return nil
}
return err
}
vip := oriVip.DeepCopy()
var needUpdateLabel bool
var op string
if vip.Labels[util.IpReservedLabel] == "" {
return nil
} else {
op = "replace"
vip.Labels[util.IpReservedLabel] = ""
needUpdateLabel = true
}
if needUpdateLabel {
klog.V(3).Infof("clean reserved label from vip %s", key)
patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s }]`
raw, _ := json.Marshal(vip.Labels)
patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw)
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Patch(context.Background(), vip.Name,
types.JSONPatchType, []byte(patchPayload), metav1.PatchOptions{}); err != nil {
klog.Errorf("failed to patch label for vip '%s', %v", vip.Name, err)
return err
}
if _, _, _, err = c.ipam.GetStaticAddress(key, vip.Name, vip.Status.V4ip, vip.Status.Mac, vip.Spec.Subnet, false); err != nil {
klog.Errorf("failed to recover IPAM from VIP CR %s: %v", vip.Name, err)
}
c.updateSubnetStatusQueue.Add(vip.Spec.Subnet)
}
return nil
}
func (c *Controller) handleAddVipFinalizer(key string) error {
cachedVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if cachedVip.DeletionTimestamp.IsZero() {
if util.ContainsString(cachedVip.Finalizers, util.ControllerName) {
return nil
}
}
newVip := cachedVip.DeepCopy()
controllerutil.AddFinalizer(newVip, util.ControllerName)
patch, err := util.GenerateMergePatchPayload(cachedVip, newVip)
if err != nil {
klog.Errorf("failed to generate patch payload for ovn eip '%s', %v", cachedVip.Name, err)
return err
}
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Patch(context.Background(), cachedVip.Name,
types.MergePatchType, patch, metav1.PatchOptions{}, ""); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Errorf("failed to add finalizer for vip '%s', %v", cachedVip.Name, err)
return err
}
return nil
}
func (c *Controller) handleDelVipFinalizer(key string) error {
cachedVip, err := c.virtualIpsLister.Get(key)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
if len(cachedVip.Finalizers) == 0 {
return nil
}
newVip := cachedVip.DeepCopy()
controllerutil.RemoveFinalizer(newVip, util.ControllerName)
patch, err := util.GenerateMergePatchPayload(cachedVip, newVip)
if err != nil {
klog.Errorf("failed to generate patch payload for ovn eip '%s', %v", cachedVip.Name, err)
return err
}
if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Patch(context.Background(), cachedVip.Name,
types.MergePatchType, patch, metav1.PatchOptions{}, ""); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Errorf("failed to remove finalizer from vip '%s', %v", cachedVip.Name, err)
return err
}
return nil
}