forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint_dataplane.go
More file actions
3207 lines (2863 loc) · 112 KB
/
Copy pathint_dataplane.go
File metadata and controls
3207 lines (2863 loc) · 112 KB
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 (c) 2020-2026 Tigera, Inc. All rights reserved.
//
// 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 intdataplane
import (
"context"
"errors"
"fmt"
"net"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
apiv3 "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
"github.com/projectcalico/api/pkg/lib/numorstring"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"k8s.io/client-go/kubernetes"
"github.com/projectcalico/calico/felix/bpf"
"github.com/projectcalico/calico/felix/bpf/bpfmap"
bpfconntrack "github.com/projectcalico/calico/felix/bpf/conntrack"
bpftimeouts "github.com/projectcalico/calico/felix/bpf/conntrack/timeouts"
"github.com/projectcalico/calico/felix/bpf/events"
"github.com/projectcalico/calico/felix/bpf/failsafes"
bpfifstate "github.com/projectcalico/calico/felix/bpf/ifstate"
bpfipsets "github.com/projectcalico/calico/felix/bpf/ipsets"
bpfmaps "github.com/projectcalico/calico/felix/bpf/maps"
bpfnat "github.com/projectcalico/calico/felix/bpf/nat"
bpfproxy "github.com/projectcalico/calico/felix/bpf/proxy"
"github.com/projectcalico/calico/felix/bpf/qos"
bpfringbuf "github.com/projectcalico/calico/felix/bpf/ringbuf"
bpfroutes "github.com/projectcalico/calico/felix/bpf/routes"
"github.com/projectcalico/calico/felix/bpf/tc"
tcdefs "github.com/projectcalico/calico/felix/bpf/tc/defs"
bpfutils "github.com/projectcalico/calico/felix/bpf/utils"
"github.com/projectcalico/calico/felix/calc"
"github.com/projectcalico/calico/felix/collector"
collectortypes "github.com/projectcalico/calico/felix/collector/types"
felixconfig "github.com/projectcalico/calico/felix/config"
"github.com/projectcalico/calico/felix/dataplane/common"
dpsets "github.com/projectcalico/calico/felix/dataplane/ipsets"
"github.com/projectcalico/calico/felix/dataplane/linux/dataplanedefs"
"github.com/projectcalico/calico/felix/environment"
"github.com/projectcalico/calico/felix/generictables"
"github.com/projectcalico/calico/felix/idalloc"
"github.com/projectcalico/calico/felix/ifacemonitor"
"github.com/projectcalico/calico/felix/ipsets"
"github.com/projectcalico/calico/felix/iptables"
"github.com/projectcalico/calico/felix/iptables/cmdshim"
"github.com/projectcalico/calico/felix/jitter"
"github.com/projectcalico/calico/felix/labelindex/ipsetmember"
"github.com/projectcalico/calico/felix/linkaddrs"
"github.com/projectcalico/calico/felix/logutils"
"github.com/projectcalico/calico/felix/netlinkshim"
"github.com/projectcalico/calico/felix/nftables"
"github.com/projectcalico/calico/felix/proto"
"github.com/projectcalico/calico/felix/routerule"
"github.com/projectcalico/calico/felix/routetable"
"github.com/projectcalico/calico/felix/routetable/ownershippol"
"github.com/projectcalico/calico/felix/rules"
"github.com/projectcalico/calico/felix/throttle"
"github.com/projectcalico/calico/felix/types"
"github.com/projectcalico/calico/felix/vxlanfdb"
"github.com/projectcalico/calico/felix/wireguard"
"github.com/projectcalico/calico/libcalico-go/lib/health"
"github.com/projectcalico/calico/libcalico-go/lib/ipam"
lclogutils "github.com/projectcalico/calico/libcalico-go/lib/logutils"
cprometheus "github.com/projectcalico/calico/libcalico-go/lib/prometheus"
"github.com/projectcalico/calico/libcalico-go/lib/set"
)
const (
// msgPeekLimit is the maximum number of messages we'll try to grab from our channels
// before we apply the changes. Higher values allow us to batch up more work on
// the channel for greater throughput when we're under load (at cost of higher latency).
msgPeekLimit = 100
// Interface name used by kube-proxy to bind service ips.
KubeIPVSInterface = "kube-ipvs0"
// Route cleanup grace period. Used for workload routes only.
routeCleanupGracePeriod = 10 * time.Second
)
var (
countDataplaneSyncErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_int_dataplane_failures",
Help: "Number of times dataplane updates failed and will be retried.",
})
countMessages = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "felix_int_dataplane_messages",
Help: "Number dataplane messages by type.",
}, []string{"type"})
gaugeInitialResyncApplyTime = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "felix_int_dataplane_initial_resync_time_seconds",
Help: "Time in seconds that it took to do the initial resync with " +
"the dataplane and bring the dataplane into sync for the first time.",
})
summaryApplyTime = cprometheus.NewSummary(prometheus.SummaryOpts{
Name: "felix_int_dataplane_apply_time_seconds",
Help: "Time in seconds for each incremental update to the dataplane " +
"(after the initial resync).",
})
summaryBatchSize = cprometheus.NewSummary(prometheus.SummaryOpts{
Name: "felix_int_dataplane_msg_batch_size",
Help: "Number of messages processed in each batch. Higher values indicate we're " +
"doing more batching to try to keep up.",
})
summaryIfaceBatchSize = cprometheus.NewSummary(prometheus.SummaryOpts{
Name: "felix_int_dataplane_iface_msg_batch_size",
Help: "Number of interface state messages processed in each batch. Higher " +
"values indicate we're doing more batching to try to keep up.",
})
summaryAddrBatchSize = cprometheus.NewSummary(prometheus.SummaryOpts{
Name: "felix_int_dataplane_addr_msg_batch_size",
Help: "Number of interface address messages processed in each batch. Higher " +
"values indicate we're doing more batching to try to keep up.",
})
processStartTime time.Time
zeroKey = wgtypes.Key{}
maxCleanupRetries = 5
)
func init() {
prometheus.MustRegister(countDataplaneSyncErrors)
prometheus.MustRegister(gaugeInitialResyncApplyTime)
prometheus.MustRegister(summaryApplyTime)
prometheus.MustRegister(countMessages)
prometheus.MustRegister(summaryBatchSize)
prometheus.MustRegister(summaryIfaceBatchSize)
prometheus.MustRegister(summaryAddrBatchSize)
processStartTime = time.Now()
}
type Config struct {
Hostname string
NodeZone string
IPv6Enabled bool
RuleRendererOverride rules.RuleRenderer
IPIPMTU int
VXLANMTU int
VXLANMTUV6 int
VXLANPort int
MaxIPSetSize int
RouteSyncDisabled bool
IptablesBackend string
IPSetsRefreshInterval time.Duration
RouteRefreshInterval time.Duration
DeviceRouteSourceAddress net.IP
DeviceRouteSourceAddressIPv6 net.IP
DeviceRouteProtocol netlink.RouteProtocol
RemoveExternalRoutes bool
ProgramClusterRoutes bool
NoEncapEnabled bool
IPForwarding string
TableRefreshInterval time.Duration
IptablesPostWriteCheckInterval time.Duration
IptablesInsertMode string
IptablesLockTimeout time.Duration
IptablesLockProbeInterval time.Duration
XDPRefreshInterval time.Duration
FloatingIPsEnabled bool
LocalSubnetL2Reachability string
LocalSubnetL2ReachabilityRefreshInterval time.Duration
Wireguard wireguard.Config
NetlinkTimeout time.Duration
RulesConfig rules.Config
IfaceMonitorConfig ifacemonitor.Config
StatusReportingInterval time.Duration
ConfigChangedRestartCallback func()
FatalErrorRestartCallback func(error)
PostInSyncCallback func()
HealthAggregator *health.HealthAggregator
WatchdogTimeout time.Duration
RouteTableManager *idalloc.IndexAllocator
bpfProxyHealthCheck bpfproxy.Healthcheck
DebugSimulateDataplaneHangAfter time.Duration
DebugSimulateDataplaneApplyDelay time.Duration
ExternalNodesCidrs []string
BPFEnabled bool
BPFPolicyDebugEnabled bool
BPFDisableUnprivileged bool
BPFJITHardening string
BPFKubeProxyIptablesCleanupEnabled bool
BPFLogLevel string
BPFConntrackLogLevel string
BPFLogFilters map[string]string
BPFCTLBLogFilter string
BPFExtToServiceConnmark int
BPFDataIfacePattern *regexp.Regexp
BPFL3IfacePattern *regexp.Regexp
XDPEnabled bool
XDPAllowGeneric bool
BPFConntrackCleanupMode apiv3.BPFConntrackMode
BPFConntrackTimeouts bpftimeouts.Timeouts
BPFCgroupV2 string
BPFConnTimeLBEnabled bool
BPFConnTimeLB string
BPFHostNetworkedNAT string
BPFNodePortDSREnabled bool
BPFDSROptoutCIDRs []string
BPFPSNATPorts numorstring.Port
BPFMapSizeRoute int
BPFMapSizeConntrack int
BPFMapSizePerCPUConntrack int
BPFMapSizeConntrackScaling string
BPFMapSizeConntrackCleanupQueue int
BPFMapSizeNATFrontend int
BPFMapSizeNATBackend int
BPFMapSizeNATAffinity int
BPFMapSizeIPSets int
BPFMapSizeIfState int
BPFMapSizeMaglev int
BPFMaglevLUTSize int
BPFIpv6Enabled bool
BPFHostConntrackBypass bool
BPFIPFragmentReassemblyEnabled bool
BPFEnforceRPF string
BPFDisableGROForIfaces *regexp.Regexp
BPFExcludeCIDRsFromNAT []string
BPFExportBufferSizeMB int
BPFRedirectToPeer string
BPFAttachType apiv3.BPFAttachOption
BPFIPFragTimeout time.Duration
BPFProfiling string
KubeProxyMinSyncPeriod time.Duration
KubeProxyHealtzPort int
SidecarAccelerationEnabled bool
WorkloadSourceSpoofing bool
// Flow logs related fields.
NfNetlinkBufSize int
Collector collector.Collector
LookupsCache *calc.LookupsCache
FlowLogsEnabled bool
ServiceLoopPrevention string
LookPathOverride func(file string) (string, error)
KubeClientSet kubernetes.Interface
FeatureDetectOverrides map[string]string
FeatureGates map[string]string
// Populated with the smallest host MTU based on auto-detection.
hostMTU int
MTUIfacePattern *regexp.Regexp
RequireMTUFile bool
RouteSource string
IPv4NormalRoutePriority int
IPv4ElevatedRoutePriority int
IPv6NormalRoutePriority int
IPv6ElevatedRoutePriority int
LiveMigrationRouteConvergenceTime time.Duration
// IPAMClient is the Calico IPAM client used to swap owner attributes
// when a KubeVirt live migration completes.
IPAMClient ipam.Interface
KubernetesProvider felixconfig.Provider
// For testing purposes - allows unit tests to mock out the creation of the nftables dataplane.
NewNftablesDataplane nftables.NewNftablesDataplaneFn
}
type UpdateBatchResolver interface {
// Opportunity for a manager component to resolve state that depends jointly on the updates
// that it has seen since the preceding CompleteDeferredWork call. Processing here can
// include passing resolved state to other managers. It should not include any actual
// dataplane updates yet. (Those should be actioned in CompleteDeferredWork.)
ResolveUpdateBatch() error
}
// InternalDataplane implements an in-process Felix dataplane driver based on iptables
// and ipsets. It communicates with the datastore-facing part of Felix via the
// Send/RecvMessage methods, which operate on the protobuf-defined API objects.
//
// # Architecture
//
// The internal dataplane driver is organised around a main event loop, which handles
// update events from the datastore and dataplane.
//
// Each pass around the main loop has two phases. In the first phase, updates are fanned
// out to "manager" objects, which calculate the changes that are needed and pass them to
// the dataplane programming layer. In the second phase, the dataplane layer applies the
// updates in a consistent sequence. The second phase is skipped until the datastore is
// in sync; this ensures that the first update to the dataplane applies a consistent
// snapshot.
//
// Having the dataplane layer batch updates has several advantages. It is much more
// efficient to batch updates, since each call to iptables/ipsets has a high fixed cost.
// In addition, it allows for different managers to make updates without having to
// coordinate on their sequencing.
//
// # Requirements on the API
//
// The internal dataplane does not do consistency checks on the incoming data (as the
// old Python-based driver used to do). It expects to be told about dependent resources
// before they are needed and for their lifetime to exceed that of the resources that
// depend on them. For example, it is important that the datastore layer sends an IP set
// create event before it sends a rule that references that IP set.
type InternalDataplane struct {
toDataplane chan any
fromDataplane chan any
sendDataplaneInSyncOnce sync.Once
mainRouteTables []routetable.SyncerInterface
allTables []generictables.Table
mangleTables []generictables.Table
natTables []generictables.Table
rawTables []generictables.Table
filterTables []generictables.Table
arpTables []generictables.Table
ipSets []dpsets.IPSetsDataplane
ipipParentIfaceC chan string
ipipManager *ipipManager
noEncapManager *noEncapManager
noEncapManagerV6 *noEncapManager
noEncapParentIfaceC chan string
noEncapParentIfaceCV6 chan string
vxlanParentIfaceC chan string
vxlanParentIfaceCV6 chan string
vxlanManager *vxlanManager
vxlanManagerV6 *vxlanManager
vxlanFDBs []*vxlanfdb.VXLANFDB
linkAddrsManagers []linkaddrs.Interface
wireguardManager *wireguardManager
wireguardManagerV6 *wireguardManager
ifaceMonitor *ifacemonitor.InterfaceMonitor
ifaceUpdates chan any
liveMigrationMonitor *liveMigrationMonitor
endpointStatusCombiner *endpointStatusCombiner
allManagers []Manager
managersWithRouteTables []ManagerWithRouteTables
managersWithRouteRules []ManagerWithRouteRules
ruleRenderer rules.RuleRenderer
// datastoreInSync is set to true after we receive the "in sync" message from the datastore.
// We delay programming of the dataplane until we're in sync with the datastore.
datastoreInSync bool
// ifaceMonitorInSync is set to true after the interface monitor reports that it is in sync.
// As above, we block dataplane updates until we get that message.
ifaceMonitorInSync bool
// dataplaneNeedsSync is set if the dataplane is dirty in some way, i.e. we need to
// call apply().
dataplaneNeedsSync bool
// forceIPSetsRefresh is set by the IP sets refresh timer to indicate that we should
// check the IP sets in the dataplane.
forceIPSetsRefresh bool
// forceRouteRefresh is set by the route refresh timer to indicate that we should
// check the routes in the dataplane.
forceRouteRefresh bool
// forceXDPRefresh is set by the XDP refresh timer to indicate that we should
// check the XDP state in the dataplane.
forceXDPRefresh bool
// doneFirstApply is set after we finish the first update to the dataplane. It indicates
// that the dataplane should now be in sync, though it is possible that an error occurred
// necessitating a re-apply.
doneFirstApply bool
reschedTimer *time.Timer
reschedC <-chan time.Time
applyThrottle *throttle.Throttle
config Config
debugHangC <-chan time.Time
xdpState *xdpState
sockmapState *sockmapState
endpointsSourceV4 endpointsSource
ipsetsSourceV4 ipsetsSource
callbacks *common.Callbacks
loopSummarizer *logutils.Summarizer
// Fields used to accumulate counts of messages of various types before we report them to
// prometheus.
datastoreBatchSize int
linkUpdateBatchSize int
addrsUpdateBatchSize int
actions generictables.ActionFactory
newMatch func() generictables.MatchCriteria
// nftablesEnabled tracks whether we are using nftables on this node.
nftablesEnabled bool
// kubeProxyNftablesEnabled tracks whether kube-proxy is running in nftables mode on this node.
kubeProxyNftablesEnabled bool
// getKubeProxyNftablesEnabled is a function that can be called to re-check whether kube-proxy
// is running in nftables mode.
getKubeProxyNftablesEnabled func() (bool, error)
}
const (
healthName = "InternalDataplaneMainLoop"
healthInterval = 10 * time.Second
ipipMTUOverhead = 20
vxlanMTUOverhead = 50
vxlanV6MTUOverhead = 70
wireguardMTUOverhead = 60
wireguardV6MTUOverhead = 80
aksMTUOverhead = 100
)
func NewIntDataplaneDriver(config Config) *InternalDataplane {
if config.BPFLogLevel == "info" {
config.BPFLogLevel = "off"
}
log.WithField("config", config).Info("Creating internal dataplane driver.")
// Decide whether to use nftables or iptables based on configuration and kube-proxy mode.
detectKubeProxyNftablesMode := nftables.KubeProxyNftablesEnabledFn(config.NewNftablesDataplane)
kubeProxyNftablesEnabled, err := detectKubeProxyNftablesMode()
if err != nil {
log.WithError(err).Panic("Unable to detect kube-proxy nftables mode, shutting down")
}
nftablesEnabled := useNftables(config.RulesConfig.NFTablesMode, kubeProxyNftablesEnabled)
ruleRenderer := config.RuleRendererOverride
if ruleRenderer == nil {
ruleRenderer = rules.NewRenderer(config.RulesConfig, nftablesEnabled)
}
epMarkMapper := rules.NewEndpointMarkMapper(
config.RulesConfig.MarkEndpoint,
config.RulesConfig.MarkNonCaliEndpoint)
// Auto-detect host MTU.
hostMTU, err := findHostMTU(config.MTUIfacePattern)
if err != nil {
log.WithError(err).Panic("Unable to detect host MTU, shutting down")
return nil
}
ConfigureDefaultMTUs(hostMTU, &config)
podMTU := determinePodMTU(config)
if err := writeMTUFile(podMTU); err != nil {
// Fail early if RequireMTUFile is true
if config.RequireMTUFile {
log.WithError(err).Error("Failed to write MTU file shutting, down")
return nil
}
log.WithError(err).Error("Failed to write MTU file, pod MTU may not be properly set")
}
featureDetector := environment.NewFeatureDetector(
config.FeatureDetectOverrides,
environment.WithFeatureGates(config.FeatureGates),
)
// Determine the action set and new match function based on the underlying generictables implementation.
actionSet := iptables.Actions()
newMatchFn := iptables.Match
if nftablesEnabled {
actionSet = nftables.Actions()
newMatchFn = nftables.Match
}
dp := &InternalDataplane{
toDataplane: make(chan any, msgPeekLimit),
fromDataplane: make(chan any, 100),
ruleRenderer: ruleRenderer,
ifaceMonitor: ifacemonitor.New(config.IfaceMonitorConfig, featureDetector, config.FatalErrorRestartCallback),
ifaceUpdates: make(chan any, 100),
config: config,
applyThrottle: throttle.New(10),
loopSummarizer: logutils.NewSummarizer("dataplane reconciliation loops"),
actions: actionSet,
newMatch: newMatchFn,
nftablesEnabled: nftablesEnabled,
kubeProxyNftablesEnabled: kubeProxyNftablesEnabled,
getKubeProxyNftablesEnabled: detectKubeProxyNftablesMode,
}
dp.applyThrottle.Refill() // Allow the first apply() immediately.
dp.liveMigrationMonitor = newLiveMigrationMonitor(config.LiveMigrationRouteConvergenceTime, config.IPAMClient)
dp.RegisterManager(dp.liveMigrationMonitor)
dp.ifaceMonitor.StateCallback = dp.onIfaceStateChange
dp.ifaceMonitor.AddrCallback = dp.onIfaceAddrsChange
dp.ifaceMonitor.InSyncCallback = dp.onIfaceInSync
backendMode := environment.DetectBackend(config.LookPathOverride, cmdshim.NewRealCmd, config.IptablesBackend)
// Most tables need the same options.
iptablesOptions := iptables.TableOptions{
HistoricChainPrefixes: rules.AllHistoricChainNamePrefixes,
InsertMode: config.IptablesInsertMode,
RefreshInterval: config.TableRefreshInterval,
PostWriteInterval: config.IptablesPostWriteCheckInterval,
LockProbeInterval: config.IptablesLockProbeInterval,
BackendMode: backendMode,
LookPathOverride: config.LookPathOverride,
OnStillAlive: dp.reportHealth,
OpRecorder: dp.loopSummarizer,
}
nftablesOptions := nftables.TableOptions{
RefreshInterval: config.TableRefreshInterval,
LookPathOverride: config.LookPathOverride,
OnStillAlive: dp.reportHealth,
OpRecorder: dp.loopSummarizer,
Disabled: !nftablesEnabled,
NewDataplane: config.NewNftablesDataplane,
}
var cleanupTables []generictables.Table
if config.BPFEnabled && config.BPFKubeProxyIptablesCleanupEnabled {
// If BPF-mode is enabled, clean up kube-proxy's rules too.
log.Info("BPF enabled, configuring iptables/nftables layer to clean up kube-proxy's rules.")
iptablesOptions.ExtraCleanupRegexPattern = rules.KubeProxyInsertRuleRegex
iptablesOptions.HistoricChainPrefixes = append(iptablesOptions.HistoricChainPrefixes, rules.KubeProxyChainPrefixes...)
// Delete the ip kube-proxy and ip6 kube-proxy tables in nftables.
nftablesKPOptions := nftablesOptions
nftablesKPOptions.Disabled = true
kubeProxyTableV4NFT := nftables.NewTable("kube-proxy", 4, rules.RuleHashPrefix, featureDetector, nftablesKPOptions, nftablesEnabled)
cleanupTables = append(cleanupTables, kubeProxyTableV4NFT)
if config.IPv6Enabled {
kubeProxyTableV6NFT := nftables.NewTable("kube-proxy", 6, rules.RuleHashPrefix, featureDetector, nftablesKPOptions, nftablesEnabled)
cleanupTables = append(cleanupTables, kubeProxyTableV6NFT)
}
}
if config.BPFEnabled && !config.BPFPolicyDebugEnabled {
err := os.RemoveAll(bpf.RuntimePolDir)
if err != nil && !os.IsNotExist(err) {
log.WithError(err).Info("Policy debug disabled but failed to remove the debug directory. Ignoring.")
}
}
// However, the NAT tables need an extra cleanup regex.
iptablesNATOptions := iptablesOptions
if iptablesNATOptions.ExtraCleanupRegexPattern == "" {
iptablesNATOptions.ExtraCleanupRegexPattern = rules.HistoricInsertedNATRuleRegex
} else {
iptablesNATOptions.ExtraCleanupRegexPattern += "|" + rules.HistoricInsertedNATRuleRegex
}
// iptables and nftables implementations.
var mangleTableV4NFT, natTableV4NFT, rawTableV4NFT, filterTableV4NFT generictables.Table
var mangleTableV4IPT, natTableV4IPT, rawTableV4IPT, filterTableV4IPT generictables.Table
// This is required when nftables mode is configured; but also useful for cleanup in other modes.
nftablesV4RootTable := nftables.NewTable("calico", 4, rules.RuleHashPrefix, featureDetector, nftablesOptions, nftablesEnabled)
if nftablesEnabled {
// Create nftables Table implementations.
mangleTableV4NFT = nftables.NewTableLayer("mangle", nftablesV4RootTable)
natTableV4NFT = nftables.NewTableLayer("nat", nftablesV4RootTable)
rawTableV4NFT = nftables.NewTableLayer("raw", nftablesV4RootTable)
filterTableV4NFT = nftables.NewTableLayer("filter", nftablesV4RootTable)
}
// Create iptables table implementations.
mangleTableV4IPT = iptables.NewTable("mangle", 4, rules.RuleHashPrefix, featureDetector, iptablesOptions)
natTableV4IPT = iptables.NewTable("nat", 4, rules.RuleHashPrefix, featureDetector, iptablesNATOptions)
rawTableV4IPT = iptables.NewTable("raw", 4, rules.RuleHashPrefix, featureDetector, iptablesOptions)
filterTableV4IPT = iptables.NewTable("filter", 4, rules.RuleHashPrefix, featureDetector, iptablesOptions)
// Based on configuration, some of the above tables should be active and others not.
var mangleTableV4, natTableV4, rawTableV4, filterTableV4 generictables.Table
var ipSetsV4 dpsets.IPSetsDataplane
var cleanupIPSets []dpsets.IPSetsDataplane
if nftablesEnabled {
// Enable nftables.
mangleTableV4 = mangleTableV4NFT
natTableV4 = natTableV4NFT
rawTableV4 = rawTableV4NFT
filterTableV4 = filterTableV4NFT
ipSetsV4 = nftablesV4RootTable
// Cleanup iptables.
cleanupTables = append(cleanupTables,
mangleTableV4IPT,
natTableV4IPT,
rawTableV4IPT,
filterTableV4IPT,
)
cleanupIPSets = append(cleanupIPSets, ipsets.NewIPSets(config.RulesConfig.IPSetConfigV4, dp.loopSummarizer))
} else {
// Enable iptables.
mangleTableV4 = mangleTableV4IPT
natTableV4 = natTableV4IPT
rawTableV4 = rawTableV4IPT
filterTableV4 = filterTableV4IPT
ipSetsV4 = ipsets.NewIPSets(config.RulesConfig.IPSetConfigV4, dp.loopSummarizer)
if nftablesV4RootTable != nil {
// Cleanup nftables - we can simply add the root table here, Since
// all the other tables / ipsets / maps are handled by the root table.
cleanupTables = append(cleanupTables, nftablesV4RootTable)
}
}
dp.natTables = append(dp.natTables, natTableV4)
dp.rawTables = append(dp.rawTables, rawTableV4)
dp.mangleTables = append(dp.mangleTables, mangleTableV4)
dp.filterTables = append(dp.filterTables, filterTableV4)
dp.ipSets = append(dp.ipSets, ipSetsV4)
var routeTableV4 routetable.Interface
var routeTableV6 routetable.Interface
var mainTablePolV4 *ownershippol.MainTableOwnershipPolicy
var mainTablePolV6 *ownershippol.MainTableOwnershipPolicy
if !config.RouteSyncDisabled {
log.Debug("Route management is enabled.")
mainTablePolV4 = ownershippol.NewMainTable(
dataplanedefs.VXLANIfaceNameV4,
config.DeviceRouteProtocol,
config.RulesConfig.WorkloadIfacePrefixes,
config.RemoveExternalRoutes,
)
routeTableV4 = routetable.New(
mainTablePolV4,
4,
config.NetlinkTimeout,
config.DeviceRouteSourceAddress,
config.DeviceRouteProtocol,
config.RemoveExternalRoutes,
unix.RT_TABLE_MAIN,
dp.loopSummarizer,
featureDetector,
routetable.WithStaticARPEntries(true),
routetable.WithLivenessCB(dp.reportHealth),
routetable.WithRouteCleanupGracePeriod(routeCleanupGracePeriod),
)
if config.IPv6Enabled {
mainTablePolV6 = ownershippol.NewMainTable(
dataplanedefs.VXLANIfaceNameV6,
config.DeviceRouteProtocol,
config.RulesConfig.WorkloadIfacePrefixes,
config.RemoveExternalRoutes,
)
routeTableV6 = routetable.New(
mainTablePolV6,
6,
config.NetlinkTimeout,
config.DeviceRouteSourceAddressIPv6,
config.DeviceRouteProtocol,
config.RemoveExternalRoutes,
unix.RT_TABLE_MAIN,
dp.loopSummarizer,
featureDetector,
// Note: deliberately not including:
// - Static neighbor entries: we've never supported these for IPv6;
// we let the kernel populate them.
routetable.WithLivenessCB(dp.reportHealth),
routetable.WithRouteCleanupGracePeriod(routeCleanupGracePeriod),
)
}
} else {
log.Info("Route management is disabled, using DummyTables.")
routeTableV4 = &routetable.DummyTable{}
if config.IPv6Enabled {
routeTableV6 = &routetable.DummyTable{}
}
}
dp.mainRouteTables = append(dp.mainRouteTables, routeTableV4)
if routeTableV6 != nil {
dp.mainRouteTables = append(dp.mainRouteTables, routeTableV6)
}
// Start a noEncap manager if an IP pool with no encapsulation exists.
if config.ProgramClusterRoutes && config.NoEncapEnabled {
log.Info("NoEncap IP pool present, starting thread to keep IPv4 noencap routes in sync.")
dp.noEncapManager = newNoEncapManager(
routeTableV4,
4,
config,
dp.loopSummarizer,
)
dp.noEncapParentIfaceC = make(chan string, 1)
go dp.noEncapManager.monitorParentDevice(
context.Background(),
time.Second*10,
dp.noEncapParentIfaceC,
)
dp.RegisterManager(dp.noEncapManager)
if config.IPv6Enabled {
log.Info("NoEncap IP pool present, starting thread to keep IPv6 noencap routes in sync.")
dp.noEncapManagerV6 = newNoEncapManager(
routeTableV6,
6,
config,
dp.loopSummarizer,
)
dp.noEncapParentIfaceCV6 = make(chan string, 1)
go dp.noEncapManagerV6.monitorParentDevice(
context.Background(),
time.Second*10,
dp.noEncapParentIfaceCV6,
)
dp.RegisterManager(dp.noEncapManagerV6)
}
}
// Register the proxy neighbor managers when enabled. They listen on raw sockets
// and respond to ARP (IPv4) / NDP (IPv6) requests for pod and LB IPs that fall
// within the same subnet as a host physical interface.
if apiv3.LocalSubnetL2ReachabilityMode(config.LocalSubnetL2Reachability) != apiv3.LocalSubnetL2ReachabilityDisabled {
proxyNeighMgr4 := newProxyNeighManager(config, 4)
dp.RegisterManager(proxyNeighMgr4)
if config.IPv6Enabled {
proxyNeighMgr6 := newProxyNeighManager(config, 6)
dp.RegisterManager(proxyNeighMgr6)
}
}
dataplaneFeatures := featureDetector.GetFeatures()
if config.RulesConfig.VXLANEnabled {
var fdbOpts []vxlanfdb.Option
if config.BPFEnabled {
fdbOpts = append(fdbOpts, vxlanfdb.WithNeighUpdatesOnly())
}
vxlanFDB := vxlanfdb.New(netlink.FAMILY_V4, dataplanedefs.VXLANIfaceNameV4, featureDetector, config.NetlinkTimeout, fdbOpts...)
dp.vxlanFDBs = append(dp.vxlanFDBs, vxlanFDB)
dp.vxlanManager = newVXLANManager(
ipSetsV4,
routeTableV4,
vxlanFDB,
dataplanedefs.VXLANIfaceNameV4,
4,
config.VXLANMTU,
config,
dp.loopSummarizer,
)
dp.vxlanParentIfaceC = make(chan string, 1)
vxlanMTU := config.VXLANMTU
if config.BPFEnabled {
vxlanMTU = 0
}
go dp.vxlanManager.keepVXLANDeviceInSync(
context.Background(),
vxlanMTU,
dataplaneFeatures.ChecksumOffloadBroken,
10*time.Second,
dp.vxlanParentIfaceC,
)
dp.RegisterManager(dp.vxlanManager)
} else {
// Start a cleanup goroutine not to block felix if it needs to retry
go cleanUpVXLANDevice(dataplanedefs.VXLANIfaceNameV4)
}
dp.endpointStatusCombiner = newEndpointStatusCombiner(dp.fromDataplane, config.IPv6Enabled)
callbacks := common.NewCallbacks()
dp.callbacks = callbacks
if config.XDPEnabled {
if err := bpf.SupportsXDP(); err != nil {
log.WithError(err).Warn("Can't enable XDP acceleration.")
config.XDPEnabled = false
} else if !config.BPFEnabled {
st, err := NewXDPState(config.XDPAllowGeneric)
if err != nil {
log.WithError(err).Warn("Can't enable XDP acceleration.")
} else {
dp.xdpState = st
dp.xdpState.PopulateCallbacks(callbacks)
dp.RegisterManager(st)
log.Info("XDP acceleration enabled.")
}
}
} else {
log.Info("XDP acceleration disabled.")
}
// TODO Support cleaning up non-BPF XDP state from a previous Felix run, when BPF mode has just been enabled.
if !config.BPFEnabled && dp.xdpState == nil {
xdpState, err := NewXDPState(config.XDPAllowGeneric)
if err == nil {
if err := xdpState.WipeXDP(); err != nil {
log.WithError(err).Warn("Failed to cleanup preexisting XDP state")
}
}
// if we can't create an XDP state it means we couldn't get a working
// bpffs so there's nothing to clean up
}
if config.SidecarAccelerationEnabled {
if err := bpf.SupportsSockmap(); err != nil {
log.WithError(err).Warn("Can't enable Sockmap acceleration.")
} else {
st, err := NewSockmapState()
if err != nil {
log.WithError(err).Warn("Can't enable Sockmap acceleration.")
} else {
dp.sockmapState = st
dp.sockmapState.PopulateCallbacks(callbacks)
if err := dp.sockmapState.SetupSockmapAcceleration(); err != nil {
dp.sockmapState = nil
log.WithError(err).Warn("Failed to set up Sockmap acceleration")
} else {
log.Info("Sockmap acceleration enabled.")
}
}
}
}
if dp.sockmapState == nil {
st, err := NewSockmapState()
if err == nil {
st.WipeSockmap(bpf.FindInBPFFSOnly)
}
// if we can't create a sockmap state it means we couldn't get a working
// bpffs so there's nothing to clean up
}
ipsetsManager := dpsets.NewIPSetsManager("ipv4", ipSetsV4, config.MaxIPSetSize)
ipsetsManagerV6 := dpsets.NewIPSetsManager("ipv6", nil, config.MaxIPSetSize)
// iptables / nftables specific filter Table implementations for IPv6.
var filterTableV6NFT, filterTableV6IPT generictables.Table
// Create nftables Table implementations for IPv6.
nftablesV6RootTable := nftables.NewTable("calico", 6, rules.RuleHashPrefix, featureDetector, nftablesOptions, nftablesEnabled)
filterTableV6NFT = nftables.NewTableLayer("filter", nftablesV6RootTable)
// Create iptables Table implementations for IPv6.
filterTableV6IPT = iptables.NewTable("filter", 6, rules.RuleHashPrefix, featureDetector, iptablesOptions)
// Select the correct table implementation based on whether we're using nftables or iptables.
var filterTableV6 generictables.Table
if nftablesEnabled {
filterTableV6 = filterTableV6NFT
} else {
filterTableV6 = filterTableV6IPT
}
dp.RegisterManager(ipsetsManager)
if !config.BPFEnabled {
// BPF mode disabled, create the iptables/nftables-only managers.
dp.ipsetsSourceV4 = ipsetsManager
// TODO Connect host IP manager to BPF
dp.RegisterManager(newHostIPManager(
config.RulesConfig.WorkloadIfacePrefixes,
rules.IPSetIDThisHostIPs,
ipSetsV4,
config.MaxIPSetSize))
dp.RegisterManager(newPolicyManager(rawTableV4, mangleTableV4, filterTableV4, ruleRenderer, 4, nftablesEnabled))
// Clean up any leftover BPF state.
err := bpfnat.RemoveConnectTimeLoadBalancer(true, "")
if err != nil {
log.WithError(err).Info("Failed to remove BPF connect-time load balancer, ignoring.")
}
tc.CleanUpProgramsAndPins()
bpfutils.RemoveBPFSpecialDevices()
} else {
// In BPF mode we still use iptables for raw egress policy.
dp.RegisterManager(newRawEgressPolicyManager(rawTableV4, ruleRenderer, 4, ipSetsV4.SetFilter, nftablesEnabled))
}
interfaceRegexes := make([]string, len(config.RulesConfig.WorkloadIfacePrefixes))
for i, r := range config.RulesConfig.WorkloadIfacePrefixes {
interfaceRegexes[i] = "^" + r + ".*"
}
defaultRPFilter, err := os.ReadFile("/proc/sys/net/ipv4/conf/default/rp_filter")
if err != nil {
log.Warn("could not determine default rp_filter setting, defaulting to strict")
defaultRPFilter = []byte{'1'}
}
bpfMapSizeConntrack := config.BPFMapSizeConntrack
if config.BPFMapSizePerCPUConntrack > 0 {
bpfMapSizeConntrack = config.BPFMapSizePerCPUConntrack * bpfmaps.NumPossibleCPUs()
}
bpfMapSizeConntrackResizeSize, _ := conntrackMapSizeFromFile()
if bpfMapSizeConntrackResizeSize > bpfMapSizeConntrack {
log.Infof("Overriding bpfMapSizeConntrack (%d) with map size growth (%d)",
bpfMapSizeConntrack, bpfMapSizeConntrackResizeSize)
bpfMapSizeConntrack = bpfMapSizeConntrackResizeSize
}
bpfipsets.SetMapSize(config.BPFMapSizeIPSets)
bpfnat.SetMapSizes(config.BPFMapSizeNATFrontend, config.BPFMapSizeNATBackend, config.BPFMapSizeNATAffinity, config.BPFMapSizeMaglev)
bpfroutes.SetMapSize(config.BPFMapSizeRoute)
bpfconntrack.SetMapSize(bpfMapSizeConntrack)
bpfconntrack.SetCleanupMapSize(config.BPFMapSizeConntrackCleanupQueue)
bpfifstate.SetMapSize(config.BPFMapSizeIfState)
ringBufSize := calcRingBufSize(config.BPFExportBufferSizeMB)
bpfringbuf.SetMapSize(ringBufSize)
var (
bpfEndpointManager *bpfEndpointManager
bpfEvnt events.Events
bpfEventPoller *bpfEventPoller
collectorPacketInfoReader collectortypes.PacketInfoReader
collectorConntrackInfoReader collectortypes.ConntrackInfoReader
)
// Initialisation needed for bpf.
if config.BPFEnabled && config.FlowLogsEnabled {
var err error
bpfEvnt, err = events.New(events.SourceRingBuffer, ringBufSize)
if err != nil {
log.WithError(err).Error("Failed to create ring buffer event source")
} else {
bpfEventPoller = newBpfEventPoller(bpfEvnt)
}
}
if config.BPFEnabled {
log.Info("BPF enabled, starting BPF endpoint manager and map manager.")
bpfMaps, err := bpfmap.CreateBPFMaps(config.BPFIpv6Enabled)
if err != nil {
log.WithError(err).Panic("error creating bpf maps")
}
// Register map managers first since they create the maps that will be used by the endpoint manager.
// Important that we create the maps before we load a BPF program with TC since we make sure the map
// metadata name is set whereas TC doesn't set that field.
var conntrackScannerV4, conntrackScannerV6 *bpfconntrack.Scanner
var workloadRemoveChanV4, workloadRemoveChanV6 chan string
var ipSetIDAllocatorV4, ipSetIDAllocatorV6 *idalloc.IDAllocator
ipSetIDAllocatorV4 = idalloc.New()
if config.RulesConfig.IstioAmbientModeEnabled {
ipSetIDAllocatorV4.ReserveWellKnownID(rules.IPSetIDAllIstioWEPs, bpfipsets.AllIstioWEPsID)
}
// Start IPv4 BPF dataplane components
conntrackScannerV4, workloadRemoveChanV4 = startBPFDataplaneComponents(proto.IPVersion_IPV4, bpfMaps.V4, ipSetIDAllocatorV4, &config, ipsetsManager, dp)
if config.BPFIpv6Enabled {
// Start IPv6 BPF dataplane components
ipSetIDAllocatorV6 = idalloc.New()
if config.RulesConfig.IstioAmbientModeEnabled {
ipSetIDAllocatorV6.ReserveWellKnownID(rules.IPSetIDAllIstioWEPs, bpfipsets.AllIstioWEPsID)
}
conntrackScannerV6, workloadRemoveChanV6 = startBPFDataplaneComponents(proto.IPVersion_IPV6, bpfMaps.V6, ipSetIDAllocatorV6, &config, ipsetsManagerV6, dp)
}
workloadIfaceRegex := regexp.MustCompile(strings.Join(interfaceRegexes, "|"))
if config.BPFConnTimeLB == string(apiv3.BPFConnectTimeLBDisabled) &&
config.BPFHostNetworkedNAT == string(apiv3.BPFHostNetworkedNATDisabled) {