-
Notifications
You must be signed in to change notification settings - Fork 357
/
gateway_shared_intf.go
1370 lines (1222 loc) · 59.6 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/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"
kapi "k8s.io/api/core/v1"
ktypes "k8s.io/apimachinery/pkg/types"
"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"
)
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
// Map of service name to programmed iptables/OF rules
serviceInfo map[ktypes.NamespacedName]*serviceConfig
serviceInfoLock 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
}
// createFlowsForNonLocalHostNetEp adds the necessary openflows for a service when its backed by non-local-host-networked endpoints
// This function is currently used only in LGW mode and when ETP=local for the service
// cookie is the hash value of openflow cookie, svcPort is the nodePort of the service, flowProtocol is tcp/udp/sctp in v4 or v6 modes,
// externalIPOrLBIngressIP is either externalIP or LB.status.ingress, nwDst&nwSrc are constants used to match on the destinations based on the flowprotocol
func (npw *nodePortWatcher) createFlowsForNonLocalHostNetEp(cookie string, svcPort int32, flowProtocol string, externalIPOrLBIngressIP, nwDst, nwSrc string) []string {
var nodeportFlowsResult []string
if len(externalIPOrLBIngressIP) != 0 {
// if externalIPOrLBIngressIP is set then this service is of type LB/EIP
nodeportFlowsResult = append(nodeportFlowsResult,
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, %s=%s, tp_dst=%d, actions=ct(commit,zone=%d,table=6)",
cookie, npw.ofportPhys, flowProtocol, nwDst, externalIPOrLBIngressIP, svcPort, HostNodePortCTZone),
fmt.Sprintf("cookie=%s, priority=110, in_port=LOCAL, %s, %s=%s, tp_src=%d, actions=ct(zone=%d,table=7)",
cookie, flowProtocol, nwSrc, externalIPOrLBIngressIP, svcPort, HostNodePortCTZone))
} else {
// if externalIPOrLBIngressIP is not set then this service is of type NP
nodeportFlowsResult = append(nodeportFlowsResult,
// Traffic destined for ETP=local backed by OVN-K pod in LGW mode is matched on the svcNP and sent to table6.
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_dst=%d, actions=ct(commit,zone=%d,table=6)",
cookie, npw.ofportPhys, flowProtocol, svcPort, HostNodePortCTZone),
// Return traffic is matched on the svcNP as the sourcePort and gets un-DNATed back to nodeIP.
fmt.Sprintf("cookie=%s, priority=110, in_port=LOCAL, %s, tp_src=%d, actions=ct(zone=%d,table=7)",
cookie, flowProtocol, svcPort, HostNodePortCTZone))
}
nodeportFlowsResult = append(nodeportFlowsResult,
// 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 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))
return nodeportFlowsResult
}
// 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: Only applicable for LGW mode: If a service has externalTrafficPolicy=local, and it doesn't have host-networked
// endpoints local to the node (!hasLocalHostNetworkEp - including empty endpoint.Subset), traffic will be steered into LOCAL
// preserving sourceIP and IPTables will steer this traffic into OVN via ovn-k8s-mp0.
//
// case3: All other types of services i.e:
// case3a: if externalTrafficPolicy=cluster, irrespective of gateway modes, traffic will be steered into OVN via GR.
// case3b: if externalTrafficPolicy=local+!hasLocalHostNetworkEp+SGW mode, traffic will be steered into OVN via GR.
// `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) {
var cookie, key string
var err error
// 14 bytes of overhead for ethernet header (does not include VLAN)
maxPktLength := getMaxFrameLength()
isServiceTypeETPLocal := util.ServiceExternalTrafficPolicyLocal(service)
var actions string
if config.Gateway.DisablePacketMTUCheck {
actions = fmt.Sprintf("output:%s", npw.ofportPatch)
} else {
// check packet length larger than MTU + eth header - vlan overhead
// send to table 11 to check if it needs to go to kernel for ICMP needs frag
actions = fmt.Sprintf("check_pkt_larger(%d)->reg0[0],resubmit(,11)", maxPktLength)
}
// 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
}
// (astoycos) TODO combine flow generation into a single function
// 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 it to the correct NodeIP
// If ipv6 make sure to choose the ipv6 node address), and sends to table 6
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 isServiceTypeETPLocal && !hasLocalHostNetworkEp && config.Gateway.Mode == config.GatewayModeLocal {
// case2 (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)
nodeportFlows = npw.createFlowsForNonLocalHostNetEp(cookie, svcPort.NodePort, flowProtocol, "", "", "")
npw.ofm.updateFlowCacheEntry(key, nodeportFlows)
} else {
// case3 (see function description for details)
npw.ofm.updateFlowCacheEntry(key, []string{
fmt.Sprintf("cookie=%s, priority=110, in_port=%s, %s, tp_dst=%d, "+
"actions=%s",
cookie, npw.ofportPhys, flowProtocol, svcPort.NodePort, actions),
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 {
err = npw.createLbAndExternalSvcFlows(service, &svcPort, add, hasLocalHostNetworkEp, protocol, actions, ing.IP, "Ingress")
if err != nil {
klog.Errorf(err.Error())
}
}
}
// flows for externalIPs
for _, externalIP := range service.Spec.ExternalIPs {
err = npw.createLbAndExternalSvcFlows(service, &svcPort, add, hasLocalHostNetworkEp, protocol, actions, externalIP, "External")
if err != nil {
klog.Errorf(err.Error())
}
}
}
}
// 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: Only applicable for LGW mode: If a service has externalTrafficPolicy=local, and it doesn't have host-networked
// endpoints local to the node (!hasLocalHostNetworkEp - including empty endpoint.Subset), traffic will be steered into LOCAL
// preserving sourceIP and IPTables will steer this traffic into OVN via ovn-k8s-mp0.
//
// case3: All other types of services i.e:
// case3a: if externalTrafficPolicy=cluster, irrespective of gateway modes, traffic will be steered into OVN via GR.
// case3b: if externalTrafficPolicy=local+!hasLocalHostNetworkEp+SGW mode, traffic will be steered into OVN via GR.
// `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`: based on config.Gateway.DisablePacketMTUCheck, this will either be "send to patchport" or "send to table11 for checking if it needs to go to kernel for ICMP needs frag"
// `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
}
// 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)
var nodeportFlows []string
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 it to the correct NodeIP
// 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, %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 {
nodeportFlows = append(nodeportFlows,
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()))
}
nodeportFlows = append(nodeportFlows,
// table 6, Sends the packet to the host
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, the packet back out eth0 to the external client
fmt.Sprintf("cookie=%s, priority=110, table=7, "+
"actions=output:%s", etpSvcOpenFlowCookie, npw.ofportPhys))
npw.ofm.updateFlowCacheEntry(key, nodeportFlows)
} else if isServiceTypeETPLocal && !hasLocalHostNetworkEp && config.Gateway.Mode == config.GatewayModeLocal {
// case2 (see function description for details)
var nodeportFlows []string
klog.V(5).Infof("Adding flows on breth0 for %s Service %s in Namespace: %s since ExternalTrafficPolicy=local", ipType, service.Name, service.Namespace)
nodeportFlows = npw.createFlowsForNonLocalHostNetEp(cookie, svcPort.Port, flowProtocol, externalIPOrLBIngressIP, nwDst, nwSrc)
npw.ofm.updateFlowCacheEntry(key, nodeportFlows)
} else {
// case3 (see function description for details)
npw.ofm.updateFlowCacheEntry(key, []string{
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),
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.generateArpBypassFlow(protocol, externalIPOrLBIngressIP, cookie)})
}
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) {
// For dpu or Full mode
if npw != nil {
npw.updateServiceFlowCache(service, true, svcHasLocalHostNetEndPnt)
npw.ofm.requestFlowSync()
if !npw.dpuMode {
// add iptable rules only in full mode
addGatewayIptRules(service, svcHasLocalHostNetEndPnt)
}
return
}
// For Host Only Mode
addGatewayIptRules(service, svcHasLocalHostNetEndPnt)
}
// delServiceRules deletes all possible iptables rules and OpenFlow physical
// flows for a service
func delServiceRules(service *kapi.Service, npw *nodePortWatcher) {
// full mode || dpu mode
if npw != nil {
npw.updateServiceFlowCache(service, false, false)
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 | GatewayMode | Scenario for deletion |
// |--------------------------|-----------------------|--------------|--------------------------------|
// | | | | deletes the REDIRECT |
// | true | local | shared+local | rules for etp=local + |
// | | | | host-networked eps |
// |--------------------------|-----------------------|--------------|--------------------------------|
// | | | | deletes the DNAT rules for |
// | false | local | shared+local | etp=local + non-local-host-net |
// | | | | eps towards masqueradeIP |
// |--------------------------|-----------------------|--------------|--------------------------------|
// | | | | deletes the DNAT rules |
// | false | cluster | shared+local | towards clusterIP |
// | | | | for the default case |
// +--------------------------+-----------------------+--------------+--------------------------------+
// case1: deletes the REDIRECT rules for etp=local + host-networked pods in both gw modes
delGatewayIptRules(service, true)
// case2: deletes the DNAT rules towards masqueradeIP for etp=local + ovn-k pods in both gw modes OR
// case3: deletes the DNAT rules towards clusterIP for etp=cluster in both gw modes
delGatewayIptRules(service, false)
}
return
}
// For host only mode always try and delete all rules here
// case1: deletes the REDIRECT rules for etp=local + host-networked pods in both gw modes
delGatewayIptRules(service, true)
// case2: deletes the DNAT rules towards masqueradeIP for etp=local + ovn-k pods in both gw modes OR
// case3: deletes the DNAT rules towards clusterIP for etp=cluster in both gw modes
delGatewayIptRules(service, false)
}
func serviceUpdateNeeded(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.Type, old.Spec.Type) &&
reflect.DeepEqual(new.Status.LoadBalancer.Ingress, old.Status.LoadBalancer.Ingress) &&
reflect.DeepEqual(new.Spec.ExternalTrafficPolicy, old.Spec.ExternalTrafficPolicy)
}
// 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) {
var hasLocalHostNetworkEp bool
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return
}
klog.V(5).Infof("Adding service %s in namespace %s", service.Name, service.Namespace)
name := ktypes.NamespacedName{Namespace: service.Namespace, Name: service.Name}
ep, err := npw.watchFactory.GetEndpoint(service.Namespace, service.Name)
if err != nil {
klog.V(5).Infof("No endpoint 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 {
hasLocalHostNetworkEp = hasLocalHostNetworkEndpoints(ep, &npw.nodeIPManager.addresses)
}
// 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)
addServiceRules(service, hasLocalHostNetworkEp, npw)
} else {
klog.V(5).Infof("Rules already programmed for %s in namespace %s", service.Name, service.Namespace)
}
}
func (npw *nodePortWatcher) UpdateService(old, new *kapi.Service) {
name := ktypes.NamespacedName{Namespace: old.Namespace, Name: old.Name}
if serviceUpdateNeeded(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.Type, .Status.LoadBalancer.Ingress, .Spec.ExternalTrafficPolicy", new.Name)
return
}
// 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
}
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)
delServiceRules(old, npw)
}
if util.ServiceTypeHasClusterIP(new) && util.IsClusterIPSet(new) {
klog.V(5).Infof("Adding new service rules for: %v", new)
addServiceRules(new, svcConfig.hasLocalHostNetworkEp, npw)
}
}
func (npw *nodePortWatcher) DeleteService(service *kapi.Service) {
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return
}
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 {
delServiceRules(svcConfig.service, npw)
} else {
klog.Warningf("Deletion failed No service found in cache for endpoint %s in namespace %s", service.Name, service.Namespace)
}
}
func (npw *nodePortWatcher) SyncServices(services []interface{}) {
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
}
ep, err := npw.watchFactory.GetEndpoint(service.Namespace, service.Name)
if err != nil {
klog.V(5).Infof("No endpoint found for service %s in namespace %s during sync", service.Name, service.Namespace)
continue
}
hasLocalHostNetworkEp := hasLocalHostNetworkEndpoints(ep, &npw.nodeIPManager.addresses)
npw.getAndSetServiceInfo(name, service, hasLocalHostNetworkEp)
// Delete OF rules for service if they exist
npw.updateServiceFlowCache(service, false, hasLocalHostNetworkEp)
npw.updateServiceFlowCache(service, true, hasLocalHostNetworkEp)
// Add correct iptables rules only for Full mode
if !npw.dpuMode {
keepIPTRules = append(keepIPTRules, getGatewayIPTRules(service, hasLocalHostNetworkEp)...)
}
}
// sync OF rules once
npw.ofm.requestFlowSync()
// sync IPtables rules once only for Full mode
if !npw.dpuMode {
for _, chain := range []string{iptableNodePortChain, iptableExternalIPChain, iptableMgmPortChain} {
recreateIPTRules("nat", chain, keepIPTRules)
}
}
}
func (npw *nodePortWatcher) AddEndpoints(ep *kapi.Endpoints) {
name := ktypes.NamespacedName{Namespace: ep.Namespace, Name: ep.Name}
svc, err := npw.watchFactory.GetService(ep.Namespace, ep.Name)
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 endpoint %s in namespace %s during add", ep.Name, ep.Namespace)
return
}
if !util.ServiceTypeHasClusterIP(svc) || !util.IsClusterIPSet(svc) {
return
}
klog.V(5).Infof("Adding endpoints %s in namespace %s", ep.Name, ep.Namespace)
hasLocalHostNetworkEp := hasLocalHostNetworkEndpoints(ep, &npw.nodeIPManager.addresses)
// Here we make sure the correct rules are programmed whenever an AddEndpoint
// 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
out, exists := npw.getAndSetServiceInfo(name, svc, hasLocalHostNetworkEp)
if !exists {
klog.V(5).Infof("Endpoint %s ADD event in namespace %s is creating rules", ep.Name, ep.Namespace)
addServiceRules(svc, hasLocalHostNetworkEp, npw)
return
}
if out.hasLocalHostNetworkEp != hasLocalHostNetworkEp {
klog.V(5).Infof("Endpoint %s ADD event in namespace %s is updating rules", ep.Name, ep.Namespace)
delServiceRules(svc, npw)
addServiceRules(svc, hasLocalHostNetworkEp, npw)
}
}
func (npw *nodePortWatcher) DeleteEndpoints(ep *kapi.Endpoints) {
var hasLocalHostNetworkEp = false
klog.V(5).Infof("Deleting endpoints %s in namespace %s", ep.Name, ep.Namespace)
// remove rules for endpoints and add back normal ones
name := ktypes.NamespacedName{Namespace: ep.Namespace, Name: ep.Name}
if svcConfig, exists := npw.updateServiceInfo(name, 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()
delServiceRules(svcConfig.service, npw)
addServiceRules(svcConfig.service, hasLocalHostNetworkEp, npw)
}
}
func (npw *nodePortWatcher) UpdateEndpoints(old *kapi.Endpoints, new *kapi.Endpoints) {
name := ktypes.NamespacedName{Namespace: old.Namespace, Name: old.Name}
if reflect.DeepEqual(new.Subsets, old.Subsets) {
return
}
klog.V(5).Infof("Updating endpoints %s in namespace %s", old.Name, old.Namespace)
// Delete old endpoint rules and add normal ones back
if len(new.Subsets) == 0 {
if _, exists := npw.getServiceInfo(name); exists {
npw.DeleteEndpoints(old)
}
}
// Update rules if hasLocalHostNetworkEpNew status changed.
hasLocalHostNetworkEpOld := hasLocalHostNetworkEndpoints(old, &npw.nodeIPManager.addresses)
hasLocalHostNetworkEpNew := hasLocalHostNetworkEndpoints(new, &npw.nodeIPManager.addresses)
if hasLocalHostNetworkEpOld != hasLocalHostNetworkEpNew {
npw.DeleteEndpoints(old)
npw.AddEndpoints(new)
}
}
func (npwipt *nodePortWatcherIptables) AddService(service *kapi.Service) {
// don't process headless service or services that doesn't have NodePorts or ExternalIPs
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return
}
addServiceRules(service, false, nil)
}
func (npwipt *nodePortWatcherIptables) UpdateService(old, new *kapi.Service) {
if serviceUpdateNeeded(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.Type, .Status.LoadBalancer.Ingress", new.Name)
return
}
if util.ServiceTypeHasClusterIP(old) && util.IsClusterIPSet(old) {
delServiceRules(old, nil)
}
if util.ServiceTypeHasClusterIP(new) && util.IsClusterIPSet(new) {
addServiceRules(new, false, nil)
}
}
func (npwipt *nodePortWatcherIptables) DeleteService(service *kapi.Service) {
// don't process headless service
if !util.ServiceTypeHasClusterIP(service) || !util.IsClusterIPSet(service) {
return
}
delServiceRules(service, nil)
}
func (npwipt *nodePortWatcherIptables) SyncServices(services []interface{}) {
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 is not implemented for smart NIC mode.
keepIPTRules = append(keepIPTRules, getGatewayIPTRules(service, false)...)
}
// sync IPtables rules once
for _, chain := range []string{iptableNodePortChain, iptableExternalIPChain} {
recreateIPTRules("nat", chain, keepIPTRules)
}
}
// 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
// -- to handle host -> service access, via masquerading from the host to OVN GR
// -- to handle external -> service(ExternalTrafficPolicy: Local) -> host access without SNAT
func newSharedGatewayOpenFlowManager(gwBridge, exGWBridge *bridgeConfiguration) (*openflowManager, error) {
dftFlows, err := flowsForDefaultBridge(gwBridge.ofPortPhys, gwBridge.macAddress.String(), gwBridge.ofPortPatch,
gwBridge.ofPortHost, gwBridge.ips)
if err != nil {
return nil, err
}
dftCommonFlows := commonFlows(gwBridge.ofPortPhys, gwBridge.macAddress.String(), gwBridge.ofPortPatch,
gwBridge.ofPortHost)
dftFlows = append(dftFlows, dftCommonFlows...)
// add health check function to check default OpenFlow flows are on the shared gateway bridge
ofm := &openflowManager{
defaultBridge: gwBridge,
externalGatewayBridge: exGWBridge,
flowCache: make(map[string][]string),
flowMutex: sync.Mutex{},
exGWFlowCache: make(map[string][]string),
exGWFlowMutex: sync.Mutex{},
flowChan: make(chan struct{}, 1),
}
ofm.updateFlowCacheEntry("NORMAL", []string{fmt.Sprintf("table=0,priority=0,actions=%s\n", util.NormalAction)})
ofm.updateFlowCacheEntry("DEFAULT", dftFlows)
// we consume ex gw bridge flows only if that is enabled
if exGWBridge != nil {
ofm.updateExBridgeFlowCacheEntry("NORMAL", []string{fmt.Sprintf("table=0,priority=0,actions=%s\n", util.NormalAction)})
exGWBridgeDftFlows := commonFlows(exGWBridge.ofPortPhys, exGWBridge.macAddress.String(),
exGWBridge.ofPortPatch, exGWBridge.ofPortHost)
ofm.updateExBridgeFlowCacheEntry("DEFAULT", exGWBridgeDftFlows)
}
// defer flowSync until syncService() to prevent the existing service OpenFlows being deleted
return ofm, nil
}
func flowsForDefaultBridge(ofPortPhys, bridgeMacAddress, ofPortPatch, ofPortHost string, bridgeIPs []*net.IPNet) ([]string, error) {
var dftFlows []string
// 14 bytes of overhead for ethernet header (does not include VLAN)
maxPktLength := getMaxFrameLength()
if config.IPv4Mode {
// table0, Geneve packets coming from external. Skip conntrack and go directly to host
// if dest mac is the shared mac send directly to host.
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=205, in_port=%s, dl_dst=%s, udp, udp_dst=%d, "+
"actions=output:%s", defaultOpenFlowCookie, ofPortPhys, bridgeMacAddress, config.Default.EncapPort,
ofPortHost))
// perform NORMAL action otherwise.
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=200, in_port=%s, udp, udp_dst=%d, "+
"actions=NORMAL", defaultOpenFlowCookie, ofPortPhys, config.Default.EncapPort))
// table0, Geneve packets coming from LOCAL. Skip conntrack and go directly to external
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=200, in_port=%s, udp, udp_dst=%d, "+
"actions=output:%s", defaultOpenFlowCookie, ovsLocalPort, config.Default.EncapPort, ofPortPhys))
physicalIP, err := util.MatchIPNetFamily(false, bridgeIPs)
if err != nil {
return nil, fmt.Errorf("unable to determine IPv4 physical IP of host: %v", err)
}
// table 0, SVC Hairpin from OVN destined to local host, DNAT and go to table 4
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, ip, ip_dst=%s, ip_src=%s,"+
"actions=ct(commit,zone=%d,nat(dst=%s),table=4)",
defaultOpenFlowCookie, ofPortPatch, types.V4HostMasqueradeIP, physicalIP.IP,
HostMasqCTZone, physicalIP.IP))
// table 0, Reply SVC traffic from Host -> OVN, unSNAT and goto table 5
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, ip, ip_dst=%s,"+
"actions=ct(zone=%d,nat,table=5)",
defaultOpenFlowCookie, ofPortHost, types.V4OVNMasqueradeIP, OVNMasqCTZone))
}
if config.IPv6Mode {
// table0, Geneve packets coming from external. Skip conntrack and go directly to host
// if dest mac is the shared mac send directly to host.
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=205, in_port=%s, dl_dst=%s, udp6, udp_dst=%d, "+
"actions=output:%s", defaultOpenFlowCookie, ofPortPhys, bridgeMacAddress, config.Default.EncapPort,
ofPortHost))
// perform NORMAL action otherwise.
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=200, in_port=%s, udp6, udp_dst=%d, "+
"actions=NORMAL", defaultOpenFlowCookie, ofPortPhys, config.Default.EncapPort))
// table0, Geneve packets coming from LOCAL. Skip conntrack and send to external
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=200, in_port=%s, udp6, udp_dst=%d, "+
"actions=output:%s", defaultOpenFlowCookie, ovsLocalPort, config.Default.EncapPort, ofPortPhys))
physicalIP, err := util.MatchIPNetFamily(true, bridgeIPs)
if err != nil {
return nil, fmt.Errorf("unable to determine IPv6 physical IP of host: %v", err)
}
// table 0, SVC Hairpin from OVN destined to local host, DNAT to host, send to table 4
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, ipv6, ipv6_dst=%s, ipv6_src=%s,"+
"actions=ct(commit,zone=%d,nat(dst=%s),table=4)",
defaultOpenFlowCookie, ofPortPatch, types.V6HostMasqueradeIP, physicalIP.IP,
HostMasqCTZone, physicalIP.IP))
// table 0, Reply SVC traffic from Host -> OVN, unSNAT and goto table 5
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, ipv6, ipv6_dst=%s,"+
"actions=ct(zone=%d,nat,table=5)",
defaultOpenFlowCookie, ofPortHost, types.V6OVNMasqueradeIP, OVNMasqCTZone))
}
var protoPrefix string
var masqIP string
// table 0, packets coming from Host -> Service
for _, svcCIDR := range config.Kubernetes.ServiceCIDRs {
if utilnet.IsIPv4CIDR(svcCIDR) {
protoPrefix = "ip"
masqIP = types.V4HostMasqueradeIP
} else {
protoPrefix = "ipv6"
masqIP = types.V6HostMasqueradeIP
}
// table 0, Host -> OVN towards SVC, SNAT to special IP
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, %s, %s_dst=%s,"+
"actions=ct(commit,zone=%d,nat(src=%s),table=2)",
defaultOpenFlowCookie, ofPortHost, protoPrefix, protoPrefix, svcCIDR, HostMasqCTZone, masqIP))
// table 0, Reply hairpin traffic to host, coming from OVN, unSNAT
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=500, in_port=%s, %s, %s_src=%s, %s_dst=%s,"+
"actions=ct(zone=%d,nat,table=3)",
defaultOpenFlowCookie, ofPortPatch, protoPrefix, protoPrefix, svcCIDR,
protoPrefix, masqIP, HostMasqCTZone))
}
var actions string
if config.Gateway.DisablePacketMTUCheck {
actions = fmt.Sprintf("output:%s", ofPortPatch)
} else {
// check packet length larger than MTU + eth header - vlan overhead
// send to table 11 to check if it needs to go to kernel for ICMP needs frag
actions = fmt.Sprintf("check_pkt_larger(%d)->reg0[0],resubmit(,11)", maxPktLength)
}
if config.IPv4Mode {
// table 1, established and related connections in zone 64000 with ct_mark ctMarkOVN go to OVN
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip, ct_state=+trk+est, ct_mark=%s, "+
"actions=%s",
defaultOpenFlowCookie, ctMarkOVN, actions))
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip, ct_state=+trk+rel, ct_mark=%s, "+
"actions=%s",
defaultOpenFlowCookie, ctMarkOVN, actions))
// table 1, established and related connections in zone 64000 with ct_mark ctMarkHost go to host
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip, ct_state=+trk+est, ct_mark=%s, "+
"actions=output:%s",
defaultOpenFlowCookie, ctMarkHost, ofPortHost))
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip, ct_state=+trk+rel, ct_mark=%s, "+
"actions=output:%s",
defaultOpenFlowCookie, ctMarkHost, ofPortHost))
}
if config.IPv6Mode {
// table 1, established and related connections in zone 64000 with ct_mark ctMarkOVN go to OVN
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ipv6, ct_state=+trk+est, ct_mark=%s, "+
"actions=%s",
defaultOpenFlowCookie, ctMarkOVN, actions))
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ipv6, ct_state=+trk+rel, ct_mark=%s, "+
"actions=%s",
defaultOpenFlowCookie, ctMarkOVN, actions))
// table 1, established and related connections in zone 64000 with ct_mark ctMarkHost go to host
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip6, ct_state=+trk+est, ct_mark=%s, "+
"actions=output:%s",
defaultOpenFlowCookie, ctMarkHost, ofPortHost))
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=100, table=1, ip6, ct_state=+trk+rel, ct_mark=%s, "+
"actions=output:%s",
defaultOpenFlowCookie, ctMarkHost, ofPortHost))
}
// table 1, we check to see if this dest mac is the shared mac, if so send to host
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, priority=10, table=1, dl_dst=%s, actions=output:%s",
defaultOpenFlowCookie, bridgeMacAddress, ofPortHost))
// table 2, dispatch from Host -> OVN
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=2, "+
"actions=mod_dl_dst=%s,output:%s", defaultOpenFlowCookie, bridgeMacAddress, ofPortPatch))
// table 3, dispatch from OVN -> Host
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=3, "+
"actions=move:NXM_OF_ETH_DST[]->NXM_OF_ETH_SRC[],mod_dl_dst=%s,output:%s",
defaultOpenFlowCookie, bridgeMacAddress, ofPortHost))
// table 4, hairpinned pkts that need to go from OVN -> Host
// We need to SNAT and masquerade OVN GR IP, send to table 3 for dispatch to Host
if config.IPv4Mode {
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=4,ip,"+
"actions=ct(commit,zone=%d,nat(src=%s),table=3)",
defaultOpenFlowCookie, OVNMasqCTZone, types.V4OVNMasqueradeIP))
}
if config.IPv6Mode {
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=4,ipv6, "+
"actions=ct(commit,zone=%d,nat(src=%s),table=3)",
defaultOpenFlowCookie, OVNMasqCTZone, types.V6OVNMasqueradeIP))
}
// table 5, Host Reply traffic to hairpinned svc, need to unDNAT, send to table 2
if config.IPv4Mode {
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=5, ip, "+
"actions=ct(commit,zone=%d,nat,table=2)",
defaultOpenFlowCookie, HostMasqCTZone))
}
if config.IPv6Mode {
dftFlows = append(dftFlows,
fmt.Sprintf("cookie=%s, table=5, ipv6, "+
"actions=ct(commit,zone=%d,nat,table=2)",
defaultOpenFlowCookie, HostMasqCTZone))
}
return dftFlows, nil
}
func commonFlows(ofPortPhys, bridgeMacAddress, ofPortPatch, ofPortHost string) []string {
var dftFlows []string