forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xdp_state.go
2268 lines (2070 loc) · 65.8 KB
/
xdp_state.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 (c) 2019 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 (
"fmt"
"net"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/felix/bpf"
"github.com/projectcalico/felix/ipsets"
"github.com/projectcalico/felix/proto"
"github.com/projectcalico/libcalico-go/lib/set"
)
// XDP state manages XDP programs installed on network interfaces and
// the BPF maps those programs use. Each network interface that has an
// XDP program installed has its own corresponding BPF map. The "map"
// part in "BPF map" suggests a key-value store. And indeed keys are
// CIDRs, and values are implementation specific stuff (for now, just
// a reference counter). If a CIDR is in a map then it means that
// traffic coming from the IP addresses that match this CIDR is
// blocked.
//
// To set up the XDP program and the map we need two things: a list of
// network interface names and the list of blocked CIDRs for each
// network interface. The list of blocked CIDRs can be different for
// each network interface.
//
// To get the required data we need to track a chain of information we
// get from the data store. From the datastore we can receive
// information about network interfaces, host endpoints, policies, and
// ipsets. Network interfaces are associated with host endpoints. Host
// endpoints have information about policies that are applied to the
// network interface associated with a particular host endpoint. The
// policy can contain information about IDs of ipsets. Ipsets are
// basically a sets of members. And these members are put into BPF
// maps.
//
// XDP state does not receive the information about all the above
// directly from the datastore, but indirectly through various
// managers using callbacks. The network interface and host endpoint
// stuff comes from the endpoint manager, policies come from the
// policy manager, and ipsets come from the ipsets manager. Callbacks
// are set in the PopulateCallbacks function.
//
// XDP state gathers information during the first phase of the
// internal dataplane event loop, where the internal dataplane routes
// messages from the data store to each manager, which in turn may
// invoke some callbacks. Those callbacks are also invoked at the
// beginning of the second phase of the internal dataplane event loop,
// where the internal dataplane tells each manager to complete its
// deferred work.
//
// XDP state contains an IP state which is a representation of an XDP
// state for a specific IP family. Currently it only contains such a
// thing for IPv4. Among other data the IP state has a field called
// system state which is a view of the information from the data store
// that is relevant to XDP. That is: network interface names, host
// endpoints, policies, and ipset IDs. Note the lack of ipset contents
// - this is to preserve memory. Such a form of a system state
// requires us to perform updates of the XDP state in two steps:
// processing pending diff state together with applying BPF actions,
// and processing member updates.
//
// After the information gathering is done, it is processed to figure
// out the next system state of XDP and generate BPF actions to go to
// the desired state from the current one. This part is done in the
// ProcessPendingDiffState function.
//
// Next step is to apply the actions. This happens in the
// ApplyBPFActions function.
//
// Then we need to process member updates. This consumes the
// information we get from the ipset manager about changes within
// ipsets. This happens in the ProcessMemberUpdates function.
//
// There is a special step for resynchronization - it modifies BPF
// actions based on the actual state of XDP on the system and the
// desired state. See the ResyncIfNeeded function.
type xdpState struct {
ipV4State *xdpIPState
common xdpStateCommon
}
func NewXDPState(allowGenericXDP bool) (*xdpState, error) {
lib, err := bpf.NewBPFLib()
if err != nil {
return nil, err
}
return NewXDPStateWithBPFLibrary(lib, allowGenericXDP), nil
}
func NewXDPStateWithBPFLibrary(library bpf.BPFDataplane, allowGenericXDP bool) *xdpState {
log.Debug("Created new xdpState.")
return &xdpState{
ipV4State: newXDPIPState(4),
common: xdpStateCommon{
programTag: "",
needResync: true,
bpfLib: library,
xdpModes: getXDPModes(allowGenericXDP),
},
}
}
func (x *xdpState) PopulateCallbacks(cbs *callbacks) {
if x.ipV4State != nil {
cbIDs := []*CbID{
cbs.UpdatePolicyV4.Append(x.ipV4State.updatePolicy),
cbs.RemovePolicyV4.Append(x.ipV4State.removePolicy),
cbs.AddMembersIPSetV4.Append(x.ipV4State.addMembersIPSet),
cbs.RemoveMembersIPSetV4.Append(x.ipV4State.removeMembersIPSet),
cbs.ReplaceIPSetV4.Append(x.ipV4State.replaceIPSet),
cbs.RemoveIPSetV4.Append(x.ipV4State.removeIPSet),
cbs.AddInterfaceV4.Append(x.ipV4State.addInterface),
cbs.RemoveInterfaceV4.Append(x.ipV4State.removeInterface),
cbs.UpdateInterfaceV4.Append(x.ipV4State.updateInterface),
cbs.UpdateHostEndpointV4.Append(x.ipV4State.updateHostEndpoint),
cbs.RemoveHostEndpointV4.Append(x.ipV4State.removeHostEndpoint),
}
x.ipV4State.cbIDs = append(x.ipV4State.cbIDs, cbIDs...)
}
}
func (x *xdpState) DepopulateCallbacks(cbs *callbacks) {
if x.ipV4State != nil {
for _, id := range x.ipV4State.cbIDs {
cbs.Drop(id)
}
x.ipV4State.cbIDs = nil
}
}
func (x *xdpState) QueueResync() {
x.common.needResync = true
}
func (x *xdpState) ProcessPendingDiffState(epSourceV4 endpointsSource) {
if x.ipV4State != nil {
x.ipV4State.processPendingDiffState(epSourceV4)
}
}
func (x *xdpState) ResyncIfNeeded(isSourceV4 ipsetsSource) error {
var err error
if !x.common.needResync {
return nil
}
success := false
for i := 0; i < 10; i++ {
if i > 0 {
log.Info("Retrying after an XDP update failure...")
}
log.Info("Resyncing XDP state with dataplane.")
err = x.tryResync(newConvertingIPSetsSource(isSourceV4))
if err == nil {
success = true
break
}
}
if !success {
return fmt.Errorf("failed to resync: %v", err)
}
x.common.needResync = false
return nil
}
func (x *xdpState) ApplyBPFActions(isSource ipsetsSource) error {
if x.ipV4State != nil {
memberCacheV4 := newXDPMemberCache(x.ipV4State.getBpfIPFamily(), x.common.bpfLib)
err := x.ipV4State.bpfActions.apply(memberCacheV4, x.ipV4State.ipsetIDsToMembers, newConvertingIPSetsSource(isSource), x.common.xdpModes)
x.ipV4State.bpfActions = newXDPBPFActions()
if err != nil {
log.WithError(err).Warning("Applying BPF actions failed. Queueing XDP resync.")
x.QueueResync()
return err
}
}
return nil
}
func (x *xdpState) ProcessMemberUpdates() error {
if x.ipV4State != nil {
memberCacheV4 := newXDPMemberCache(x.ipV4State.getBpfIPFamily(), x.common.bpfLib)
err := x.ipV4State.processMemberUpdates(memberCacheV4)
if err != nil {
log.WithError(err).Warning("Processing member updates failed. Queueing XDP resync.")
x.QueueResync()
return err
}
}
return nil
}
func (x *xdpState) DropPendingDiffState() {
if x.ipV4State != nil {
x.ipV4State.pendingDiffState = newXDPPendingDiffState()
}
}
func (x *xdpState) UpdateState() {
if x.ipV4State != nil {
x.ipV4State.currentState, x.ipV4State.newCurrentState = x.ipV4State.newCurrentState, nil
x.ipV4State.cleanupCache()
}
}
func (x *xdpState) WipeXDP() error {
savedIPV4State := x.ipV4State
x.ipV4State = newXDPIPState(4)
x.ipV4State.newCurrentState = newXDPSystemState()
defer func() {
x.ipV4State = savedIPV4State
}()
// Nil source, we are not going to use it anyway,
// because we are about to drop everything, and when
// we only drop stuff, the code does not call
// ipsetsSource functions at all.
isSource := &nilIPSetsSource{}
if err := x.tryResync(isSource); err != nil {
return err
}
if err := x.ApplyBPFActions(isSource); err != nil {
return err
}
x.QueueResync()
return nil
}
func (x *xdpState) tryResync(isSourceV4 ipsetsSource) error {
if x.common.programTag == "" {
tag, err := x.common.bpfLib.GetXDPObjTagAuto()
if err != nil {
return err
}
x.common.programTag = tag
}
if x.ipV4State != nil {
if err := x.ipV4State.tryResync(&x.common, isSourceV4); err != nil {
return err
}
}
return nil
}
// xdpIPState holds the XDP state specific to an IP family.
type xdpIPState struct {
ipFamily int
ipsetIDsToMembers *ipsetIDsToMembers
currentState *xdpSystemState
pendingDiffState *xdpPendingDiffState
newCurrentState *xdpSystemState
bpfActions *xdpBPFActions
cbIDs []*CbID
logCxt *log.Entry
}
type ipsetIDsToMembers struct {
cache map[string]set.Set // ipSetID -> members
pendingReplaces map[string]set.Set // ipSetID -> members
pendingAdds map[string]set.Set // ipSetID -> members
pendingDeletions map[string]set.Set // ipSetID -> members
}
func newIPSetIDsToMembers() *ipsetIDsToMembers {
i := &ipsetIDsToMembers{}
i.Clear()
return i
}
func (i *ipsetIDsToMembers) Clear() {
i.cache = make(map[string]set.Set)
i.pendingReplaces = make(map[string]set.Set)
i.pendingAdds = make(map[string]set.Set)
i.pendingDeletions = make(map[string]set.Set)
}
func (i *ipsetIDsToMembers) GetCached(setID string) (s set.Set, ok bool) {
s, ok = i.cache[setID]
return
}
func safeAdd(m map[string]set.Set, setID, member string) {
if m[setID] == nil {
m[setID] = set.New()
}
m[setID].Add(member)
}
func (i *ipsetIDsToMembers) AddMembers(setID string, members set.Set) {
if _, ok := i.cache[setID]; !ok {
// not tracked by XDP
return
}
if rs, ok := i.pendingReplaces[setID]; ok {
members.Iter(func(item interface{}) error {
member := item.(string)
rs.Add(member)
return nil
})
} else {
members.Iter(func(item interface{}) error {
member := item.(string)
safeAdd(i.pendingAdds, setID, member)
return nil
})
}
}
func (i *ipsetIDsToMembers) RemoveMembers(setID string, members set.Set) {
if _, ok := i.cache[setID]; !ok {
// not tracked by XDP
return
}
if rs, ok := i.pendingReplaces[setID]; ok {
members.Iter(func(item interface{}) error {
member := item.(string)
rs.Discard(member)
return nil
})
} else {
members.Iter(func(item interface{}) error {
member := item.(string)
safeAdd(i.pendingDeletions, setID, member)
return nil
})
}
}
func (i *ipsetIDsToMembers) Delete(setID string) {
if _, ok := i.cache[setID]; !ok {
// not tracked by XDP
return
}
i.pendingReplaces[setID] = set.New()
delete(i.pendingAdds, setID)
delete(i.pendingDeletions, setID)
}
func (i *ipsetIDsToMembers) Replace(setID string, members set.Set) {
if _, ok := i.cache[setID]; !ok {
// not tracked by XDP
return
}
i.pendingReplaces[setID] = members
delete(i.pendingAdds, setID)
delete(i.pendingDeletions, setID)
}
func (i *ipsetIDsToMembers) UpdateCache() {
cachedSetIDs := set.New()
for setID := range i.cache {
cachedSetIDs.Add(setID)
}
cachedSetIDs.Iter(func(item interface{}) error {
setID := item.(string)
if m, ok := i.pendingReplaces[setID]; ok {
i.cache[setID] = m
} else {
if m, ok := i.pendingDeletions[setID]; ok {
m.Iter(func(item interface{}) error {
member := item.(string)
i.cache[setID].Discard(member)
return nil
})
}
if m, ok := i.pendingAdds[setID]; ok {
m.Iter(func(item interface{}) error {
member := item.(string)
i.cache[setID].Add(member)
return nil
})
}
}
return nil
})
// flush everything
i.pendingReplaces = make(map[string]set.Set)
i.pendingAdds = make(map[string]set.Set)
i.pendingDeletions = make(map[string]set.Set)
}
func (i *ipsetIDsToMembers) SetCache(setID string, members set.Set) {
i.cache[setID] = members
}
func newXDPIPState(ipFamily int) *xdpIPState {
return &xdpIPState{
ipFamily: ipFamily,
ipsetIDsToMembers: newIPSetIDsToMembers(),
currentState: newXDPSystemState(),
pendingDiffState: newXDPPendingDiffState(),
bpfActions: newXDPBPFActions(),
cbIDs: nil,
logCxt: log.WithField("family", ipFamily),
}
}
func (s *xdpIPState) getBpfIPFamily() bpf.IPFamily {
if s.ipFamily == 4 {
return bpf.IPFamilyV4
}
s.logCxt.WithField("ipFamily", s.ipFamily).Panic("Invalid ip family.")
return bpf.IPFamilyUnknown
}
func (s *xdpIPState) newXDPResyncState(common *xdpStateCommon, isSource ipsetsSource) (*xdpResyncState, error) {
xdpIfaces, err := common.bpfLib.GetXDPIfaces()
if err != nil {
return nil, err
}
s.logCxt.WithField("ifaces", xdpIfaces).Debug("Interfaces with XDP program installed.")
ifacesWithProgs := make(map[string]progInfo, len(xdpIfaces))
for _, iface := range xdpIfaces {
tag, tagErr := common.bpfLib.GetXDPTag(iface)
mode, modeErr := common.bpfLib.GetXDPMode(iface)
// error can happen when the program was not pinned in
// the bpf filesystem, so we say it's bogus anyway
bogus := tagErr != nil || tag != common.programTag || modeErr != nil || !isValidMode(mode, common)
ifacesWithProgs[iface] = progInfo{
bogus: bogus,
}
}
ifacesWithPinnedMaps, err := common.bpfLib.ListCIDRMaps(s.getBpfIPFamily())
if err != nil {
return nil, err
}
s.logCxt.WithField("ifaces", ifacesWithPinnedMaps).Debug("Interfaces with BPF blacklist maps.")
ifacesWithMaps := make(map[string]mapInfo, len(ifacesWithPinnedMaps))
for _, iface := range ifacesWithPinnedMaps {
mapOk, err := common.bpfLib.IsValidMap(iface, s.getBpfIPFamily())
if err != nil {
return nil, err
}
mapBogus := !mapOk
mapMismatch, err := func() (bool, error) {
if _, ok := ifacesWithProgs[iface]; !ok {
return false, nil
}
mapID, err := common.bpfLib.GetCIDRMapID(iface, s.getBpfIPFamily())
if err != nil {
return false, err
}
mapIDs, err := common.bpfLib.GetMapsFromXDP(iface)
if err != nil {
return false, err
}
matched := false
for _, id := range mapIDs {
if mapID == id {
matched = true
break
}
}
return !matched, nil
}()
if err != nil {
return nil, err
}
var mapContents map[bpf.CIDRMapKey]uint32
if !mapBogus {
dump, err := common.bpfLib.DumpCIDRMap(iface, s.getBpfIPFamily())
if err != nil {
return nil, err
}
mapContents = dump
}
ifacesWithMaps[iface] = mapInfo{
bogus: mapBogus,
mismatched: mapMismatch,
contents: mapContents,
}
s.logCxt.WithFields(log.Fields{
"iface": iface,
"info": ifacesWithMaps[iface],
}).Debug("Information about BPF blacklist map.")
}
visited := set.New()
ipsetMembers := make(map[string]set.Set)
for _, data := range s.newCurrentState.IfaceNameToData {
for _, setIDs := range data.PoliciesToSetIDs {
var opErr error
setIDs.Iter(func(item interface{}) error {
setID := item.(string)
if visited.Contains(setID) {
return nil
}
members, err := s.getIPSetMembers(setID, isSource)
if err != nil {
opErr = err
return set.StopIteration
}
s.logCxt.WithFields(log.Fields{
"setID": setID,
"memberCount": members.Len(),
}).Debug("Information about ipset members.")
ipsetMembers[setID] = members
visited.Add(setID)
return nil
})
if opErr != nil {
return nil, opErr
}
}
}
return &xdpResyncState{
ifacesWithProgs: ifacesWithProgs,
ifacesWithMaps: ifacesWithMaps,
ipsetMembers: ipsetMembers,
}, nil
}
func isValidMode(mode bpf.XDPMode, common *xdpStateCommon) bool {
for _, xdpMode := range common.xdpModes {
if xdpMode == mode {
return true
}
}
return false
}
func (s *xdpIPState) getIPSetMembers(setID string, isSource ipsetsSource) (set.Set, error) {
return getIPSetMembers(s.ipsetIDsToMembers, setID, isSource)
}
// tryResync performs the resynchronization of the XDP state. It
// modifies the BPF actions based on the state of XDP on the system
// and on the desired state. It also repopulates the members cache.
//
// This function ensures that after applying the BPF actions, the XDP
// state will be consistent. Which means making sure that XDP programs
// are installed in desired interfaces, that they are referencing
// correct maps, and that maps contain the desired ipsets.
func (s *xdpIPState) tryResync(common *xdpStateCommon, isSource ipsetsSource) error {
resyncStart := time.Now()
defer func() {
s.logCxt.WithField("resyncDuration", time.Since(resyncStart)).Info("Finished XDP resync.")
}()
s.ipsetIDsToMembers.Clear()
resyncState, err := s.newXDPResyncState(common, isSource)
if err != nil {
return err
}
s.fixupXDPProgramAndMapConsistency(resyncState)
s.fixupBlacklistContents(resyncState)
return nil
}
// fixupXDPProgramAndMapConsistency ensures that XDP programs are
// installed on the proper network interfaces, are valid, and
// reference the correct maps.
//
// There are several concepts related to programs and maps:
//
// A program can be installed or not. If the program is installed, it
// can be valid or not. A valid XDP program is a program that has an
// expected tag. Tag is basically a checksum of the program's
// bytecode. We figure out the desired program tag on the first
// resync. The tag is computed by the kernel, so it is not something
// we can know in advance.
//
// A map can exist or not. If it exists then it can be valid or
// not. If it is valid then it can be mismatched or not. A valid map
// is a map of an expected type with an expected key and value size
// (for the kernel, keys and values are purely array of bytes, and the
// length of those arrays needs to be defined at map creation time
// along with the map type). A mismatched map means that it is not
// used by the program. Which in reality means that the program is
// invalid and needs to be replaced.
//
// Since an XDP program references a BPF map and not the other way
// around, it means that if a map is invalid and needs to be replaced,
// then the program that references the map needs to be replaced too.
// In case of mismatched maps, only the program gets replaced.
func (s *xdpIPState) fixupXDPProgramAndMapConsistency(resyncState *xdpResyncState) {
ifaces := s.getIfaces(resyncState, giNS|giWX|giIX|giUX|giWM|giCM|giRM)
ifaces.Iter(func(item interface{}) error {
iface := item.(string)
shouldHaveXDP := func() bool {
if data, ok := s.newCurrentState.IfaceNameToData[iface]; ok {
return data.NeedsXDP()
}
return false
}()
hasXDP, hasBogusXDP := func() (bool, bool) {
if progInfo, ok := resyncState.ifacesWithProgs[iface]; ok {
return true, progInfo.bogus
}
return false, false
}()
mapExists, mapBogus, mapMismatch := func() (bool, bool, bool) {
if mapInfo, ok := resyncState.ifacesWithMaps[iface]; ok {
return true, mapInfo.bogus, mapInfo.mismatched
}
return false, false, false
}()
s.logCxt.WithFields(log.Fields{
"iface": iface,
"hasProgram": hasXDP,
"isProgramBogus": hasBogusXDP,
"wantsProgram": shouldHaveXDP,
"mapExists": mapExists,
"mapBogus": mapBogus,
"mapMismatched": mapMismatch,
}).Debug("Resync - fixing XDP program and map consistency.")
func() {
if !hasXDP && !shouldHaveXDP {
s.bpfActions.InstallXDP.Discard(iface)
s.bpfActions.UninstallXDP.Discard(iface)
if !mapExists {
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else {
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Add(iface)
}
return
}
if !hasXDP && shouldHaveXDP {
s.bpfActions.InstallXDP.Add(iface)
s.bpfActions.UninstallXDP.Discard(iface)
if !mapExists {
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else if mapBogus {
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Add(iface)
} else {
// mismatch is not possible, so it's a
// good map
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
}
return
}
if hasXDP && !shouldHaveXDP {
s.bpfActions.InstallXDP.Discard(iface)
s.bpfActions.UninstallXDP.Add(iface)
if !mapExists {
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else {
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Add(iface)
}
return
}
if hasXDP && !hasBogusXDP && shouldHaveXDP {
if !mapExists {
// Good program, but no map? Means the
// program needs to be replaced, so it
// reads from the correct maps. The
// map needs to be created.
s.bpfActions.InstallXDP.Add(iface)
s.bpfActions.UninstallXDP.Add(iface)
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else if mapBogus {
// Good program, but bogus map? Means
// the program needs to be replaced,
// so it reads from the correct
// maps. The map needs to be replaced.
s.bpfActions.InstallXDP.Add(iface)
s.bpfActions.UninstallXDP.Add(iface)
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Add(iface)
} else if mapMismatch {
// Good program, but mismatched map?
// Means the program needs to be
// replaced, so it reads from the
// correct maps. The map itself is
// fine.
s.bpfActions.InstallXDP.Add(iface)
s.bpfActions.UninstallXDP.Add(iface)
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else {
// Good program reading from correct
// maps. Nothing to do.
s.bpfActions.InstallXDP.Discard(iface)
s.bpfActions.UninstallXDP.Discard(iface)
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
}
return
}
if hasXDP && hasBogusXDP && shouldHaveXDP {
s.bpfActions.InstallXDP.Add(iface)
s.bpfActions.UninstallXDP.Add(iface)
if !mapExists {
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Discard(iface)
} else if mapBogus {
s.bpfActions.CreateMap.Add(iface)
s.bpfActions.RemoveMap.Add(iface)
} else {
// Mismatched or not, the map itself
// is ok, so nothing to do here. The
// replaced program will make use of
// it.
s.bpfActions.CreateMap.Discard(iface)
s.bpfActions.RemoveMap.Discard(iface)
}
return
}
}()
s.logCxt.WithFields(log.Fields{
"iface": iface,
"installXDP": s.bpfActions.InstallXDP.Contains(iface),
"uninstallXDP": s.bpfActions.UninstallXDP.Contains(iface),
"createMap": s.bpfActions.CreateMap.Contains(iface),
"removeMap": s.bpfActions.RemoveMap.Contains(iface),
}).Debug("Resync - finished fixing XDP program and map consistency.")
return nil
})
}
// fixupBlacklistContents ensures that contents of the BPF maps are in
// sync with ipsets those maps should contain.
//
// There are two cases - the BPF map is going to be created/replaced,
// and the BPF map already exists. When BPF map is about to be
// created/replaced, we just need to set up BPF actions that are about
// inserting whole ipsets into the BPF map. But if the map already
// exists, then we need to dump the contents of the map, compute the
// desired contents of the map, figure out the missing or superfluous
// members and update the BPF actions that are about modifying the BPF
// maps on a member level.
func (s *xdpIPState) fixupBlacklistContents(resyncState *xdpResyncState) {
ifaces := s.getIfaces(resyncState, giNS)
ifaces.Iter(func(item interface{}) error {
iface := item.(string)
createMap := s.bpfActions.CreateMap.Contains(iface)
s.logCxt.WithFields(log.Fields{
"iface": iface,
"mapCreate": createMap,
}).Debug("Resync - fixing map contents.")
if createMap {
s.fixupBlacklistContentsFreshMap(iface)
} else {
if _, ok := resyncState.ifacesWithMaps[iface]; !ok {
s.logCxt.WithField("iface", iface).Panic("Resync - iface missing from ifaces with maps in resync state!")
}
s.fixupBlacklistContentsExistingMap(resyncState, iface)
}
s.logCxt.WithFields(log.Fields{
"iface": iface,
"addToMap": s.bpfActions.AddToMap[iface],
"removeFromMap": s.bpfActions.RemoveFromMap[iface],
"membersToAdd": s.bpfActions.MembersToAdd[iface],
"membersToDrop": s.bpfActions.MembersToDrop[iface],
}).Debug("Resync - finished fixing map contents.")
return nil
})
for _, m := range []map[string]map[string]uint32{s.bpfActions.AddToMap, s.bpfActions.RemoveFromMap} {
for iface := range m {
if !ifaces.Contains(iface) {
delete(m, iface)
}
}
}
}
func (s *xdpIPState) fixupBlacklistContentsFreshMap(iface string) {
setIDToRefCount := s.getSetIDToRefCountFromNewState(iface)
s.bpfActions.AddToMap[iface] = setIDToRefCount
delete(s.bpfActions.RemoveFromMap, iface)
}
func (s *xdpIPState) fixupBlacklistContentsExistingMap(resyncState *xdpResyncState, iface string) {
membersInBpfMap := resyncState.ifacesWithMaps[iface].contents
setIDsInNS := s.getSetIDToRefCountFromNewState(iface)
membersInNS := make(map[string]uint32)
for setID, refCount := range setIDsInNS {
if _, ok := resyncState.ipsetMembers[setID]; !ok {
s.logCxt.WithFields(log.Fields{
"iface": iface,
"setID": setID,
"wantedRefCount": refCount,
}).Panic("Resync - set id missing from ip set members in resync state!")
}
resyncState.ipsetMembers[setID].Iter(func(item interface{}) error {
member := item.(string)
membersInNS[member] += refCount
return nil
})
}
setIDsInNS = nil
for mapKey, actualRefCount := range membersInBpfMap {
member := mapKey.ToIPNet().String()
expectedRefCount := membersInNS[member]
s.logCxt.WithFields(log.Fields{
"iface": iface,
"member": member,
"actualRefCount": actualRefCount,
"expectedRefCount": expectedRefCount,
}).Debug("Resync - syncing member.")
if expectedRefCount > actualRefCount {
s.updateMembersToChange(s.bpfActions.MembersToAdd, iface, member, expectedRefCount-actualRefCount)
} else if expectedRefCount < actualRefCount {
s.updateMembersToChange(s.bpfActions.MembersToDrop, iface, member, actualRefCount-expectedRefCount)
}
delete(membersInNS, member)
}
for member, expectedRefCount := range membersInNS {
s.logCxt.WithFields(log.Fields{
"iface": iface,
"member": member,
"expectedRefCount": expectedRefCount,
}).Debug("Resync - missing member.")
s.updateMembersToChange(s.bpfActions.MembersToAdd, iface, member, expectedRefCount)
}
delete(s.bpfActions.AddToMap, iface)
delete(s.bpfActions.RemoveFromMap, iface)
}
func (s *xdpIPState) updateMembersToChange(membersToChangeMap map[string]map[string]uint32, iface, member string, refCount uint32) {
memberToRefCountMap := func() map[string]uint32 {
m := membersToChangeMap[iface]
if m == nil {
m = make(map[string]uint32)
membersToChangeMap[iface] = m
}
return m
}()
memberToRefCountMap[member] += refCount
}
func (s *xdpIPState) getSetIDToRefCountFromNewState(iface string) map[string]uint32 {
setIDToRefCount := make(map[string]uint32)
if data, ok := s.newCurrentState.IfaceNameToData[iface]; ok {
for _, setIDs := range data.PoliciesToSetIDs {
setIDs.Iter(func(item interface{}) error {
setID := item.(string)
setIDToRefCount[setID] += 1
return nil
})
}
}
return setIDToRefCount
}
type IfaceFlags uint8
const (
// from new state
giNS = 1 << iota
// from installXDP
giIX
// from uninstall XDP
giUX
// from ifacesWithProgs
giWX
// from createMaps
giCM
// from removeMaps
giRM
// from ifacesWithMaps
giWM
)
func (s *xdpIPState) getIfaces(resyncState *xdpResyncState, flags IfaceFlags) set.Set {
ifaces := set.New()
addFromSet := func(item interface{}) error {
ifaces.Add(item)
return nil
}
if flags&giNS == giNS {
for iface, data := range s.newCurrentState.IfaceNameToData {
if data.NeedsXDP() {
ifaces.Add(iface)
}
}
}
if flags&giIX == giIX {
s.bpfActions.InstallXDP.Iter(addFromSet)
}
if flags&giUX == giUX {
s.bpfActions.UninstallXDP.Iter(addFromSet)
}
if flags&giWX == giWX {
for iface := range resyncState.ifacesWithProgs {
ifaces.Add(iface)
}
}
if flags&giCM == giCM {
s.bpfActions.CreateMap.Iter(addFromSet)
}
if flags&giRM == giRM {
s.bpfActions.RemoveMap.Iter(addFromSet)
}
if flags&giWM == giWM {
for iface := range resyncState.ifacesWithMaps {
ifaces.Add(iface)
}
}
return ifaces
}
// PROCESS MEMBER UPDATES
func (s *xdpIPState) processMemberUpdates(memberCache *xdpMemberCache) error {
s.logCxt.Debug("Processing member updates.")
// process member changes
changes := s.getMemberChanges()
for setID, change := range changes {
ifacesToRefCounts := s.getAffectedIfaces(setID)
s.logCxt.WithFields(log.Fields{
"setID": setID,
"affectedIfaces": ifacesToRefCounts,
}).Debug("Processing member changes.")
for iface, refCount := range ifacesToRefCounts {
s.logCxt.WithFields(log.Fields{
"setID": setID,
"iface": iface,
"refCount": refCount,
"toAdd": change.toAdd,
"toDrop": change.toDrop,
}).Debug("Processing BPF map changes.")
miDelete := &memberIterSet{
members: change.toDrop,
refCount: refCount,
}
if err := processMemberDeletions(memberCache, iface, miDelete); err != nil {
return err
}
miAdd := &memberIterSet{
members: change.toAdd,
refCount: refCount,
}
if err := processMemberAdds(memberCache, iface, miAdd); err != nil {
return err
}
}
}
s.logCxt.Debug("Updating ipsetIDsToMembers cache.")
s.ipsetIDsToMembers.UpdateCache()
return nil
}
// processPendingDiffState processes the information the state has
// gathered from callbacks and generates the new desired state and the
// actions that, when executed, will get the current state into the
// new desired state.
//
// The aim is to get a list of IP addresses/CIDRs to be blocked on
// network interfaces. We can get addresses/CIDRs from ipsets. We can
// get ipsets from policies. We can get policies from host endpoints.
// Host endpoints are associated with network interfaces. All this
// creates a chain from interface to addresses/CIDRs: network
// interface -> host endpoint -> policies -> ipsets ->
// addresses/CIDRs.
//
// In this function we process the information in the same order as it
// is in the chain, so first we process the changes wrt. network
// interfaces, then changes in host endpoints, then changes in
// policies. Note that changes in ipsets themselves are processed
// elsewhere (see the processMemberUpdates function), because members
// of ipsets are not stored in the current state/new desired state.
// Current state has a granularity up to the ipset ID level.
//
// The function is careful to process each interface at most once - so
// if the network interface's host endpoint has changed and some
// policy associated with the host endpoint has changed, then the
// interface is only processed in the part of the code that handles
// updates of the host endpoint and it is skipped in the code that
// handles policy updates.