-
Notifications
You must be signed in to change notification settings - Fork 129
/
gateway_shared_intf.go
1886 lines (1689 loc) · 77.8 KB
/
gateway_shared_intf.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package node
import (
"fmt"
"hash/fnv"
"net"
"reflect"
"strings"
"sync"
"github.com/coreos/go-iptables/iptables"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/config"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/factory"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/kube"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/types"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/util"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
kapi "k8s.io/api/core/v1"
discovery "k8s.io/api/discovery/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
ktypes "k8s.io/apimachinery/pkg/types"
apierrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2"
utilnet "k8s.io/utils/net"
)
const (
// defaultOpenFlowCookie identifies default open flow rules added to the host OVS bridge.
// The hex number 0xdeff105, aka defflos, is meant to sound like default flows.
defaultOpenFlowCookie = "0xdeff105"
// etpSvcOpenFlowCookie identifies constant open flow rules added to the host OVS
// bridge to move packets between host and external for etp=local traffic.
// The hex number 0xe745ecf105, represents etp(e74)-service(5ec)-flows which makes it easier for debugging.
etpSvcOpenFlowCookie = "0xe745ecf105"
// ovsLocalPort is the name of the OVS bridge local port
ovsLocalPort = "LOCAL"
// ctMarkOVN is the conntrack mark value for OVN traffic
ctMarkOVN = "0x1"
// ctMarkHost is the conntrack mark value for host traffic
ctMarkHost = "0x2"
// ovnkubeITPMark is the fwmark used for host->ITP=local svc traffic. Note that the fwmark is not a part
// of the packet, but just stored by kernel in its memory to track/filter packet. Hence fwmark is lost as
// soon as packet exits the host.
ovnkubeITPMark = "0x1745ec" // constant itp(174)-service(5ec)
// ovnkubeSvcViaMgmPortRT is the number of the custom routing table used to steer host->service
// traffic packets into OVN via ovn-k8s-mp0. Currently only used for ITP=local traffic.
ovnkubeSvcViaMgmPortRT = "7"
)
var (
HostMasqCTZone = config.Default.ConntrackZone + 1 //64001
OVNMasqCTZone = HostMasqCTZone + 1 //64002
HostNodePortCTZone = config.Default.ConntrackZone + 3 //64003
)
// nodePortWatcherIptables manages iptables rules for shared gateway
// to ensure that services using NodePorts are accessible.
type nodePortWatcherIptables struct {
}
func newNodePortWatcherIptables() *nodePortWatcherIptables {
return &nodePortWatcherIptables{}
}
// nodePortWatcher manages OpenFlow and iptables rules
// to ensure that services using NodePorts are accessible
type nodePortWatcher struct {
dpuMode bool
gatewayIPv4 string
gatewayIPv6 string
ofportPhys string
ofportPatch string
gwBridge string
nodeName string
// Map of service name to programmed iptables/OF rules
serviceInfo map[ktypes.NamespacedName]*serviceConfig
serviceInfoLock sync.Mutex
egressServiceInfo map[ktypes.NamespacedName]*serviceEps
egressServiceInfoLock sync.Mutex
ofm *openflowManager
nodeIPManager *addressManager
watchFactory factory.NodeWatchFactory
}
type serviceConfig struct {
// Contains the current service
service *kapi.Service
// hasLocalHostNetworkEp will be true for a service if it has at least one endpoint which is "hostnetworked&local-to-this-node".
hasLocalHostNetworkEp bool
}
type serviceEps struct {
v4 sets.String
v6 sets.String
}
type cidrAndFlags struct {
ipNet *net.IPNet
flags int
}
// updateServiceFlowCache handles managing breth0 gateway flows for ingress traffic towards kubernetes services
// (nodeport, external, ingress). By default incoming traffic into the node is steered directly into OVN (case3 below).
//
// case1: If a service has externalTrafficPolicy=local, and has host-networked endpoints local to the node (hasLocalHostNetworkEp),
// traffic instead will be steered directly into the host and DNAT-ed to the targetPort on the host.
//
// case2: All other types of services in SGW mode i.e:
//
// case2a: if externalTrafficPolicy=cluster + SGW mode, traffic will be steered into OVN via GR.
// case2b: if externalTrafficPolicy=local + !hasLocalHostNetworkEp + SGW mode, traffic will be steered into OVN via GR.
//
// NOTE: If LGW mode, the default flow will take care of sending traffic to host irrespective of service flow type.
//
// `add` parameter indicates if the flows should exist or be removed from the cache
// `hasLocalHostNetworkEp` indicates if at least one host networked endpoint exists for this service which is local to this node.
func (npw *nodePortWatcher) updateServiceFlowCache(service *kapi.Service, add, hasLocalHostNetworkEp bool) error {
var cookie, key string
var err error
var errors []error
isServiceTypeETPLocal := util.ServiceExternalTrafficPolicyLocal(service)
actions := fmt.Sprintf("output:%s", npw.ofportPatch)
// cookie is only used for debugging purpose. so it is not fatal error if cookie is failed to be generated.
for _, svcPort := range service.Spec.Ports {
protocol := strings.ToLower(string(svcPort.Protocol))
if svcPort.NodePort > 0 {
flowProtocols := []string{}
if config.IPv4Mode {
flowProtocols = append(flowProtocols, protocol)
}
if config.IPv6Mode {
flowProtocols = append(flowProtocols, protocol+"6")
}
for _, flowProtocol := range flowProtocols {
cookie, err = svcToCookie(service.Namespace, service.Name, flowProtocol, svcPort.NodePort)
if err != nil {
klog.Warningf("Unable to generate cookie for nodePort svc: %s, %s, %s, %d, error: %v",
service.Namespace, service.Name, flowProtocol, svcPort.Port, err)
cookie = "0"
}
key = strings.Join([]string{"NodePort", service.Namespace, service.Name, flowProtocol, fmt.Sprintf("%d", svcPort.NodePort)}, "_")
// Delete if needed and skip to next protocol
if !add {
npw.ofm.deleteFlowsByKey(key)
continue
}
// This allows external traffic ingress when the svc's ExternalTrafficPolicy is
// set to Local, and the backend pod is HostNetworked. We need to add
// Flows that will DNAT all traffic coming into nodeport to the nodeIP:Port and
// ensure that the return traffic is UnDNATed to correct the nodeIP:Nodeport
if isServiceTypeETPLocal && hasLocalHostNetworkEp {
// case1 (see function description for details)
var nodeportFlows []string
klog.V(5).Infof("Adding flows on breth0 for Nodeport Service %s in Namespace: %s since ExternalTrafficPolicy=local", service.Name, service.Namespace)
// table 0, This rule matches on all traffic with dst port == NodePort, DNAT's the nodePort to the svc targetPort
// If ipv6 make sure to choose the ipv6 node address for rule
if strings.Contains(flowProtocol, "6") {
nodeportFlows = append(nodeportFlows,
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_dst=%d, actions=ct(commit,zone=%d,nat(dst=[%s]:%s),table=6)",
cookie, npw.ofportPhys, flowProtocol, svcPort.NodePort, HostNodePortCTZone, npw.gatewayIPv6, svcPort.TargetPort.String()))
} else {
nodeportFlows = append(nodeportFlows,
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_dst=%d, actions=ct(commit,zone=%d,nat(dst=%s:%s),table=6)",
cookie, npw.ofportPhys, flowProtocol, svcPort.NodePort, HostNodePortCTZone, npw.gatewayIPv4, svcPort.TargetPort.String()))
}
nodeportFlows = append(nodeportFlows,
// table 6, Sends the packet to the host. Note that the constant etp svc cookie is used since this flow would be
// same for all such services.
fmt.Sprintf("cookie=%s, priority=110, table=6, actions=output:LOCAL",
etpSvcOpenFlowCookie),
// table 0, Matches on return traffic, i.e traffic coming from the host networked pod's port, and unDNATs
fmt.Sprintf("cookie=%s, priority=110, in_port=LOCAL, %s, tp_src=%s, actions=ct(zone=%d nat,table=7)",
cookie, flowProtocol, svcPort.TargetPort.String(), HostNodePortCTZone),
// table 7, Sends the packet back out eth0 to the external client. Note that the constant etp svc
// cookie is used since this would be same for all such services.
fmt.Sprintf("cookie=%s, priority=110, table=7, "+
"actions=output:%s", etpSvcOpenFlowCookie, npw.ofportPhys))
npw.ofm.updateFlowCacheEntry(key, nodeportFlows)
} else if config.Gateway.Mode == config.GatewayModeShared {
// case2 (see function description for details)
npw.ofm.updateFlowCacheEntry(key, []string{
// table=0, matches on service traffic towards nodePort and sends it to OVN pipeline
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_dst=%d, "+
"actions=%s",
cookie, npw.ofportPhys, flowProtocol, svcPort.NodePort, actions),
// table=0, matches on return traffic from service nodePort and sends it out to primary node interface (br-ex)
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_src=%d, "+
"actions=output:%s",
cookie, npw.ofportPatch, flowProtocol, svcPort.NodePort, npw.ofportPhys)})
}
}
}
// Flows for cloud load balancers on Azure/GCP
// Established traffic is handled by default conntrack rules
// NodePort/Ingress access in the OVS bridge will only ever come from outside of the host
for _, ing := range service.Status.LoadBalancer.Ingress {
if len(ing.IP) > 0 {
if err = npw.createLbAndExternalSvcFlows(service, &svcPort, add, hasLocalHostNetworkEp, protocol, actions, utilnet.ParseIPSloppy(ing.IP).String(), "Ingress"); err != nil {
errors = append(errors, err)
}
}
}
// flows for externalIPs
for _, externalIP := range service.Spec.ExternalIPs {
if err = npw.createLbAndExternalSvcFlows(service, &svcPort, add, hasLocalHostNetworkEp, protocol, actions, utilnet.ParseIPSloppy(externalIP).String(), "External"); err != nil {
errors = append(errors, err)
}
}
}
return apierrors.NewAggregate(errors)
}
// createLbAndExternalSvcFlows handles managing breth0 gateway flows for ingress traffic towards kubernetes services
// (externalIP and LoadBalancer types). By default incoming traffic into the node is steered directly into OVN (case3 below).
//
// case1: If a service has externalTrafficPolicy=local, and has host-networked endpoints local to the node (hasLocalHostNetworkEp),
// traffic instead will be steered directly into the host and DNAT-ed to the targetPort on the host.
//
// case2: All other types of services in SGW mode i.e:
//
// case2a: if externalTrafficPolicy=cluster + SGW mode, traffic will be steered into OVN via GR.
// case2b: if externalTrafficPolicy=local + !hasLocalHostNetworkEp + SGW mode, traffic will be steered into OVN via GR.
//
// NOTE: If LGW mode, the default flow will take care of sending traffic to host irrespective of service flow type.
//
// `add` parameter indicates if the flows should exist or be removed from the cache
// `hasLocalHostNetworkEp` indicates if at least one host networked endpoint exists for this service which is local to this node.
// `protocol` is TCP/UDP/SCTP as set in the svc.Port
// `actions`: "send to patchport"
// `externalIPOrLBIngressIP` is either externalIP.IP or LB.status.ingress.IP
// `ipType` is either "External" or "Ingress"
func (npw *nodePortWatcher) createLbAndExternalSvcFlows(service *kapi.Service, svcPort *kapi.ServicePort, add bool, hasLocalHostNetworkEp bool, protocol string, actions string, externalIPOrLBIngressIP string, ipType string) error {
if net.ParseIP(externalIPOrLBIngressIP) == nil {
return fmt.Errorf("failed to parse %s IP: %q", ipType, externalIPOrLBIngressIP)
}
flowProtocol := protocol
nwDst := "nw_dst"
nwSrc := "nw_src"
if utilnet.IsIPv6String(externalIPOrLBIngressIP) {
flowProtocol = protocol + "6"
nwDst = "ipv6_dst"
nwSrc = "ipv6_src"
}
cookie, err := svcToCookie(service.Namespace, service.Name, externalIPOrLBIngressIP, svcPort.Port)
if err != nil {
klog.Warningf("Unable to generate cookie for %s svc: %s, %s, %s, %d, error: %v",
ipType, service.Namespace, service.Name, externalIPOrLBIngressIP, svcPort.Port, err)
cookie = "0"
}
key := strings.Join([]string{ipType, service.Namespace, service.Name, externalIPOrLBIngressIP, fmt.Sprintf("%d", svcPort.Port)}, "_")
// Delete if needed and skip to next protocol
if !add {
npw.ofm.deleteFlowsByKey(key)
return nil
}
// add the ARP bypass flow regardless of service type or gateway modes since its applicable in all scenarios.
arpFlow := npw.generateArpBypassFlow(protocol, externalIPOrLBIngressIP, cookie)
externalIPFlows := []string{arpFlow}
// This allows external traffic ingress when the svc's ExternalTrafficPolicy is
// set to Local, and the backend pod is HostNetworked. We need to add
// Flows that will DNAT all external traffic destined for the lb/externalIP service
// to the nodeIP / nodeIP:port of the host networked backend.
// And then ensure that return traffic is UnDNATed correctly back
// to the ingress / external IP
isServiceTypeETPLocal := util.ServiceExternalTrafficPolicyLocal(service)
if isServiceTypeETPLocal && hasLocalHostNetworkEp {
// case1 (see function description for details)
klog.V(5).Infof("Adding flows on breth0 for %s Service %s in Namespace: %s since ExternalTrafficPolicy=local", ipType, service.Name, service.Namespace)
// table 0, This rule matches on all traffic with dst ip == LoadbalancerIP / externalIP, DNAT's the nodePort to the svc targetPort
// If ipv6 make sure to choose the ipv6 node address for rule
if strings.Contains(flowProtocol, "6") {
externalIPFlows = append(externalIPFlows,
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, tp_dst=%d, actions=ct(commit,zone=%d,nat(dst=[%s]:%s),table=6)",
cookie, npw.ofportPhys, flowProtocol, nwDst, externalIPOrLBIngressIP, svcPort.Port, HostNodePortCTZone, npw.gatewayIPv6, svcPort.TargetPort.String()))
} else {
externalIPFlows = append(externalIPFlows,
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, tp_dst=%d, actions=ct(commit,zone=%d,nat(dst=%s:%s),table=6)",
cookie, npw.ofportPhys, flowProtocol, nwDst, externalIPOrLBIngressIP, svcPort.Port, HostNodePortCTZone, npw.gatewayIPv4, svcPort.TargetPort.String()))
}
externalIPFlows = append(externalIPFlows,
// table 6, Sends the packet to Host. Note that the constant etp svc cookie is used since this flow would be
// same for all such services.
fmt.Sprintf("cookie=%s, priority=110, table=6, actions=output:LOCAL",
etpSvcOpenFlowCookie),
// table 0, Matches on return traffic, i.e traffic coming from the host networked pod's port, and unDNATs
fmt.Sprintf("cookie=%s, priority=110, in_port=LOCAL, %s, tp_src=%s, actions=ct(commit,zone=%d nat,table=7)",
cookie, flowProtocol, svcPort.TargetPort.String(), HostNodePortCTZone),
// table 7, Sends the reply packet back out eth0 to the external client. Note that the constant etp svc
// cookie is used since this would be same for all such services.
fmt.Sprintf("cookie=%s, priority=110, table=7, actions=output:%s",
etpSvcOpenFlowCookie, npw.ofportPhys))
} else if config.Gateway.Mode == config.GatewayModeShared {
// case2 (see function description for details)
externalIPFlows = append(externalIPFlows,
// table=0, matches on service traffic towards externalIP or LB ingress and sends it to OVN pipeline
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, tp_dst=%d, "+
"actions=%s",
cookie, npw.ofportPhys, flowProtocol, nwDst, externalIPOrLBIngressIP, svcPort.Port, actions),
// table=0, matches on return traffic from service externalIP or LB ingress and sends it out to primary node interface (br-ex)
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, tp_src=%d, "+
"actions=output:%s",
cookie, npw.ofportPatch, flowProtocol, nwSrc, externalIPOrLBIngressIP, svcPort.Port, npw.ofportPhys))
}
npw.ofm.updateFlowCacheEntry(key, externalIPFlows)
return nil
}
// generate ARP/NS bypass flow which will send the ARP/NS request everywhere *but* to OVN
// OpenFlow will not do hairpin switching, so we can safely add the origin port to the list of ports, too
func (npw *nodePortWatcher) generateArpBypassFlow(protocol string, ipAddr string, cookie string) string {
addrResDst := "arp_tpa"
addrResProto := "arp, arp_op=1"
if utilnet.IsIPv6String(ipAddr) {
addrResDst = "nd_target"
addrResProto = "icmp6, icmp_type=135, icmp_code=0"
}
var arpFlow string
var arpPortsFiltered []string
arpPorts, err := util.GetOpenFlowPorts(npw.gwBridge, false)
if err != nil {
// in the odd case that getting all ports from the bridge should not work,
// simply output to LOCAL (this should work well in the vast majority of cases, anyway)
klog.Warningf("Unable to get port list from bridge. Using ovsLocalPort as output only: error: %v",
err)
arpFlow = fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, "+
"actions=output:%s",
cookie, npw.ofportPhys, addrResProto, addrResDst, ipAddr, ovsLocalPort)
} else {
// cover the case where breth0 has more than 3 ports, e.g. if an admin adds a 4th port
// and the ExternalIP would be on that port
// Use all ports except for ofPortPhys and the ofportPatch
// Filtering ofPortPhys is for consistency / readability only, OpenFlow will not send
// out the in_port normally (see man 7 ovs-actions)
for _, port := range arpPorts {
if port == npw.ofportPatch || port == npw.ofportPhys {
continue
}
arpPortsFiltered = append(arpPortsFiltered, port)
}
arpFlow = fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, "+
"actions=output:%s",
cookie, npw.ofportPhys, addrResProto, addrResDst, ipAddr, strings.Join(arpPortsFiltered, ","))
}
return arpFlow
}
// getAndDeleteServiceInfo returns the serviceConfig for a service and if it exists and then deletes the entry
func (npw *nodePortWatcher) getAndDeleteServiceInfo(index ktypes.NamespacedName) (out *serviceConfig, exists bool) {
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
out, exists = npw.serviceInfo[index]
delete(npw.serviceInfo, index)
return out, exists
}
// getServiceInfo returns the serviceConfig for a service and if it exists
func (npw *nodePortWatcher) getServiceInfo(index ktypes.NamespacedName) (out *serviceConfig, exists bool) {
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
out, exists = npw.serviceInfo[index]
return out, exists
}
// getAndSetServiceInfo creates and sets the serviceConfig, returns if it existed and whatever was there
func (npw *nodePortWatcher) getAndSetServiceInfo(index ktypes.NamespacedName, service *kapi.Service, hasLocalHostNetworkEp bool) (old *serviceConfig, exists bool) {
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
old, exists = npw.serviceInfo[index]
npw.serviceInfo[index] = &serviceConfig{service: service, hasLocalHostNetworkEp: hasLocalHostNetworkEp}
return old, exists
}
// addOrSetServiceInfo creates and sets the serviceConfig if it doesn't exist
func (npw *nodePortWatcher) addOrSetServiceInfo(index ktypes.NamespacedName, service *kapi.Service, hasLocalHostNetworkEp bool) (exists bool) {
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
if _, exists := npw.serviceInfo[index]; !exists {
// Only set this if it doesn't exist
npw.serviceInfo[index] = &serviceConfig{service: service, hasLocalHostNetworkEp: hasLocalHostNetworkEp}
return false
}
return true
}
// updateServiceInfo sets the serviceConfig for a service and returns the existing serviceConfig, if inputs are nil
// do not update those fields, if it does not exist return nil.
func (npw *nodePortWatcher) updateServiceInfo(index ktypes.NamespacedName, service *kapi.Service, hasLocalHostNetworkEp *bool) (old *serviceConfig, exists bool) {
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
if old, exists = npw.serviceInfo[index]; !exists {
klog.V(5).Infof("No serviceConfig found for service %s in namespace %s", index.Name, index.Namespace)
return nil, exists
}
if service != nil {
npw.serviceInfo[index].service = service
}
if hasLocalHostNetworkEp != nil {
npw.serviceInfo[index].hasLocalHostNetworkEp = *hasLocalHostNetworkEp
}
return old, exists
}
// addServiceRules ensures the correct iptables rules and OpenFlow physical
// flows are programmed for a given service and endpoint configuration
func addServiceRules(service *kapi.Service, svcHasLocalHostNetEndPnt bool, npw *nodePortWatcher) error {
// For dpu or Full mode
var err error
var errors []error
if npw != nil {
if err = npw.updateServiceFlowCache(service, true, svcHasLocalHostNetEndPnt); err != nil {
errors = append(errors, err)
}
npw.ofm.requestFlowSync()
if !npw.dpuMode {
// add iptable rules only in full mode
if err = addGatewayIptRules(service, svcHasLocalHostNetEndPnt); err != nil {
errors = append(errors, err)
}
if err = updateEgressSVCIptRules(service, npw); err != nil {
errors = append(errors, err)
}
}
} else {
// For Host Only Mode
if err = addGatewayIptRules(service, svcHasLocalHostNetEndPnt); err != nil {
errors = append(errors, err)
}
}
return apierrors.NewAggregate(errors)
}
// delServiceRules deletes all possible iptables rules and OpenFlow physical
// flows for a service
func delServiceRules(service *kapi.Service, npw *nodePortWatcher) error {
var err error
var errors []error
// full mode || dpu mode
if npw != nil {
if err = npw.updateServiceFlowCache(service, false, false); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
npw.ofm.requestFlowSync()
if !npw.dpuMode {
// Always try and delete all rules here in full mode & in host only mode. We don't touch iptables in dpu mode.
// +--------------------------+-----------------------+-----------------------+--------------------------------+
// | svcHasLocalHostNetEndPnt | ExternalTrafficPolicy | InternalTrafficPolicy | Scenario for deletion |
// |--------------------------|-----------------------|-----------------------|--------------------------------|
// | | | | deletes the MARK |
// | false | cluster | local | rules for itp=local |
// | | | | called from mangle |
// |--------------------------|-----------------------|-----------------------|--------------------------------|
// | | | | deletes the REDIRECT |
// | true | cluster | local | rules towards target |
// | | | | port for itp=local |
// |--------------------------|-----------------------|-----------------------|--------------------------------|
// | | | | deletes the DNAT rules for |
// | false | local | cluster | non-local-host-net |
// | | | | eps towards masqueradeIP + |
// | | | | DNAT rules towards clusterIP |
// |--------------------------|-----------------------|-----------------------|--------------------------------|
// | | | | deletes the DNAT rules |
// | false||true | cluster | cluster | towards clusterIP |
// | | | | for the default case |
// |--------------------------|-----------------------|-----------------------|--------------------------------|
// | | | | deletes all the rules |
// | false||true | local | local | for etp=local + itp=local |
// | | | | + default dnat towards CIP |
// +--------------------------+-----------------------+-----------------------+--------------------------------+
if err = delGatewayIptRules(service, true); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
if err = delGatewayIptRules(service, false); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
if err = delAllEgressSVCIptRules(service, npw); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
}
} else {
if err = delGatewayIptRules(service, true); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
if err = delGatewayIptRules(service, false); err != nil {
errors = append(errors, fmt.Errorf("error updating service flow cache: %v", err))
}
}
return apierrors.NewAggregate(errors)
}
func serviceUpdateNotNeeded(old, new *kapi.Service) bool {
return reflect.DeepEqual(new.Spec.Ports, old.Spec.Ports) &&
reflect.DeepEqual(new.Spec.ExternalIPs, old.Spec.ExternalIPs) &&
reflect.DeepEqual(new.Spec.ClusterIP, old.Spec.ClusterIP) &&
reflect.DeepEqual(new.Spec.ClusterIPs, old.Spec.ClusterIPs) &&
reflect.DeepEqual(new.Spec.Type, old.Spec.Type) &&
reflect.DeepEqual(new.Status.LoadBalancer.Ingress, old.Status.LoadBalancer.Ingress) &&
reflect.DeepEqual(new.Spec.ExternalTrafficPolicy, old.Spec.ExternalTrafficPolicy) &&
(new.Spec.InternalTrafficPolicy != nil && old.Spec.InternalTrafficPolicy != nil &&
reflect.DeepEqual(*new.Spec.InternalTrafficPolicy, *old.Spec.InternalTrafficPolicy)) &&
!util.EgressSVCHostChanged(old, new)
}
// AddService handles configuring shared gateway bridge flows to steer External IP, Node Port, Ingress LB traffic into OVN
func (npw *nodePortWatcher) AddService(service *kapi.Service) error {
var hasLocalHostNetworkEp bool
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return nil
}
klog.V(5).Infof("Adding service %s in namespace %s", service.Name, service.Namespace)
name := ktypes.NamespacedName{Namespace: service.Namespace, Name: service.Name}
epSlices, err := npw.watchFactory.GetEndpointSlices(service.Namespace, service.Name)
if err != nil {
klog.V(5).Infof("No endpointslice found for service %s in namespace %s during service Add",
service.Name, service.Namespace)
// No endpoint object exists yet so default to false
hasLocalHostNetworkEp = false
} else {
nodeIPs := npw.nodeIPManager.ListAddresses()
hasLocalHostNetworkEp = hasLocalHostNetworkEndpoints(epSlices, nodeIPs)
}
// If something didn't already do it add correct Service rules
if exists := npw.addOrSetServiceInfo(name, service, hasLocalHostNetworkEp); !exists {
klog.V(5).Infof("Service Add %s event in namespace %s came before endpoint event setting svcConfig",
service.Name, service.Namespace)
if err := addServiceRules(service, hasLocalHostNetworkEp, npw); err != nil {
return fmt.Errorf("AddService failed for nodePortWatcher: %v", err)
}
} else {
klog.V(5).Infof("Rules already programmed for %s in namespace %s", service.Name, service.Namespace)
}
return nil
}
func (npw *nodePortWatcher) UpdateService(old, new *kapi.Service) error {
var err error
var errors []error
name := ktypes.NamespacedName{Namespace: old.Namespace, Name: old.Name}
if serviceUpdateNotNeeded(old, new) {
klog.V(5).Infof("Skipping service update for: %s as change does not apply to any of .Spec.Ports, "+
".Spec.ExternalIP, .Spec.ClusterIP, .Spec.ClusterIPs, .Spec.Type, .Status.LoadBalancer.Ingress, "+
".Spec.ExternalTrafficPolicy, .Spec.InternalTrafficPolicy, Egress service host", new.Name)
return nil
}
// Update the service in svcConfig if we need to, so that other handler
// threads do the correct thing, leave hasLocalHostNetworkEp alone in the cache
svcConfig, exists := npw.updateServiceInfo(name, new, nil)
if !exists {
klog.V(5).Infof("Service %s in namespace %s was deleted during service Update", old.Name, old.Namespace)
return nil
}
if util.ServiceTypeHasClusterIP(old) && util.IsClusterIPSet(old) {
// Delete old rules if needed, but don't delete svcConfig
// so that we don't miss any endpoint update events here
klog.V(5).Infof("Deleting old service rules for: %v", old)
if err = delServiceRules(old, npw); err != nil {
errors = append(errors, err)
}
}
if util.ServiceTypeHasClusterIP(new) && util.IsClusterIPSet(new) {
klog.V(5).Infof("Adding new service rules for: %v", new)
if err = addServiceRules(new, svcConfig.hasLocalHostNetworkEp, npw); err != nil {
errors = append(errors, err)
}
}
if err = apierrors.NewAggregate(errors); err != nil {
return fmt.Errorf("UpdateService failed for nodePortWatcher: %v", err)
}
return nil
}
// deleteConntrackForServiceVIP deletes the conntrack entries for the provided svcVIP:svcPort by comparing them to ConntrackOrigDstIP:ConntrackOrigDstPort
func deleteConntrackForServiceVIP(svcVIPs []string, svcPorts []kapi.ServicePort, ns, name string) error {
for _, svcVIP := range svcVIPs {
for _, svcPort := range svcPorts {
err := util.DeleteConntrack(svcVIP, svcPort.Port, svcPort.Protocol, netlink.ConntrackOrigDstIP, nil)
if err != nil {
return fmt.Errorf("failed to delete conntrack entry for service %s/%s with svcVIP %s, svcPort %d, protocol %s: %v",
ns, name, svcVIP, svcPort.Port, svcPort.Protocol, err)
}
}
}
return nil
}
// deleteConntrackForService deletes the conntrack entries corresponding to the service VIPs of the provided service
func (npw *nodePortWatcher) deleteConntrackForService(service *kapi.Service) error {
// remove conntrack entries for LB VIPs and External IPs
externalIPs := util.GetExternalAndLBIPs(service)
if err := deleteConntrackForServiceVIP(externalIPs, service.Spec.Ports, service.Namespace, service.Name); err != nil {
return err
}
if util.ServiceTypeHasNodePort(service) {
// remove conntrack entries for NodePorts
nodeIPs := npw.nodeIPManager.ListAddresses()
for _, nodeIP := range nodeIPs {
for _, svcPort := range service.Spec.Ports {
err := util.DeleteConntrack(nodeIP.String(), svcPort.NodePort, svcPort.Protocol, netlink.ConntrackOrigDstIP, nil)
if err != nil {
return fmt.Errorf("failed to delete conntrack entry for service %s/%s with nodeIP %s, nodePort %d, protocol %s: %v",
service.Namespace, service.Name, nodeIP, svcPort.Port, svcPort.Protocol, err)
}
}
}
}
// remove conntrack entries for ClusterIPs
clusterIPs := util.GetClusterIPs(service)
if err := deleteConntrackForServiceVIP(clusterIPs, service.Spec.Ports, service.Namespace, service.Name); err != nil {
return err
}
return nil
}
func (npw *nodePortWatcher) DeleteService(service *kapi.Service) error {
var err error
var errors []error
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return nil
}
klog.V(5).Infof("Deleting service %s in namespace %s", service.Name, service.Namespace)
name := ktypes.NamespacedName{Namespace: service.Namespace, Name: service.Name}
if svcConfig, exists := npw.getAndDeleteServiceInfo(name); exists {
if err = delServiceRules(svcConfig.service, npw); err != nil {
errors = append(errors, err)
}
} else {
klog.Warningf("Delete service: no service found in cache for endpoint %s in namespace %s", service.Name, service.Namespace)
}
// Remove all conntrack entries for the serviceVIPs of this service irrespective of protocol stack
// since service deletion is considered as unplugging the network cable and hence graceful termination
// is not guaranteed. See https://github.com/kubernetes/kubernetes/issues/108523#issuecomment-1074044415.
if err = npw.deleteConntrackForService(service); err != nil {
errors = append(errors, fmt.Errorf("failed to delete conntrack entry for service %v: %v", name, err))
}
if err = apierrors.NewAggregate(errors); err != nil {
return fmt.Errorf("DeleteService failed for nodePortWatcher: %v", err)
}
return nil
}
func (npw *nodePortWatcher) SyncServices(services []interface{}) error {
var err error
var errors []error
keepIPTRules := []iptRule{}
for _, serviceInterface := range services {
name := ktypes.NamespacedName{Namespace: serviceInterface.(*kapi.Service).Namespace, Name: serviceInterface.(*kapi.Service).Name}
service, ok := serviceInterface.(*kapi.Service)
if !ok {
klog.Errorf("Spurious object in syncServices: %v",
serviceInterface)
continue
}
epSlices, err := npw.watchFactory.GetEndpointSlices(service.Namespace, service.Name)
if err != nil {
klog.V(5).Infof("No endpointslice found for service %s in namespace %s during sync", service.Name, service.Namespace)
continue
}
nodeIPs := npw.nodeIPManager.ListAddresses()
hasLocalHostNetworkEp := hasLocalHostNetworkEndpoints(epSlices, nodeIPs)
npw.getAndSetServiceInfo(name, service, hasLocalHostNetworkEp)
// Delete OF rules for service if they exist
if err = npw.updateServiceFlowCache(service, false, hasLocalHostNetworkEp); err != nil {
errors = append(errors, err)
}
if err = npw.updateServiceFlowCache(service, true, hasLocalHostNetworkEp); err != nil {
errors = append(errors, err)
}
// Add correct iptables rules only for Full mode
if !npw.dpuMode {
keepIPTRules = append(keepIPTRules, getGatewayIPTRules(service, hasLocalHostNetworkEp)...)
}
if !npw.dpuMode && shouldConfigureEgressSVC(service, npw) {
v4Eps := sets.NewString()
v6Eps := sets.NewString()
for _, epSlice := range epSlices {
if epSlice.AddressType == discovery.AddressTypeFQDN {
continue
}
epsToInsert := v4Eps
if epSlice.AddressType == discovery.AddressTypeIPv6 {
epsToInsert = v6Eps
}
for _, ep := range epSlice.Endpoints {
for _, ip := range ep.Addresses {
ipStr := utilnet.ParseIPSloppy(ip).String()
if !isHostEndpoint(ipStr) {
epsToInsert.Insert(ipStr)
}
}
}
}
keepIPTRules = append(keepIPTRules, egressSVCIPTRulesForEndpoints(service, v4Eps.UnsortedList(), v6Eps.UnsortedList())...)
npw.egressServiceInfoLock.Lock()
npw.egressServiceInfo[name] = &serviceEps{v4: v4Eps, v6: v6Eps}
npw.egressServiceInfoLock.Unlock()
}
}
// sync OF rules once
npw.ofm.requestFlowSync()
// sync IPtables rules once only for Full mode
if !npw.dpuMode {
// (NOTE: Order is important, add jump to iptableETPChain before jump to NP/EIP chains)
for _, chain := range []string{iptableITPChain, iptableESVCChain, iptableNodePortChain, iptableExternalIPChain, iptableETPChain, iptableMgmPortChain} {
if err = recreateIPTRules("nat", chain, keepIPTRules); err != nil {
errors = append(errors, err)
}
}
if err = recreateIPTRules("mangle", iptableITPChain, keepIPTRules); err != nil {
errors = append(errors, err)
}
}
return apierrors.NewAggregate(errors)
}
func (npw *nodePortWatcher) AddEndpointSlice(epSlice *discovery.EndpointSlice) error {
var err error
var errors []error
var svc *kapi.Service
svcName := epSlice.Labels[discovery.LabelServiceName]
svc, err = npw.watchFactory.GetService(epSlice.Namespace, svcName)
if err != nil {
// This is not necessarily an error. For e.g when there are endpoints
// without a corresponding service.
klog.V(5).Infof("No service found for endpointslice %s in namespace %s during add", epSlice.Name, epSlice.Namespace)
return nil
}
if !util.ServiceTypeHasClusterIP(svc) || !util.IsClusterIPSet(svc) {
return nil
}
klog.V(5).Infof("Adding endpointslice %s in namespace %s", epSlice.Name, epSlice.Namespace)
nodeIPs := npw.nodeIPManager.ListAddresses()
hasLocalHostNetworkEp := hasLocalHostNetworkEndpoints([]*discovery.EndpointSlice{epSlice}, nodeIPs)
// Here we make sure the correct rules are programmed whenever an AddEndpointSlice
// event is received, only alter flows if we need to, i.e if cache wasn't
// set or if it was and hasLocalHostNetworkEp state changed, to prevent flow churn
namespacedName, err := serviceNamespacedNameFromEndpointSlice(epSlice)
if err != nil {
return fmt.Errorf("cannot add %s/%s to nodePortWatcher: %v", epSlice.Namespace, epSlice.Name, err)
}
out, exists := npw.getAndSetServiceInfo(namespacedName, svc, hasLocalHostNetworkEp)
if !exists {
klog.V(5).Infof("Endpointslice %s ADD event in namespace %s is creating rules", epSlice.Name, epSlice.Namespace)
return addServiceRules(svc, hasLocalHostNetworkEp, npw)
}
if out.hasLocalHostNetworkEp != hasLocalHostNetworkEp {
klog.V(5).Infof("Endpointslice %s ADD event in namespace %s is updating rules", epSlice.Name, epSlice.Namespace)
if err = delServiceRules(svc, npw); err != nil {
errors = append(errors, err)
}
if err = addServiceRules(svc, hasLocalHostNetworkEp, npw); err != nil {
errors = append(errors, err)
}
return apierrors.NewAggregate(errors)
}
// Call this in case it wasn't already called by addServiceRules
npw.egressServiceInfoLock.Lock()
_, found := npw.egressServiceInfo[namespacedName]
npw.egressServiceInfoLock.Unlock()
if found && !npw.dpuMode {
return updateEgressSVCIptRules(svc, npw)
}
return nil
}
func (npw *nodePortWatcher) DeleteEndpointSlice(epSlice *discovery.EndpointSlice) error {
var err error
var errors []error
var hasLocalHostNetworkEp = false
klog.V(5).Infof("Deleting endpointslice %s in namespace %s", epSlice.Name, epSlice.Namespace)
// remove rules for endpoints and add back normal ones
namespacedName, err := serviceNamespacedNameFromEndpointSlice(epSlice)
if err != nil {
return fmt.Errorf("cannot delete %s/%s from nodePortWatcher: %v", epSlice.Namespace, epSlice.Name, err)
}
if svcConfig, exists := npw.updateServiceInfo(namespacedName, nil, &hasLocalHostNetworkEp); exists {
// Lock the cache mutex here so we don't miss a service delete during an endpoint delete
// we have to do this because deleting and adding iptables rules is slow.
npw.serviceInfoLock.Lock()
defer npw.serviceInfoLock.Unlock()
if err = delServiceRules(svcConfig.service, npw); err != nil {
errors = append(errors, err)
}
if err = addServiceRules(svcConfig.service, hasLocalHostNetworkEp, npw); err != nil {
errors = append(errors, err)
}
return apierrors.NewAggregate(errors)
}
return nil
}
func getEndpointAddresses(endpointSlice *discovery.EndpointSlice, service *kapi.Service) []string {
endpointsAddress := make([]string, 0)
includeTerminating := service != nil && service.Spec.PublishNotReadyAddresses
for _, endpoint := range endpointSlice.Endpoints {
if util.IsEndpointValid(endpoint, includeTerminating) {
for _, ip := range endpoint.Addresses {
endpointsAddress = append(endpointsAddress, utilnet.ParseIPSloppy(ip).String())
}
}
}
return endpointsAddress
}
func (npw *nodePortWatcher) UpdateEndpointSlice(oldEpSlice, newEpSlice *discovery.EndpointSlice) error {
var err error
var errors []error
namespacedName, err := serviceNamespacedNameFromEndpointSlice(newEpSlice)
if err != nil {
return fmt.Errorf("cannot update %s/%s in nodePortWatcher: %v", newEpSlice.Namespace, newEpSlice.Name, err)
}
svc, err := npw.watchFactory.GetService(namespacedName.Namespace, namespacedName.Name)
if err != nil && !kerrors.IsNotFound(err) {
return fmt.Errorf("error while retrieving service for endpointslice %s/%s during update: %v",
oldEpSlice.Namespace, oldEpSlice.Name, err)
}
oldEpAddr := getEndpointAddresses(oldEpSlice, svc)
newEpAddr := getEndpointAddresses(newEpSlice, svc)
if reflect.DeepEqual(oldEpAddr, newEpAddr) {
return nil
}
klog.V(5).Infof("Updating endpointslice %s in namespace %s", oldEpSlice.Name, oldEpSlice.Namespace)
if _, exists := npw.getServiceInfo(namespacedName); !exists {
// When a service is updated from externalName to nodeport type, it won't be
// in nodePortWatcher cache (npw): in this case, have the new nodeport IPtable rules
// installed.
if err = npw.AddEndpointSlice(newEpSlice); err != nil {
errors = append(errors, err)
}
} else if len(newEpAddr) == 0 {
// With no endpoint addresses in new endpointslice, delete old endpoint rules
// and add normal ones back
if err = npw.DeleteEndpointSlice(oldEpSlice); err != nil {
errors = append(errors, err)
}
}
// Update rules if hasHostNetworkEndpoints status changed
nodeIPs := npw.nodeIPManager.ListAddresses()
hasLocalHostNetworkEpOld := hasLocalHostNetworkEndpoints([]*discovery.EndpointSlice{oldEpSlice}, nodeIPs)
hasLocalHostNetworkEpNew := hasLocalHostNetworkEndpoints([]*discovery.EndpointSlice{newEpSlice}, nodeIPs)
if hasLocalHostNetworkEpOld != hasLocalHostNetworkEpNew {
if err = npw.DeleteEndpointSlice(oldEpSlice); err != nil {
errors = append(errors, err)
}
if err = npw.AddEndpointSlice(newEpSlice); err != nil {
errors = append(errors, err)
}
return apierrors.NewAggregate(errors)
}
// Call this in case it wasn't already called by addServiceRules
npw.egressServiceInfoLock.Lock()
_, found := npw.egressServiceInfo[namespacedName]
npw.egressServiceInfoLock.Unlock()
if found && !npw.dpuMode {
svc, err := npw.watchFactory.GetService(namespacedName.Namespace, namespacedName.Name)
if err != nil {
errors = append(errors, fmt.Errorf("failed to get service %s/%s while updating endpoint slice %s/%s",
namespacedName.Namespace, namespacedName.Name, oldEpSlice.Namespace, oldEpSlice.Name))
} else {
if err = updateEgressSVCIptRules(svc, npw); err != nil {
errors = append(errors, err)
}
}
}
return apierrors.NewAggregate(errors)
}
func (npwipt *nodePortWatcherIptables) AddService(service *kapi.Service) error {
// don't process headless service or services that doesn't have NodePorts or ExternalIPs
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return nil
}
if err := addServiceRules(service, false, nil); err != nil {
return fmt.Errorf("AddService failed for nodePortWatcherIptables: %v", err)
}
return nil
}
func (npwipt *nodePortWatcherIptables) UpdateService(old, new *kapi.Service) error {
var err error
var errors []error
if serviceUpdateNotNeeded(old, new) {
klog.V(5).Infof("Skipping service update for: %s as change does not apply to "+
"any of .Spec.Ports, .Spec.ExternalIP, .Spec.ClusterIP, .Spec.ClusterIPs,"+
" .Spec.Type, .Status.LoadBalancer.Ingress, Egress service annotations", new.Name)
return nil
}
if util.ServiceTypeHasClusterIP(old) && util.IsClusterIPSet(old) {
if err = delServiceRules(old, nil); err != nil {
errors = append(errors, err)
}
}
if util.ServiceTypeHasClusterIP(new) && util.IsClusterIPSet(new) {
if err = addServiceRules(new, false, nil); err != nil {
errors = append(errors, err)
}
}
if err = apierrors.NewAggregate(errors); err != nil {
return fmt.Errorf("UpdateService failed for nodePortWatcherIptables: %v", err)
}
return nil
}
func (npwipt *nodePortWatcherIptables) DeleteService(service *kapi.Service) error {
// don't process headless service
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return nil
}
if err := delServiceRules(service, nil); err != nil {
return fmt.Errorf("DeleteService failed for nodePortWatcherIptables: %v", err)
}
return nil
}
func (npwipt *nodePortWatcherIptables) SyncServices(services []interface{}) error {
var err error
var errors []error
keepIPTRules := []iptRule{}
for _, serviceInterface := range services {
service, ok := serviceInterface.(*kapi.Service)
if !ok {
klog.Errorf("Spurious object in syncServices: %v",
serviceInterface)
continue
}
// Add correct iptables rules.
// TODO: ETP and ITP is not implemented for smart NIC mode.
keepIPTRules = append(keepIPTRules, getGatewayIPTRules(service, false)...)
}
// sync IPtables rules once
for _, chain := range []string{iptableNodePortChain, iptableExternalIPChain} {
if err = recreateIPTRules("nat", chain, keepIPTRules); err != nil {
errors = append(errors, err)
}
}
return apierrors.NewAggregate(errors)
}
// since we share the host's k8s node IP, add OpenFlow flows
// -- to steer the NodePort traffic arriving on the host to the OVN logical topology and
// -- to also connection track the outbound north-south traffic through l3 gateway so that
//
// the return traffic can be steered back to OVN logical topology