/
pod.go
656 lines (594 loc) · 20 KB
/
pod.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package controller
import (
"encoding/json"
"fmt"
"net"
"reflect"
"strconv"
"strings"
"github.com/juju/errors"
"github.com/alauda/kube-ovn/pkg/ovs"
"github.com/alauda/kube-ovn/pkg/util"
v1 "k8s.io/api/core/v1"
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"
)
func (c *Controller) enqueueAddPod(obj interface{}) {
if !c.isLeader() {
return
}
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
p := obj.(*v1.Pod)
if p.Annotations[util.IpPoolAnnotation] != "" && p.Annotations[util.IpAddressAnnotation] == "" {
klog.V(3).Infof("enqueue add ip pool address pod %s", key)
c.addIpPoolPodQueue.AddRateLimited(key)
return
}
klog.V(3).Infof("enqueue add pod %s", key)
c.addPodQueue.AddRateLimited(key)
// TODO: we need to find a way to reduce duplicated np added to the queue
if p.Status.PodIP != "" {
for _, np := range c.podMatchNetworkPolicies(p) {
c.updateNpQueue.AddRateLimited(np)
}
}
}
func (c *Controller) enqueueDeletePod(obj interface{}) {
if !c.isLeader() {
return
}
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
klog.V(3).Infof("enqueue delete pod %s", key)
c.deletePodQueue.AddRateLimited(key)
p := obj.(*v1.Pod)
for _, np := range c.podMatchNetworkPolicies(p) {
c.updateNpQueue.AddRateLimited(np)
}
}
func (c *Controller) enqueueUpdatePod(oldObj, newObj interface{}) {
if !c.isLeader() {
return
}
oldPod := oldObj.(*v1.Pod)
newPod := newObj.(*v1.Pod)
if oldPod.ResourceVersion == newPod.ResourceVersion {
return
}
// pod assigned an ip
if oldPod.Status.PodIP == "" && newPod.Status.PodIP != "" {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil {
utilruntime.HandleError(err)
return
}
klog.V(3).Infof("enqueue update pod %s", key)
c.updatePodQueue.AddRateLimited(key)
}
if oldPod.Status.PodIP != newPod.Status.PodIP {
for _, np := range c.podMatchNetworkPolicies(newPod) {
c.updateNpQueue.AddRateLimited(np)
}
return
}
if !reflect.DeepEqual(oldPod.Labels, newPod.Labels) {
oldNp := c.podMatchNetworkPolicies(oldPod)
newNp := c.podMatchNetworkPolicies(newPod)
for _, np := range util.DiffStringSlice(oldNp, newNp) {
c.updateNpQueue.AddRateLimited(np)
}
}
}
// runWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// workqueue.
func (c *Controller) runAddPodWorker() {
for c.processNextAddPodWorkItem() {
}
}
func (c *Controller) runAddIpPoolPodWorker() {
for c.processNextAddIpPoolPodWorkItem() {
}
}
// runWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// workqueue.
func (c *Controller) runDeletePodWorker() {
for c.processNextDeletePodWorkItem() {
}
}
func (c *Controller) runUpdatePodWorker() {
for c.processNextUpdatePodWorkItem() {
}
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextAddPodWorkItem() bool {
obj, shutdown := c.addPodQueue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being re-queued. For example, we do
// not call Forget if a transient error occurs, instead the item is
// put back on the workqueue and attempted again after a back-off
// period.
defer c.addPodQueue.Done(obj)
var key string
var ok bool
// We expect strings to come off the workqueue. These are of the
// form namespace/name. We do this as the delayed nature of the
// workqueue means the items in the informer cache may actually be
// more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.addPodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
// Run the syncHandler, passing it the namespace/name string of the
// Foo resource to be synced.
if err := c.handleAddPod(key); err != nil {
// Put the item back on the workqueue to handle any transient errors.
c.addPodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
// Finally, if no error occurs we Forget this item so it does not
// get queued again until another change happens.
c.addPodQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextAddIpPoolPodWorkItem() bool {
obj, shutdown := c.addIpPoolPodQueue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being re-queued. For example, we do
// not call Forget if a transient error occurs, instead the item is
// put back on the workqueue and attempted again after a back-off
// period.
defer c.addIpPoolPodQueue.Done(obj)
var key string
var ok bool
// We expect strings to come off the workqueue. These are of the
// form namespace/name. We do this as the delayed nature of the
// workqueue means the items in the informer cache may actually be
// more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.addIpPoolPodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
// Run the syncHandler, passing it the namespace/name string of the
// Foo resource to be synced.
if err := c.handleAddIpPoolPod(key); err != nil {
// Put the item back on the workqueue to handle any transient errors.
c.addIpPoolPodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
// Finally, if no error occurs we Forget this item so it does not
// get queued again until another change happens.
c.addIpPoolPodQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextDeletePodWorkItem() bool {
obj, shutdown := c.deletePodQueue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being re-queued. For example, we do
// not call Forget if a transient error occurs, instead the item is
// put back on the workqueue and attempted again after a back-off
// period.
defer c.deletePodQueue.Done(obj)
var key string
var ok bool
// We expect strings to come off the workqueue. These are of the
// form namespace/name. We do this as the delayed nature of the
// workqueue means the items in the informer cache may actually be
// more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.deletePodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
// Run the syncHandler, passing it the namespace/name string of the
// Foo resource to be synced.
if err := c.handleDeletePod(key); err != nil {
// Put the item back on the workqueue to handle any transient errors.
c.deletePodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
// Finally, if no error occurs we Forget this item so it does not
// get queued again until another change happens.
c.deletePodQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextUpdatePodWorkItem() bool {
obj, shutdown := c.updatePodQueue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being re-queued. For example, we do
// not call Forget if a transient error occurs, instead the item is
// put back on the workqueue and attempted again after a back-off
// period.
defer c.updatePodQueue.Done(obj)
var key string
var ok bool
// We expect strings to come off the workqueue. These are of the
// form namespace/name. We do this as the delayed nature of the
// workqueue means the items in the informer cache may actually be
// more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.updatePodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
// Run the syncHandler, passing it the namespace/name string of the
// Foo resource to be synced.
if err := c.handleUpdatePod(key); err != nil {
// Put the item back on the workqueue to handle any transient errors.
c.updatePodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
// Finally, if no error occurs we Forget this item so it does not
// get queued again until another change happens.
c.updatePodQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) handleAddPod(key string) error {
// Convert the namespace/name string into a distinct namespace and name
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
pod, err := c.podsLister.Pods(namespace).Get(name)
if err != nil {
// The Pod resource may no longer exist, in which case we stop
// processing.
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
klog.Infof("add pod %s/%s", namespace, name)
if pod.Spec.HostNetwork {
klog.Infof("pod %s/%s in host network mode no need for ovn process", namespace, name)
return nil
}
ns, err := c.namespacesLister.Get(namespace)
if err != nil {
klog.Errorf("get namespace %s failed %v", namespace, err)
return err
}
ls := ns.Annotations[util.LogicalSwitchAnnotation]
if ls == "" {
ls = c.config.DefaultLogicalSwitch
}
if err := util.ValidatePodNetwork(pod.Annotations); err != nil {
klog.Errorf("validate pod %s/%s failed, %v", namespace, name, err)
c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
return err
}
// pod address info may already exist in ovn
ip := pod.Annotations[util.IpAddressAnnotation]
mac := pod.Annotations[util.MacAddressAnnotation]
nic, err := c.ovnClient.CreatePort(ls, ovs.PodNameToPortName(name, namespace), ip, mac)
if err != nil {
return err
}
op := "replace"
if len(pod.Annotations) == 0 {
op = "add"
}
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[util.IpAddressAnnotation] = nic.IpAddress
pod.Annotations[util.MacAddressAnnotation] = nic.MacAddress
pod.Annotations[util.CidrAnnotation] = nic.CIDR
pod.Annotations[util.GatewayAnnotation] = nic.Gateway
pod.Annotations[util.LogicalSwitchAnnotation] = ls
patchPayloadTemplate :=
`[{
"op": "%s",
"path": "/metadata/annotations",
"value": %s
}]`
raw, _ := json.Marshal(pod.Annotations)
patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw)
_, err = c.kubeclientset.CoreV1().Pods(namespace).Patch(name, types.JSONPatchType, []byte(patchPayload))
if err != nil {
klog.Errorf("patch pod %s/%s failed %v", name, namespace, err)
}
return err
}
func (c *Controller) handleAddIpPoolPod(key string) error {
// Convert the namespace/name string into a distinct namespace and name
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
pod, err := c.podsLister.Pods(namespace).Get(name)
if err != nil {
// The Pod resource may no longer exist, in which case we stop
// processing.
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
klog.Infof("add ip pool address pod %s/%s", namespace, name)
if pod.Spec.HostNetwork {
klog.Infof("pod %s/%s in host network mode no need for ovn process", namespace, name)
return nil
}
ns, err := c.namespacesLister.Get(namespace)
if err != nil {
klog.Errorf("get namespace %s failed %v", namespace, err)
return err
}
ls := ns.Annotations[util.LogicalSwitchAnnotation]
if ls == "" {
ls = c.config.DefaultLogicalSwitch
}
ipPoolAnnotation := pod.Annotations[util.IpPoolAnnotation]
if ipPoolAnnotation != "" && pod.Annotations[util.IpAddressAnnotation] == "" {
ipPool := strings.Split(pod.Annotations[util.IpPoolAnnotation], ",")
if isStatefulSetPod(pod) {
numIndex := len(strings.Split(pod.Name, "-")) - 1
numStr := strings.Split(pod.Name, "-")[numIndex]
index, _ := strconv.Atoi(numStr)
if index < len(ipPool) {
pod.Annotations[util.IpAddressAnnotation] = ipPool[index]
}
} else {
for _, ip := range ipPool {
if net.ParseIP(ip) == nil {
continue
}
pods, err := c.kubeclientset.CoreV1().Pods(v1.NamespaceAll).List(metav1.ListOptions{})
if err != nil {
klog.Errorf("failed to list pod %v", err)
return err
}
used := false
for _, existPod := range pods.Items {
// use annotation to get exist ips, as podIp may not exist in this interval
if strings.Split(existPod.Annotations[util.IpAddressAnnotation], "/")[0] == ip {
used = true
break
}
}
if !used {
pod.Annotations[util.IpAddressAnnotation] = ip
break
}
}
}
if pod.Annotations[util.IpAddressAnnotation] == "" {
klog.Errorf("no unused ip for pod %s", key)
c.recorder.Event(pod, v1.EventTypeWarning, "FailedAllocateIP", "no unused ip")
return fmt.Errorf("no unused ip for pod %s", key)
}
}
// pod address info may already exist in ovn
ip := pod.Annotations[util.IpAddressAnnotation]
mac := pod.Annotations[util.MacAddressAnnotation]
nic, err := c.ovnClient.CreatePort(ls, ovs.PodNameToPortName(name, namespace), ip, mac)
if err != nil {
return err
}
op := "replace"
if len(pod.Annotations) == 0 {
op = "add"
}
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[util.IpAddressAnnotation] = nic.IpAddress
pod.Annotations[util.MacAddressAnnotation] = nic.MacAddress
pod.Annotations[util.CidrAnnotation] = nic.CIDR
pod.Annotations[util.GatewayAnnotation] = nic.Gateway
pod.Annotations[util.LogicalSwitchAnnotation] = ls
patchPayloadTemplate :=
`[{
"op": "%s",
"path": "/metadata/annotations",
"value": %s
}]`
raw, _ := json.Marshal(pod.Annotations)
patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw)
_, err = c.kubeclientset.CoreV1().Pods(namespace).Patch(name, types.JSONPatchType, []byte(patchPayload))
if err != nil {
klog.Errorf("patch pod %s/%s failed %v", name, namespace, err)
}
return err
}
func (c *Controller) handleDeletePod(key string) error {
// Convert the namespace/name string into a distinct namespace and name
namespace, name, err := cache.SplitMetaNamespaceKey(key)
klog.Infof("delete pod %s/%s", namespace, name)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
portAddr, err := c.ovnClient.GetPortAddr(ovs.PodNameToPortName(name, namespace))
if err != nil {
if !strings.Contains(err.Error(), "no row") {
return err
}
} else {
if err := c.ovnClient.DeleteStaticRouter(portAddr[1], c.config.ClusterRouter); err != nil {
return err
}
}
pod, err := c.podsLister.Pods(namespace).Get(name)
if err != nil {
// The Pod resource may no longer exist, in this case we stop
// processing.
if k8serrors.IsNotFound(err) {
return c.ovnClient.DeletePort(ovs.PodNameToPortName(name, namespace))
}
return err
}
if pod.Spec.HostNetwork {
klog.Infof("pod %s/%s in host network mode no need for ovn process", pod.Namespace, pod.Name)
return nil
}
// for statefulset pod, names are same when updating, so double check to make sure the pod is to be deleted
if pod.DeletionTimestamp != nil {
return c.ovnClient.DeletePort(ovs.PodNameToPortName(name, namespace))
}
return nil
}
func (c *Controller) handleUpdatePod(key string) error {
// Convert the namespace/name string into a distinct namespace and name
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
pod, err := c.podsLister.Pods(namespace).Get(name)
if err != nil {
// The Pod resource may no longer exist, in which case we stop
// processing.
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
klog.Infof("update pod %s/%s", namespace, name)
if pod.Spec.HostNetwork {
klog.Infof("pod %s/%s in host network mode no need for ovn process", namespace, name)
return nil
}
ns, err := c.namespacesLister.Get(namespace)
if err != nil {
klog.Errorf("get namespace %s failed %v", namespace, err)
return err
}
nsGWType := ns.Annotations[util.GWTypeAnnotation]
switch nsGWType {
case "", util.GWDistributedMode:
node, err := c.nodesLister.Get(pod.Spec.NodeName)
if err != nil {
klog.Errorf("get node %s failed %v", pod.Spec.NodeName, err)
return err
}
nodeTunlIPAddr, err := getNodeTunlIP(node)
if err != nil {
return err
}
if err := c.ovnClient.AddStaticRouter(ovs.PolicySrcIP, pod.Status.PodIP, nodeTunlIPAddr.String(), c.config.ClusterRouter); err != nil {
return errors.Annotate(err, "add static route failed")
}
case util.GWCentralizedMode:
gatewayNode := ns.Annotations[util.GWNode]
node, err := c.nodesLister.Get(gatewayNode)
if err != nil {
klog.Errorf("get node %s failed %v", pod.Spec.NodeName, err)
return err
}
nodeTunlIPAddr, err := getNodeTunlIP(node)
if err != nil {
return err
}
if err := c.ovnClient.AddStaticRouter(ovs.PolicySrcIP, pod.Status.PodIP, nodeTunlIPAddr.String(), c.config.ClusterRouter); err != nil {
return errors.Annotate(err, "add static route failed")
}
}
return nil
}
func isStatefulSetPod(pod *v1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "StatefulSet" {
return true
}
}
return false
}
func getNodeTunlIP(node *v1.Node) (net.IP, error) {
nodeTunlIP := node.Annotations[util.IpAddressAnnotation]
if nodeTunlIP == "" {
return nil, errors.New("node has no tunl ip annotation")
}
nodeTunlIPAddr := net.ParseIP(nodeTunlIP)
if nodeTunlIPAddr == nil {
return nil, fmt.Errorf("failed to parse node tunl ip %s", nodeTunlIP)
}
return nodeTunlIPAddr, nil
}