-
Notifications
You must be signed in to change notification settings - Fork 386
/
Copy pathpipeline.go
2934 lines (2745 loc) · 118 KB
/
pipeline.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
// Copyright 2019 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package openflow
import (
"encoding/binary"
"fmt"
"net"
"sort"
"sync"
"time"
"antrea.io/libOpenflow/openflow15"
"antrea.io/libOpenflow/protocol"
"antrea.io/ofnet/ofctrl"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache"
"antrea.io/antrea/pkg/agent/config"
"antrea.io/antrea/pkg/agent/metrics"
"antrea.io/antrea/pkg/agent/openflow/cookie"
"antrea.io/antrea/pkg/agent/types"
"antrea.io/antrea/pkg/agent/util"
binding "antrea.io/antrea/pkg/ovs/openflow"
"antrea.io/antrea/pkg/ovs/ovsctl"
"antrea.io/antrea/pkg/util/runtime"
"antrea.io/antrea/third_party/proxy"
)
var (
// _ _ _ _ _ _
// / \ | |_| |_ ___ _ __ | |_(_) ___ _ __ | |
// / _ \| __| __/ _ \ '_ \| __| |/ _ \| '_ \ | |
// / ___ \ |_| || __/ | | | |_| | (_) | | | | |_|
// /_/ \_\__|\__\___|_| |_|\__|_|\___/|_| |_| (_)
//
// Before adding a new table in FlexiblePipeline, please read the following instructions carefully.
//
// - Double confirm the necessity of adding a new table, and consider reusing an existing table to implement the
// functionality alternatively.
// - Choose a name that can help users to understand the function of the table.
// - Choose a stage. Existing stageIDs are defined in file pkg/agent/openflow/framework.go. If you want to add a new
// stage, please discuss with maintainers or OVS pipeline developers of Antrea.
// - Choose a pipeline. Existing pipelineIDs are defined in file pkg/agent/openflow/framework.go. If you want to add
// a new pipeline, please discuss with maintainers or OVS pipeline developers of Antrea.
// - Decide where to add the new table in the pipeline. The order table declaration decides the order of tables in the
// stage. For example:
// * If you want to add a table called `FooTable` between `SpoofGuardTable` and `IPv6Table` in pipelineIP, then
// the table should be declared after `SpoofGuardTable` and before `IPv6Table`:
// ```go
// SpoofGuardTable = newTable("SpoofGuard", stageValidation, pipelineIP)
// FooTable = newTable("Foo", stageValidation, pipelineIP)
// IPv6Table = newTable("IPv6", stageValidation, pipelineIP)
// ```
// * If you want to add a table called `FooTable` just before `ARPResponderTable` in pipelineARP, then the table
// should be declared before `ARPResponderTable`:
// ```go
// FooTable = newTable("Foo", stageOutput, binding.PipelineARP)
// ARPResponderTable = newTable("ARPResponder", stageOutput, binding.PipelineARP)
// ```
// * If you want to add a table called `FooTable` just after `ConntrackStateTable` in pipelineARP, then the
// table should be declared after `ConntrackStateTable`:
// ```go
// UnSNATTable = newTable("UnSNAT", stageConntrackState, pipelineIP)
// ConntrackTable = newTable("ConntrackZone", stageConntrackState, pipelineIP)
// ConntrackStateTable = newTable("ConntrackState", stageConntrackState, pipelineIP)
// FooTable = newTable("Foo", stageConntrackState, pipelineIP)
// ```
// - Reference the new table in a feature in file pkg/agent/openflow/framework.go. The table can be referenced by multiple
// features if multiple features need to install flows in the table. Note that, if the newly added table is not
// referenced by any feature or the features referencing the table are all inactivated, then the table will not
// be realized in OVS; if at least one feature referencing the table is activated, then the table will be realized
// at the desired position in OVS pipeline.
// - By default, the miss action of the new table is to forward packets to next table. If the miss action needs to
// drop packets, add argument defaultDrop when creating the new table.
//
// How to forward packet between tables with a proper action in FlexiblePipeline?
//
// | table A | | table B | | table C | | table D | | table E | | table F | | table G |
// | stage S1 | | stage S2 | | stage S4 |
//
// - NextTable is used to forward packets to the next table. E.g. A -> B, B -> C, C -> D, etc.
// - GotoTable is used to forward packets to a specific table, and the target table ID should be greater than the
// current table ID. Within a stage, GotoTable should be used to forward packets to a specific table, e.g. B -> D,
// C -> E. Today we do not have the case, but if in future there is a case that a packet needs to be forwarded to
// a table in another stage directly, e.g. A -> C, B -> G, GotoTable can also be used.
// - GotoStage is used to forward packets to a specific stage. Note that, packets are forwarded to the first table of
// the target stage, and the first table ID of the target stage should be greater than the current table ID. E.g.
// A -> S4 (F), D -> S4 (F) are fine, but D -> S1 (A), F -> S2 (B) are not allowed. It is recommended to use
// GotoStage to forward packets across stages.
// - ResubmitToTables is used to forward packets to one or multiple tables. It should be used only when the target
// table ID is smaller than the current table ID, like E -> B; or when forwarding packets to multiple tables,
// like B - > D E; otherwise, in all other cases GotoTable should be used.
// Tables of PipelineRoot are declared below.
// PipelineRootClassifierTable is the only table of pipelineRoot at this moment and its table ID should be 0. Packets
// are forwarded to pipelineIP or pipelineARP in this table.
PipelineRootClassifierTable = newTable("PipelineRootClassifier", stageStart, pipelineRoot, defaultDrop)
// Tables of pipelineARP are declared below.
// Tables in stageValidation:
ARPSpoofGuardTable = newTable("ARPSpoofGuard", stageValidation, pipelineARP)
// Tables in stageOutput:
ARPResponderTable = newTable("ARPResponder", stageOutput, pipelineARP)
// Tables of pipelineIP are declared below.
// Tables in stageClassifier:
ClassifierTable = newTable("Classifier", stageClassifier, pipelineIP, defaultDrop)
// Tables in stageValidation:
SpoofGuardTable = newTable("SpoofGuard", stageValidation, pipelineIP, defaultDrop)
IPv6Table = newTable("IPv6", stageValidation, pipelineIP)
PipelineIPClassifierTable = newTable("PipelineIPClassifier", stageValidation, pipelineIP)
// Tables in stageConntrackState:
UnSNATTable = newTable("UnSNAT", stageConntrackState, pipelineIP)
ConntrackTable = newTable("ConntrackZone", stageConntrackState, pipelineIP)
ConntrackStateTable = newTable("ConntrackState", stageConntrackState, pipelineIP)
// Tables in stagePreRouting:
// When proxy is enabled.
PreRoutingClassifierTable = newTable("PreRoutingClassifier", stagePreRouting, pipelineIP)
NodePortMarkTable = newTable("NodePortMark", stagePreRouting, pipelineIP)
SessionAffinityTable = newTable("SessionAffinity", stagePreRouting, pipelineIP)
ServiceLBTable = newTable("ServiceLB", stagePreRouting, pipelineIP)
EndpointDNATTable = newTable("EndpointDNAT", stagePreRouting, pipelineIP)
// When proxy is disabled.
DNATTable = newTable("DNAT", stagePreRouting, pipelineIP)
// Tables in stageEgressSecurity:
EgressSecurityClassifierTable = newTable("EgressSecurityClassifier", stageEgressSecurity, pipelineIP)
AntreaPolicyEgressRuleTable = newTable("AntreaPolicyEgressRule", stageEgressSecurity, pipelineIP)
EgressRuleTable = newTable("EgressRule", stageEgressSecurity, pipelineIP)
EgressDefaultTable = newTable("EgressDefaultRule", stageEgressSecurity, pipelineIP)
EgressMetricTable = newTable("EgressMetric", stageEgressSecurity, pipelineIP)
// Tables in stageRouting:
L3ForwardingTable = newTable("L3Forwarding", stageRouting, pipelineIP)
EgressMarkTable = newTable("EgressMark", stageRouting, pipelineIP)
L3DecTTLTable = newTable("L3DecTTL", stageRouting, pipelineIP)
// Tables in stagePostRouting:
SNATMarkTable = newTable("SNATMark", stagePostRouting, pipelineIP)
SNATTable = newTable("SNAT", stagePostRouting, pipelineIP)
// Tables in stageSwitching:
L2ForwardingCalcTable = newTable("L2ForwardingCalc", stageSwitching, pipelineIP)
TrafficControlTable = newTable("TrafficControl", stageSwitching, pipelineIP)
// Tables in stageIngressSecurity:
IngressSecurityClassifierTable = newTable("IngressSecurityClassifier", stageIngressSecurity, pipelineIP)
AntreaPolicyIngressRuleTable = newTable("AntreaPolicyIngressRule", stageIngressSecurity, pipelineIP)
IngressRuleTable = newTable("IngressRule", stageIngressSecurity, pipelineIP)
IngressDefaultTable = newTable("IngressDefaultRule", stageIngressSecurity, pipelineIP)
IngressMetricTable = newTable("IngressMetric", stageIngressSecurity, pipelineIP)
// Tables in stageConntrack:
ConntrackCommitTable = newTable("ConntrackCommit", stageConntrack, pipelineIP)
// Tables in stageOutput:
VLANTable = newTable("VLAN", stageOutput, pipelineIP)
L2ForwardingOutTable = newTable("Output", stageOutput, pipelineIP)
// Tables of pipelineMulticast are declared below. Do don't declare any tables of other pipelines here!
// Tables in stageEgressSecurity:
// Since IGMP Egress rules only support IGMP report which is handled by packetIn, it is not necessary to add
// MulticastIGMPEgressMetricTable here.
MulticastEgressRuleTable = newTable("MulticastEgressRule", stageEgressSecurity, pipelineMulticast)
MulticastEgressMetricTable = newTable("MulticastEgressMetric", stageEgressSecurity, pipelineMulticast)
MulticastEgressPodMetricTable = newTable("MulticastEgressPodMetric", stageEgressSecurity, pipelineMulticast)
// Tables in stageRouting:
MulticastRoutingTable = newTable("MulticastRouting", stageRouting, pipelineMulticast)
// Tables in stageIngressSecurity
MulticastIngressRuleTable = newTable("MulticastIngressRule", stageIngressSecurity, pipelineMulticast)
MulticastIngressMetricTable = newTable("MulticastIngressMetric", stageIngressSecurity, pipelineMulticast)
MulticastIngressPodMetricTable = newTable("MulticastIngressPodMetric", stageIngressSecurity, pipelineMulticast)
// Tables in stageOutput
MulticastOutputTable = newTable("MulticastOutput", stageOutput, pipelineMulticast)
// NonIPTable is used when Antrea Agent is running on an external Node. It forwards the non-IP packet
// between the uplink and its pair port directly.
NonIPTable = newTable("NonIP", stageClassifier, pipelineNonIP, defaultDrop)
// Flow priority level
priorityHigh = uint16(210)
priorityNormal = uint16(200)
priorityLow = uint16(190)
priorityMiss = uint16(0)
priorityTopAntreaPolicy = uint16(64990)
priorityDNSIntercept = uint16(64991)
priorityDNSBypass = uint16(64992)
// Index for priority cache
priorityIndex = "priority"
// IPv6 multicast prefix
ipv6MulticastAddr = "FF00::/8"
// IPv6 link-local prefix
ipv6LinkLocalAddr = "FE80::/10"
// Operation field values in ARP packets
arpOpRequest = uint16(1)
arpOpReply = uint16(2)
tableNameIndex = "tableNameIndex"
)
type ofAction int32
const (
add ofAction = iota
mod
del
)
func (a ofAction) String() string {
switch a {
case add:
return "add"
case mod:
return "modify"
case del:
return "delete"
default:
return "unknown"
}
}
// tableCache caches the OpenFlow tables used in pipelines, and it supports using the table ID and name as the index to query the OpenFlow table.
var tableCache = cache.NewIndexer(tableIDKeyFunc, cache.Indexers{tableNameIndex: tableNameIndexFunc})
func tableNameIndexFunc(obj interface{}) ([]string, error) {
table := obj.(*Table)
return []string{table.GetName()}, nil
}
func tableIDKeyFunc(obj interface{}) (string, error) {
table := obj.(*Table)
return fmt.Sprintf("%d", table.GetID()), nil
}
func getTableByID(id uint8) binding.Table {
obj, exists, _ := tableCache.GetByKey(fmt.Sprintf("%d", id))
if !exists {
return nil
}
return obj.(*Table).ofTable
}
// GetFlowTableName returns the flow table name given the table ID. An empty
// string is returned if the table cannot be found.
func GetFlowTableName(tableID uint8) string {
table := getTableByID(tableID)
if table == nil {
return ""
}
return table.GetName()
}
// GetFlowTableID does a case insensitive lookup of the table name, and
// returns the flow table number if the table is found. Otherwise TableIDAll is
// returned if the table cannot be found.
func GetFlowTableID(tableName string) uint8 {
objs, _ := tableCache.ByIndex(tableNameIndex, tableName)
if len(objs) == 0 {
return binding.TableIDAll
}
return objs[0].(binding.Table).GetID()
}
func GetTableList() []binding.Table {
tables := make([]binding.Table, 0)
for _, obj := range tableCache.List() {
t := obj.(binding.Table)
tables = append(tables, t)
}
return tables
}
func GetAntreaPolicyEgressTables() []*Table {
return []*Table{
AntreaPolicyEgressRuleTable,
EgressDefaultTable,
}
}
func GetAntreaIGMPIngressTables() []*Table {
return []*Table{
MulticastIngressRuleTable,
}
}
func GetAntreaMulticastEgressTables() []*Table {
return []*Table{
MulticastEgressRuleTable,
}
}
func GetAntreaPolicyIngressTables() []*Table {
return []*Table{
AntreaPolicyIngressRuleTable,
IngressDefaultTable,
}
}
func GetAntreaPolicyBaselineTierTables() []*Table {
return []*Table{
EgressDefaultTable,
IngressDefaultTable,
}
}
func GetAntreaPolicyMultiTierTables() []*Table {
return []*Table{
AntreaPolicyEgressRuleTable,
AntreaPolicyIngressRuleTable,
}
}
const (
CtZone = 0xfff0
CtZoneV6 = 0xffe6
SNATCtZone = 0xfff1
SNATCtZoneV6 = 0xffe7
// disposition values used in AP
DispositionAllow = 0b00
DispositionDrop = 0b01
DispositionRej = 0b10
DispositionPass = 0b11
// CustomReasonLogging is used when send packet-in to controller indicating this
// packet need logging.
CustomReasonLogging = 0b01
// CustomReasonReject is not only used when send packet-in to controller indicating
// that this packet should be rejected, but also used in the case that when
// controller send reject packet as packet-out, we want reject response to bypass
// the connTrack to avoid unexpected drop.
CustomReasonReject = 0b10
// CustomReasonDeny is used when sending packet-in message to controller indicating
// that the corresponding connection has been dropped or rejected. It can be consumed
// by the Flow Exporter to export flow records for connections denied by network
// policy rules.
CustomReasonDeny = 0b100
CustomReasonDNS = 0b1000
CustomReasonIGMP = 0b10000
// EtherTypeDot1q is used when adding 802.1Q VLAN header in OVS action
EtherTypeDot1q = 0x8100
)
var DispositionToString = map[uint32]string{
DispositionAllow: "Allow",
DispositionDrop: "Drop",
DispositionRej: "Reject",
DispositionPass: "Pass",
}
var (
// snatPktMarkRange takes an 8-bit range of pkt_mark to store the ID of
// a SNAT IP. The bit range must match SNATIPMarkMask.
snatPktMarkRange = &binding.Range{0, 7}
GlobalVirtualMAC, _ = net.ParseMAC("aa:bb:cc:dd:ee:ff")
)
type OFEntryOperations interface {
Add(flow binding.Flow) error
Modify(flow binding.Flow) error
Delete(flow binding.Flow) error
AddAll(flows []binding.Flow) error
ModifyAll(flows []binding.Flow) error
BundleOps(adds []binding.Flow, mods []binding.Flow, dels []binding.Flow) error
DeleteAll(flows []binding.Flow) error
AddOFEntries(ofEntries []binding.OFEntry) error
DeleteOFEntries(ofEntries []binding.OFEntry) error
}
type flowCache map[string]binding.Flow
type flowCategoryCache struct {
sync.Map
}
type client struct {
enableProxy bool
proxyAll bool
enableAntreaPolicy bool
enableDenyTracking bool
enableEgress bool
enableMulticast bool
enableTrafficControl bool
enableMulticluster bool
connectUplinkToBridge bool
nodeType config.NodeType
roundInfo types.RoundInfo
cookieAllocator cookie.Allocator
bridge binding.Bridge
featurePodConnectivity *featurePodConnectivity
featureService *featureService
featureEgress *featureEgress
featureNetworkPolicy *featureNetworkPolicy
featureMulticast *featureMulticast
featureMulticluster *featureMulticluster
featureExternalNodeConnectivity *featureExternalNodeConnectivity
activatedFeatures []feature
featureTraceflow *featureTraceflow
traceableFeatures []traceableFeature
pipelines map[binding.PipelineID]binding.Pipeline
// ofEntryOperations is a wrapper interface for OpenFlow entry Add / Modify / Delete operations. It
// enables convenient mocking in unit tests.
ofEntryOperations OFEntryOperations
// replayMutex provides exclusive access to the OFSwitch to the ReplayFlows method.
replayMutex sync.RWMutex
nodeConfig *config.NodeConfig
networkConfig *config.NetworkConfig
egressConfig *config.EgressConfig
serviceConfig *config.ServiceConfig
// ovsMetersAreSupported indicates whether the OVS datapath supports OpenFlow meters.
ovsMetersAreSupported bool
// packetInHandlers stores handler to process PacketIn event. Each packetin reason can have multiple handlers registered.
// When a packetin arrives, openflow send packet to registered handlers in this map.
packetInHandlers map[uint8]map[string]PacketInHandler
// Supported IP Protocols (IP or IPv6) on the current Node.
ipProtocols []binding.Protocol
// ovsctlClient is the interface for executing OVS "ovs-ofctl" and "ovs-appctl" commands.
ovsctlClient ovsctl.OVSCtlClient
}
func (c *client) GetTunnelVirtualMAC() net.HardwareAddr {
return GlobalVirtualMAC
}
func (c *client) changeAll(flowsMap map[ofAction][]binding.Flow) error {
if len(flowsMap) == 0 {
return nil
}
startTime := time.Now()
defer func() {
d := time.Since(startTime)
for k, v := range flowsMap {
if len(v) != 0 {
metrics.OVSFlowOpsLatency.WithLabelValues(k.String()).Observe(float64(d.Milliseconds()))
}
}
}()
if err := c.bridge.AddFlowsInBundle(flowsMap[add], flowsMap[mod], flowsMap[del]); err != nil {
for k, v := range flowsMap {
if len(v) != 0 {
metrics.OVSFlowOpsErrorCount.WithLabelValues(k.String()).Inc()
}
}
return err
}
for k, v := range flowsMap {
if len(v) != 0 {
metrics.OVSFlowOpsCount.WithLabelValues(k.String()).Inc()
}
}
return nil
}
func (c *client) Add(flow binding.Flow) error {
return c.AddAll([]binding.Flow{flow})
}
func (c *client) Modify(flow binding.Flow) error {
return c.ModifyAll([]binding.Flow{flow})
}
func (c *client) Delete(flow binding.Flow) error {
return c.DeleteAll([]binding.Flow{flow})
}
func (c *client) AddAll(flows []binding.Flow) error {
return c.changeAll(map[ofAction][]binding.Flow{add: flows})
}
func (c *client) ModifyAll(flows []binding.Flow) error {
return c.changeAll(map[ofAction][]binding.Flow{mod: flows})
}
func (c *client) DeleteAll(flows []binding.Flow) error {
return c.changeAll(map[ofAction][]binding.Flow{del: flows})
}
func (c *client) BundleOps(adds []binding.Flow, mods []binding.Flow, dels []binding.Flow) error {
return c.changeAll(map[ofAction][]binding.Flow{add: adds, mod: mods, del: dels})
}
func (c *client) changeOFEntries(ofEntries []binding.OFEntry, action ofAction) error {
if len(ofEntries) == 0 {
return nil
}
var adds, mods, dels []binding.OFEntry
if action == add {
adds = ofEntries
} else if action == mod {
mods = ofEntries
} else if action == del {
dels = ofEntries
} else {
return fmt.Errorf("OF Entries Action not exists: %s", action)
}
startTime := time.Now()
defer func() {
d := time.Since(startTime)
metrics.OVSFlowOpsLatency.WithLabelValues(action.String()).Observe(float64(d.Milliseconds()))
}()
if err := c.bridge.AddOFEntriesInBundle(adds, mods, dels); err != nil {
metrics.OVSFlowOpsErrorCount.WithLabelValues(action.String()).Inc()
return err
}
metrics.OVSFlowOpsCount.WithLabelValues(action.String()).Inc()
return nil
}
func (c *client) AddOFEntries(ofEntries []binding.OFEntry) error {
return c.changeOFEntries(ofEntries, add)
}
func (c *client) DeleteOFEntries(ofEntries []binding.OFEntry) error {
return c.changeOFEntries(ofEntries, del)
}
func (c *client) defaultFlows() []binding.Flow {
cookieID := c.cookieAllocator.Request(cookie.Default).Raw()
var flows []binding.Flow
for id, pipeline := range c.pipelines {
// This generates the default flow for every table in every pipeline.
for _, table := range pipeline.ListAllTables() {
flowBuilder := table.BuildFlow(priorityMiss).Cookie(cookieID)
switch table.GetMissAction() {
case binding.TableMissActionNext:
flowBuilder = flowBuilder.Action().NextTable()
case binding.TableMissActionNormal:
flowBuilder = flowBuilder.Action().Normal()
case binding.TableMissActionDrop:
flowBuilder = flowBuilder.Action().Drop()
case binding.TableMissActionNone:
fallthrough
default:
continue
}
flows = append(flows, flowBuilder.Done())
}
switch id {
case pipelineIP:
// This generates the flow to match IPv4 / IPv6 packets and forward them to the first table of pipelineIP in
// PipelineRootClassifierTable.
for _, ipProtocol := range c.ipProtocols {
flows = append(flows, pipelineClassifyFlow(cookieID, ipProtocol, pipeline))
}
case pipelineARP:
// This generates the flow to match ARP packets and forward them to the first table of pipelineARP in
// PipelineRootClassifierTable.
flows = append(flows, pipelineClassifyFlow(cookieID, binding.ProtocolARP, pipeline))
case pipelineMulticast:
// This generates the flow to match multicast packets and forward them to the first table of pipelineMulticast
// in PipelineIPClassifierTable. Note that, PipelineIPClassifierTable is in stageValidation of pipeline for IP. In another word,
// pipelineMulticast is forked from PipelineIPClassifierTable in pipelineIP.
flows = append(flows, multicastPipelineClassifyFlow(cookieID, pipeline))
case pipelineNonIP:
flows = append(flows, nonIPPipelineClassifyFlow(cookieID, pipeline))
}
}
return flows
}
// tunnelClassifierFlow generates the flow to mark the packets from tunnel port.
func (f *featurePodConnectivity) tunnelClassifierFlow(tunnelOFPort uint32) binding.Flow {
return ClassifierTable.ofTable.BuildFlow(priorityNormal).
Cookie(f.cookieAllocator.Request(f.category).Raw()).
MatchInPort(tunnelOFPort).
Action().LoadRegMark(FromTunnelRegMark, RewriteMACRegMark).
Action().GotoStage(stageConntrackState).
Done()
}
// gatewayClassifierFlow generates the flow to mark the packets from the Antrea gateway port.
func (f *featurePodConnectivity) gatewayClassifierFlow() binding.Flow {
return ClassifierTable.ofTable.BuildFlow(priorityNormal).
Cookie(f.cookieAllocator.Request(f.category).Raw()).
MatchInPort(f.gatewayPort).
Action().LoadRegMark(FromGatewayRegMark).
Action().GotoStage(stageValidation).
Done()
}
// podClassifierFlow generates the flow to mark the packets from a local Pod port.
func (f *featurePodConnectivity) podClassifierFlow(podOFPort uint32, isAntreaFlexibleIPAM bool) binding.Flow {
regMarksToLoad := []*binding.RegMark{FromLocalRegMark}
if isAntreaFlexibleIPAM {
regMarksToLoad = append(regMarksToLoad, AntreaFlexibleIPAMRegMark, RewriteMACRegMark)
}
return ClassifierTable.ofTable.BuildFlow(priorityLow).
Cookie(f.cookieAllocator.Request(f.category).Raw()).
MatchInPort(podOFPort).
Action().LoadRegMark(regMarksToLoad...).
Action().GotoStage(stageValidation).
Done()
}
// podUplinkClassifierFlows generates the flows to mark the packets with target destination MAC address from uplink/bridge
// port, which are needed when uplink is connected to OVS bridge and Antrea IPAM is configured.
func (f *featurePodConnectivity) podUplinkClassifierFlows(dstMAC net.HardwareAddr, vlanID uint16) []binding.Flow {
cookieID := f.cookieAllocator.Request(f.category).Raw()
var flows []binding.Flow
nonVLAN := true
if vlanID > 0 {
nonVLAN = false
}
for _, ipProtocol := range f.ipProtocols {
flows = append(flows,
// This generates the flow to mark the packets from uplink port.
ClassifierTable.ofTable.BuildFlow(priorityHigh).
Cookie(cookieID).
MatchInPort(f.uplinkPort).
MatchDstMAC(dstMAC).
MatchVLAN(nonVLAN, vlanID, nil).
MatchProtocol(ipProtocol).
Action().LoadRegMark(f.ipCtZoneTypeRegMarks[ipProtocol], FromUplinkRegMark).
Action().LoadToRegField(VLANIDField, uint32(vlanID)).
Action().GotoStage(stageConntrackState).
Done(),
)
if vlanID == 0 {
flows = append(flows,
// This generates the flow to mark the packets from bridge local port.
ClassifierTable.ofTable.BuildFlow(priorityHigh).
Cookie(cookieID).
MatchInPort(f.hostIfacePort).
MatchDstMAC(dstMAC).
MatchVLAN(true, 0, nil).
MatchProtocol(ipProtocol).
Action().LoadRegMark(f.ipCtZoneTypeRegMarks[ipProtocol], FromBridgeRegMark).
Action().GotoStage(stageConntrackState).
Done(),
)
}
}
return flows
}
// conntrackFlows generates the flows about conntrack for feature PodConnectivity.
func (f *featurePodConnectivity) conntrackFlows() []binding.Flow {
cookieID := f.cookieAllocator.Request(f.category).Raw()
var flows []binding.Flow
for _, ipProtocol := range f.ipProtocols {
flows = append(flows,
// This generates the flow to transform the destination IP of request packets or source IP of reply packets
// from tracked connections in CT zone.
ConntrackTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
Action().CT(false, ConntrackTable.GetNext(), f.ctZones[ipProtocol], f.ctZoneSrcField).
NAT().
CTDone().
Done(),
// This generates the flow to match the packets of tracked non-Service connection and forward them to
// stageEgressSecurity directly to bypass stagePreRouting. The first packet of non-Service connection passes
// through stagePreRouting, and the subsequent packets go to stageEgressSecurity directly.
ConntrackStateTable.ofTable.BuildFlow(priorityLow).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateNew(false).
MatchCTStateTrk(true).
Action().GotoStage(stageEgressSecurity).
Done(),
// This generates the flow to drop invalid packets.
ConntrackStateTable.ofTable.BuildFlow(priorityHigh).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateInv(true).
MatchCTStateTrk(true).
Action().Drop().
Done(),
// This generates the flow to match the first packet of non-Service connection and mark the source of the connection
// by copying PktSourceField to ConnSourceCTMarkField.
ConntrackCommitTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateNew(true).
MatchCTStateTrk(true).
MatchCTStateSNAT(false).
MatchCTMark(NotServiceCTMark).
Action().CT(true, ConntrackCommitTable.GetNext(), f.ctZones[ipProtocol], f.ctZoneSrcField).
MoveToCtMarkField(PktSourceField, ConnSourceCTMarkField).
CTDone().
Done(),
)
}
// This generates default flow to match the first packet of a new connection and forward it to stagePreRouting.
flows = append(flows, ConntrackStateTable.ofTable.BuildFlow(priorityMiss).
Cookie(cookieID).
Action().GotoStage(stagePreRouting).
Done())
return flows
}
// conntrackFlows generates the flows about conntrack for feature Service.
func (f *featureService) conntrackFlows() []binding.Flow {
cookieID := f.cookieAllocator.Request(f.category).Raw()
var flows []binding.Flow
for _, ipProtocol := range f.ipProtocols {
flows = append(flows,
// This generates the flow to mark tracked DNATed Service connection with RewriteMACRegMark (load-balanced by
// AntreaProxy) and forward the packets to stageEgressSecurity directly to bypass stagePreRouting.
ConntrackStateTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTMark(ServiceCTMark).
MatchCTStateNew(false).
MatchCTStateTrk(true).
Action().LoadRegMark(RewriteMACRegMark).
Action().GotoStage(stageEgressSecurity).
Done(),
)
}
return flows
}
// snatConntrackFlows generates the flows about conntrack of SNAT connection for feature Service.
func (f *featureService) snatConntrackFlows() []binding.Flow {
cookieID := f.cookieAllocator.Request(f.category).Raw()
var flows []binding.Flow
for _, ipProtocol := range f.ipProtocols {
gatewayIP := f.gatewayIPs[ipProtocol]
// virtualIP is used as SNAT IP when a request's source IP is gateway IP and we need to forward it back to
// gateway interface to avoid asymmetry path.
virtualIP := f.virtualIPs[ipProtocol]
flows = append(flows,
// SNAT should be performed for the following connections:
// - Hairpin Service connection initiated through a local Pod, and SNAT should be performed with the Antrea
// gateway IP.
// - Hairpin Service connection initiated through the Antrea gateway, and SNAT should be performed with a
// virtual IP.
// - Nodeport / LoadBalancer connection initiated through the Antrea gateway and externalTrafficPolicy is
// Cluster, if the selected Endpoint is not on local Node, then SNAT should be performed with the Antrea
// gateway IP.
// Note that, for Service connections that require SNAT, ServiceCTMark is loaded in SNAT CT zone when performing
// SNAT since ServiceCTMark loaded in DNAT CT zone cannot be read in SNAT CT zone. For Service connections,
// ServiceCTMark (loaded in DNAT / SNAT CT zone) is used to bypass ConntrackCommitTable which is used to commit
// non-Service connections. For hairpin connections, HairpinCTMark is also loaded in SNAT CT zone when performing
// SNAT since HairpinCTMark loaded in DNAT CT zone also cannot be read in SNAT CT zone. HairpinCTMark is used
// to output packets of hairpin connections in L2ForwardingOutTable.
// This generates the flow to match the first packet of hairpin Service connection initiated through the Antrea
// gateway with ConnSNATCTMark and HairpinCTMark, then perform SNAT in SNAT CT zone with a virtual IP.
SNATTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateNew(true).
MatchCTStateTrk(true).
MatchRegMark(FromGatewayRegMark).
MatchCTMark(HairpinCTMark).
Action().CT(true, SNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
SNAT(&binding.IPRange{StartIP: virtualIP, EndIP: virtualIP}, nil).
LoadToCtMark(ServiceCTMark, HairpinCTMark).
CTDone().
Done(),
// This generates the flow to unSNAT reply packets of connections committed in SNAT CT zone by the above flow.
UnSNATTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchDstIP(virtualIP).
Action().CT(false, UnSNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
NAT().
CTDone().
Done(),
// This generates the flow to match the first packet of hairpin Service connection initiated through a Pod with
// ConnSNATCTMark and HairpinCTMark, then perform SNAT in SNAT CT zone with the Antrea gateway IP.
SNATTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateNew(true).
MatchCTStateTrk(true).
MatchRegMark(FromLocalRegMark).
MatchCTMark(HairpinCTMark).
Action().CT(true, SNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
SNAT(&binding.IPRange{StartIP: gatewayIP, EndIP: gatewayIP}, nil).
LoadToCtMark(ServiceCTMark, HairpinCTMark).
CTDone().
Done(),
// This generates the flow to match the first packet of NodePort / LoadBalancer connection (non-hairpin) initiated
// through the Antrea gateway with ConnSNATCTMark, then perform SNAT in SNAT CT zone with the Antrea gateway IP.
SNATTable.ofTable.BuildFlow(priorityLow).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateNew(true).
MatchCTStateTrk(true).
MatchRegMark(FromGatewayRegMark).
MatchCTMark(ConnSNATCTMark).
Action().CT(true, SNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
SNAT(&binding.IPRange{StartIP: gatewayIP, EndIP: gatewayIP}, nil).
LoadToCtMark(ServiceCTMark).
CTDone().
Done(),
// This generates the flow to unSNAT reply packets of connections committed in SNAT CT zone by the above flows.
UnSNATTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchDstIP(gatewayIP).
Action().CT(false, UnSNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
NAT().
CTDone().
Done(),
// This generates the flow to match the subsequent request packets of connection whose first request packet has
// been committed in SNAT CT zone, then commit the packets in SNAT CT zone again to perform SNAT.
// For example:
/*
* 192.168.77.1 is the IP address of client.
* 192.168.77.100 is the IP address of K8s Node.
* 30001 is the NodePort port.
* 10.10.0.1 is the IP address of Antrea gateway.
* 10.10.0.3 is the IP of NodePort Service Endpoint.
* packet 1 (request)
* client 192.168.77.1:12345->192.168.77.100:30001
* CT zone SNAT 65521 192.168.77.1:12345->192.168.77.100:30001
* CT zone DNAT 65520 192.168.77.1:12345->192.168.77.100:30001
* CT commit DNAT zone 65520 192.168.77.1:12345->192.168.77.100:30001 => 192.168.77.1:12345->10.10.0.3:80
* CT commit SNAT zone 65521 192.168.77.1:12345->10.10.0.3:80 => 10.10.0.1:12345->10.10.0.3:80
* output
* packet 2 (reply)
* Pod 10.10.0.3:80->10.10.0.1:12345
* CT zone SNAT 65521 10.10.0.3:80->10.10.0.1:12345 => 10.10.0.3:80->192.168.77.1:12345
* CT zone DNAT 65520 10.10.0.3:80->192.168.77.1:12345 => 192.168.77.1:30001->192.168.77.1:12345
* output
* packet 3 (request)
* client 192.168.77.1:12345->192.168.77.100:30001
* CT zone SNAT 65521 192.168.77.1:12345->192.168.77.100:30001
* CT zone DNAT 65520 192.168.77.1:12345->10.10.0.3:80
* CT zone SNAT 65521 192.168.77.1:12345->10.10.0.3:80 => 10.10.0.1:12345->10.10.0.3:80
* output
* packet ...
*/
// As a result, subsequent request packets like packet 3 will only perform SNAT when they pass through SNAT
// CT zone the second time, after they are DNATed in DNAT CT zone.
SNATTable.ofTable.BuildFlow(priorityNormal).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTMark(ConnSNATCTMark).
MatchCTStateNew(false).
MatchCTStateTrk(true).
MatchCTStateRpl(false).
Action().CT(false, SNATTable.GetNext(), f.snatCtZones[ipProtocol], nil).
NAT().
CTDone().
Done(),
)
}
return flows
}
// dnsResponseBypassConntrackFlow generates the flow to bypass the dns response packetout from conntrack, to avoid unexpected
// packet drop. This flow should be installed on the first table of stageConntrackState.
func (f *featureNetworkPolicy) dnsResponseBypassConntrackFlow(table binding.Table) binding.Flow {
return table.BuildFlow(priorityHigh).
MatchRegFieldWithValue(CustomReasonField, CustomReasonDNS).
Cookie(f.cookieAllocator.Request(cookie.Default).Raw()).
Action().GotoStage(stageSwitching).
Done()
}
// dnsResponseBypassPacketInFlow generates the flow to bypass the dns packetIn conjunction flow for dns response packetOut.
// This packetOut should be sent directly to the requesting client without being intercepted again.
func (f *featureNetworkPolicy) dnsResponseBypassPacketInFlow() binding.Flow {
// TODO: use a unified register bit to mark packetOuts. The pipeline does not need to be
// aware of why the packetOut is being set by the controller, it just needs to be aware that
// this is a packetOut message and that some pipeline stages (conntrack, policy enforcement)
// should therefore be skipped.
return AntreaPolicyIngressRuleTable.ofTable.BuildFlow(priorityDNSBypass).
Cookie(f.cookieAllocator.Request(cookie.Default).Raw()).
MatchRegFieldWithValue(CustomReasonField, CustomReasonDNS).
Action().GotoStage(stageOutput).
Done()
}
// TODO: Use DuplicateToBuilder or integrate this function into original one to avoid unexpected difference.
// flowsToTrace generates Traceflow specific flows in the connectionTrackStateTable or L2ForwardingCalcTable for featurePodConnectivity.
// When packet is not provided, the flows bypass the drop flow in conntrackStateFlow to avoid unexpected drop of the
// injected Traceflow packet, and to drop any Traceflow packet that has ct_state +rpl, which may happen when the Traceflow
// request destination is the Node's IP. When packet is provided, a flow is added to mark - the first packet of the first
// connection that matches the provided packet - as the Traceflow packet. The flow is added in connectionTrackStateTable
// when receiverOnly is false and it also matches in_port to be the provided ofPort (the sender Pod); otherwise when
// receiverOnly is true, the flow is added into L2ForwardingCalcTable and matches the destination MAC (the receiver Pod MAC).
func (f *featurePodConnectivity) flowsToTrace(dataplaneTag uint8,
ovsMetersAreSupported,
liveTraffic,
droppedOnly,
receiverOnly bool,
packet *binding.Packet,
ofPort uint32,
timeout uint16) []binding.Flow {
cookieID := f.cookieAllocator.Request(cookie.Traceflow).Raw()
var flows []binding.Flow
if packet == nil {
for _, ipProtocol := range f.ipProtocols {
flows = append(flows,
ConntrackStateTable.ofTable.BuildFlow(priorityLow+1).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchIPDSCP(dataplaneTag).
SetHardTimeout(timeout).
Action().GotoStage(stagePreRouting).
Done(),
ConntrackStateTable.ofTable.BuildFlow(priorityLow+2).
Cookie(cookieID).
MatchProtocol(ipProtocol).
MatchCTStateTrk(true).
MatchCTStateRpl(true).
MatchIPDSCP(dataplaneTag).
SetHardTimeout(timeout).
Action().Drop().
Done(),
)
}
} else {
var flowBuilder binding.FlowBuilder
if !receiverOnly {
flowBuilder = ConntrackStateTable.ofTable.BuildFlow(priorityLow).
Cookie(cookieID).
MatchInPort(ofPort).
MatchCTStateNew(true).
MatchCTStateTrk(true).
Action().LoadIPDSCP(dataplaneTag).
SetHardTimeout(timeout).
Action().GotoStage(stagePreRouting)
if packet.DestinationIP != nil {
flowBuilder = flowBuilder.MatchDstIP(packet.DestinationIP)
}
} else {
flowBuilder = L2ForwardingCalcTable.ofTable.BuildFlow(priorityHigh).
Cookie(cookieID).
MatchCTStateNew(true).
MatchCTStateTrk(true).
MatchDstMAC(packet.DestinationMAC).
Action().LoadToRegField(TargetOFPortField, ofPort).
Action().LoadRegMark(OFPortFoundRegMark).
Action().LoadIPDSCP(dataplaneTag).
SetHardTimeout(timeout).
Action().GotoStage(stageIngressSecurity)
if packet.SourceIP != nil {
flowBuilder = flowBuilder.MatchSrcIP(packet.SourceIP)
}
}
// Match transport header
switch packet.IPProto {
case protocol.Type_ICMP:
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolICMP)
case protocol.Type_IPv6ICMP:
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolICMPv6)
case protocol.Type_TCP:
if packet.IsIPv6 {
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolTCPv6)
} else {
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolTCP)
}
case protocol.Type_UDP:
if packet.IsIPv6 {
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolUDPv6)
} else {
flowBuilder = flowBuilder.MatchProtocol(binding.ProtocolUDP)
}
default:
flowBuilder = flowBuilder.MatchIPProtocolValue(packet.IsIPv6, packet.IPProto)
}
if packet.IPProto == protocol.Type_TCP || packet.IPProto == protocol.Type_UDP {
if packet.DestinationPort != 0 {
flowBuilder = flowBuilder.MatchDstPort(packet.DestinationPort, nil)
}