forked from projectcalico/felix
/
bpf.go
2297 lines (1908 loc) · 52.2 KB
/
bpf.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 bpf provides primitives to manage Calico-specific XDP programs
// attached to network interfaces, along with the blacklist LPM map and the
// failsafe map.
//
// It does not call the bpf() syscall itself but executes external programs
// like bpftool and ip.
package bpf
import (
"bufio"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
version "github.com/hashicorp/go-version"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"github.com/projectcalico/felix/labelindex"
"github.com/projectcalico/felix/versionparse"
)
type XDPMode int
const (
XDPDriver XDPMode = iota
XDPOffload
XDPGeneric
)
type FindObjectMode uint32
const (
FindInBPFFSOnly FindObjectMode = 1 << iota
FindByID
)
const (
// XDP
cidrMapVersion = "v1"
failsafeMapVersion = "v1"
xdpProgVersion = "v1"
failsafeMapName = "calico_failsafe_ports_" + failsafeMapVersion
failsafeSymbolMapName = "calico_failsafe_ports" // no need to version the symbol name
// sockmap
sockopsProgVersion = "v1"
sockopsProgName = "calico_sockops_" + sockopsProgVersion
skMsgProgVersion = "v1"
skMsgProgName = "calico_sk_msg_" + skMsgProgVersion
sockMapVersion = "v1"
sockMapName = "calico_sock_map_" + sockMapVersion
sockmapEndpointsMapVersion = "v1"
sockmapEndpointsMapName = "calico_sk_endpoints_" + sockmapEndpointsMapVersion
defaultBPFfsPath = "/sys/fs/bpf"
)
var (
// this holds the compiled XDP binary as an ELF file
xdpAsset []byte
// this holds the compiled sockops binary as an ELF file
sockopsAsset []byte
// this holds the compiled sk_msg binary as an ELF file
skmsgAsset []byte
bpfCalicoSubdir = "calico"
ifaceRegexp = regexp.MustCompile(`(?m)^[0-9]+:\s+(?P<name>.+):`)
// v4Dot16Dot0 is the first kernel version that has all the
// required features we use for XDP filtering
v4Dot16Dot0 = versionparse.MustParseVersion("4.16.0")
// v4Dot20Dot0 is the first kernel version that has all the
// required features we use for sidecar acceleration
v4Dot20Dot0 = versionparse.MustParseVersion("4.20.0")
)
// func init() {
// boxXDP := packr.New("xdp", "./xdp/generated")
// xdpBytes, err := boxXDP.Find("xdp.o")
// if err != nil {
// panic(fmt.Sprintf("cannot find xdp.o: %v\n", err))
// }
// boxSockmap := packr.New("sockmap", "./sockmap/generated")
// sockopsBytes, err := boxSockmap.Find("sockops.o")
// if err != nil {
// panic(fmt.Sprintf("cannot find sockops.o: %v\n", err))
// }
// skmsgBytes, err := boxSockmap.Find("redir.o")
// if err != nil {
// panic(fmt.Sprintf("cannot find redir.o: %v\n", err))
// }
// xdpAsset = xdpBytes
// sockopsAsset = sockopsBytes
// skmsgAsset = skmsgBytes
// }
func (m XDPMode) String() string {
switch m {
case XDPDriver:
return "xdpdrv"
case XDPOffload:
return "xdpoffload"
case XDPGeneric:
return "xdpgeneric"
default:
return "unknown"
}
}
// XXX maybe use ipsets.IPFamily
type IPFamily int
const (
IPFamilyUnknown IPFamily = iota
IPFamilyV4
IPFamilyV6
)
func (m IPFamily) String() string {
switch m {
case IPFamilyV4:
return "ipv4"
case IPFamilyV6:
return "ipv6"
default:
return "unknown"
}
}
func (m IPFamily) Size() int {
switch m {
case IPFamilyV4:
return 4
case IPFamilyV6:
return 16
}
return -1
}
func printCommand(name string, arg ...string) {
log.Debugf("running: %s %s", name, strings.Join(arg, " "))
}
type BPFLib struct {
bpfDir string
calicoDir string
sockmapDir string
cgroupV2Dir string
xdpDir string
}
func NewBPFLib() (*BPFLib, error) {
_, err := exec.LookPath("bpftool")
if err != nil {
return nil, errors.New("bpftool not found in $PATH")
}
bpfDir, err := maybeMountBPFfs()
if err != nil {
return nil, err
}
cgroupV2Dir, err := maybeMountCgroupV2()
if err != nil {
return nil, err
}
calicoDir := filepath.Join(bpfDir, bpfCalicoSubdir)
xdpDir := filepath.Join(calicoDir, "xdp")
sockmapDir := filepath.Join(calicoDir, "sockmap")
return &BPFLib{
bpfDir: bpfDir,
calicoDir: calicoDir,
sockmapDir: sockmapDir,
cgroupV2Dir: cgroupV2Dir,
xdpDir: xdpDir,
}, nil
}
func maybeMountBPFfs() (string, error) {
var err error
bpffsPath := defaultBPFfsPath
mnt, err := isMount(defaultBPFfsPath)
if err != nil {
return "", err
}
fsBPF, err := isBPF(defaultBPFfsPath)
if err != nil {
return "", err
}
if !mnt {
err = mountBPFfs(defaultBPFfsPath)
} else if !fsBPF {
var runfsBPF bool
bpffsPath = "/var/run/calico/bpffs"
if err := os.MkdirAll(bpffsPath, 0700); err != nil {
return "", err
}
runfsBPF, err = isBPF(bpffsPath)
if err != nil {
return "", err
}
if !runfsBPF {
err = mountBPFfs(bpffsPath)
}
}
return bpffsPath, err
}
func maybeMountCgroupV2() (string, error) {
var err error
cgroupV2Path := "/run/calico/cgroup"
if err := os.MkdirAll(cgroupV2Path, 0700); err != nil {
return "", err
}
mnt, err := isMount(cgroupV2Path)
if err != nil {
return "", fmt.Errorf("error checking if %s is a mount: %v", cgroupV2Path, err)
}
fsCgroup, err := isCgroupV2(cgroupV2Path)
if err != nil {
return "", fmt.Errorf("error checking if %s is CgroupV2: %v", cgroupV2Path, err)
}
if !mnt {
err = mountCgroupV2(cgroupV2Path)
} else if !fsCgroup {
err = fmt.Errorf("something that's not cgroup v2 is already mounted in %s", cgroupV2Path)
}
return cgroupV2Path, err
}
func mountCgroupV2(path string) error {
return syscall.Mount(path, path, "cgroup2", 0, "")
}
func isMount(path string) (bool, error) {
procPath := "/proc/self/mountinfo"
mi, err := os.Open(procPath)
if err != nil {
return false, err
}
defer mi.Close()
sc := bufio.NewScanner(mi)
for sc.Scan() {
line := sc.Text()
columns := strings.Split(line, " ")
if len(columns) < 7 {
return false, fmt.Errorf("not enough fields from line %q: %+v", line, columns)
}
mountPoint := columns[4]
if filepath.Clean(mountPoint) == filepath.Clean(path) {
return true, nil
}
}
return false, nil
}
func isBPF(path string) (bool, error) {
bpffsMagicNumber := uint32(0xCAFE4A11)
var fsdata unix.Statfs_t
if err := unix.Statfs(path, &fsdata); err != nil {
return false, fmt.Errorf("%s is not mounted", path)
}
return uint32(fsdata.Type) == bpffsMagicNumber, nil
}
func isCgroupV2(path string) (bool, error) {
cgroup2MagicNumber := uint32(0x63677270)
var fsdata unix.Statfs_t
if err := unix.Statfs(path, &fsdata); err != nil {
return false, fmt.Errorf("%s is not mounted", path)
}
return uint32(fsdata.Type) == cgroup2MagicNumber, nil
}
func mountBPFfs(path string) error {
return syscall.Mount(path, path, "bpf", 0, "")
}
type BPFDataplane interface {
DumpCIDRMap(ifName string, family IPFamily) (map[CIDRMapKey]uint32, error)
DumpFailsafeMap() ([]ProtoPort, error)
GetCIDRMapID(ifName string, family IPFamily) (int, error)
GetFailsafeMapID() (int, error)
GetMapsFromXDP(ifName string) ([]int, error)
GetXDPID(ifName string) (int, error)
GetXDPMode(ifName string) (XDPMode, error)
GetXDPIfaces() ([]string, error)
GetXDPObjTag(objPath string) (string, error)
GetXDPObjTagAuto() (string, error)
GetXDPObjTagWithBytes(objBytes []byte) (string, error)
GetXDPTag(ifName string) (string, error)
IsValidMap(ifName string, family IPFamily) (bool, error)
ListCIDRMaps(family IPFamily) ([]string, error)
LoadXDP(objPath, ifName string, mode XDPMode) error
LoadXDPAuto(ifName string, mode XDPMode) error
LoadXDPWithBytes(objBytes []byte, ifName string, mode XDPMode) error
LookupCIDRMap(ifName string, family IPFamily, ip net.IP, mask int) (uint32, error)
LookupFailsafeMap(proto uint8, port uint16) (bool, error)
NewCIDRMap(ifName string, family IPFamily) (string, error)
NewFailsafeMap() (string, error)
RemoveCIDRMap(ifName string, family IPFamily) error
RemoveFailsafeMap() error
RemoveItemCIDRMap(ifName string, family IPFamily, ip net.IP, mask int) error
RemoveItemFailsafeMap(proto uint8, port uint16) error
RemoveXDP(ifName string, mode XDPMode) error
UpdateCIDRMap(ifName string, family IPFamily, ip net.IP, mask int, refCount uint32) error
UpdateFailsafeMap(proto uint8, port uint16) error
loadXDPRaw(objPath, ifName string, mode XDPMode, mapArgs []string) error
GetBPFCalicoDir() string
AttachToSockmap() error
DetachFromSockmap(mode FindObjectMode) error
RemoveSockmap(mode FindObjectMode) error
loadBPF(objPath, progPath, progType string, mapArgs []string) error
LoadSockops(objPath string) error
LoadSockopsWithBytes(objBytes []byte) error
LoadSockopsAuto() error
RemoveSockops() error
LoadSkMsg(objPath string) error
LoadSkMsgWithBytes(objBytes []byte) error
LoadSkMsgAuto() error
RemoveSkMsg() error
AttachToCgroup() error
DetachFromCgroup(mode FindObjectMode) error
NewSockmapEndpointsMap() (string, error)
NewSockmap() (string, error)
UpdateSockmapEndpoints(ip net.IP, mask int) error
DumpSockmapEndpointsMap(family IPFamily) ([]CIDRMapKey, error)
LookupSockmapEndpointsMap(ip net.IP, mask int) (bool, error)
RemoveItemSockmapEndpointsMap(ip net.IP, mask int) error
RemoveSockmapEndpointsMap() error
}
func getCIDRMapName(ifName string, family IPFamily) string {
return fmt.Sprintf("%s_%s_%s_blacklist", ifName, family, cidrMapVersion)
}
func getProgName(ifName string) string {
return fmt.Sprintf("prefilter_%s_%s", xdpProgVersion, ifName)
}
func newMap(name, path, kind string, entries, keySize, valueSize, flags int) (string, error) {
// FIXME: for some reason this function was called several times for a
// particular map, just assume it's created if the pinned file is there for
// now
if _, err := os.Stat(path); err == nil {
return path, nil
}
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0700); err != nil {
return "", err
}
prog := "bpftool"
args := []string{
"map",
"create",
path,
"type",
kind,
"key",
fmt.Sprintf("%d", keySize),
"value",
fmt.Sprintf("%d", valueSize),
"entries",
fmt.Sprintf("%d", entries),
"name",
name,
"flags",
fmt.Sprintf("%d", flags),
}
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return "", fmt.Errorf("failed to create map (%s): %s\n%s", name, err, output)
}
return path, nil
}
func (b *BPFLib) NewFailsafeMap() (string, error) {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
keySize := 4
valueSize := 1
return newMap(mapName,
mapPath,
"hash",
65535,
keySize,
valueSize,
1, //BPF_F_NO_PREALLOC
)
}
func (b *BPFLib) GetBPFCalicoDir() string {
return b.calicoDir
}
func (b *BPFLib) NewCIDRMap(ifName string, family IPFamily) (string, error) {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
if family == IPFamilyV6 {
return "", errors.New("IPv6 not supported")
}
keySize := 8
valueSize := 4
return newMap(mapName,
mapPath,
"lpm_trie",
10240,
keySize,
valueSize,
1, //BPF_F_NO_PREALLOC
)
}
func (b *BPFLib) ListCIDRMaps(family IPFamily) ([]string, error) {
var ifNames []string
maps, err := ioutil.ReadDir(b.xdpDir)
if err != nil {
return nil, err
}
suffix := fmt.Sprintf("_%s_%s_blacklist", family, cidrMapVersion)
for _, m := range maps {
name := m.Name()
if strings.HasSuffix(name, suffix) {
ifName := strings.TrimSuffix(name, suffix)
ifNames = append(ifNames, ifName)
}
}
return ifNames, nil
}
func (b *BPFLib) RemoveFailsafeMap() error {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
return os.Remove(mapPath)
}
func (b *BPFLib) RemoveCIDRMap(ifName string, family IPFamily) error {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
return os.Remove(mapPath)
}
type mapInfo struct {
Id int `json:"id"`
Type string `json:"type"`
KeySize int `json:"bytes_key"`
ValueSize int `json:"bytes_value"`
Err string `json:"error"`
}
type getnextEntry struct {
Key []string `json:"key"`
NextKey []string `json:"next_key"`
Err string `json:"error"`
}
type mapEntry struct {
Key []string `json:"key"`
Value []string `json:"value"`
Err string `json:"error"`
}
type progInfo struct {
Id int `json:"id"`
Type string `json:"type"`
Tag string `json:"tag"`
MapIds []int `json:"map_ids"`
Err string `json:"error"`
}
type ifaceXdpProg struct {
Id int `json:"id"`
Tag string `json:"tag"`
}
type ifaceXdp struct {
Mode int `json:"mode"`
Prog ifaceXdpProg `json:"prog"`
}
type ifaceInfo []struct {
IfIndex int `json:"ifindex"`
IfName string `json:"ifname"`
Link string `json:"link"` // other side of the veth pair
LinkType string `json:"link_type"`
Xdp ifaceXdp `json:"xdp"`
}
type cgroupProgEntry struct {
ID int `json:"id"`
AttachType string `json:"attach_type"`
AttachFlags string `json:"attach_flags"`
Name string `json:"name"`
Err string `json:"error"`
}
type ProtoPort struct {
Proto labelindex.IPSetPortProtocol
Port uint16
}
func getMapStructGeneral(mapDesc []string) (*mapInfo, error) {
prog := "bpftool"
args := []string{
"--json",
"--pretty",
"map",
"show"}
args = append(args, mapDesc...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to show map (%v): %s\n%s", mapDesc, err, output)
}
m := mapInfo{}
err = json.Unmarshal(output, &m)
if err != nil {
return nil, fmt.Errorf("cannot parse json output: %v\n%s", err, output)
}
if m.Err != "" {
return nil, fmt.Errorf("%s", m.Err)
}
return &m, nil
}
func getMapStruct(mapPath string) (*mapInfo, error) {
return getMapStructGeneral([]string{"pinned", mapPath})
}
func (b *BPFLib) GetFailsafeMapID() (int, error) {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
m, err := getMapStruct(mapPath)
if err != nil {
return -1, err
}
return m.Id, nil
}
func (b *BPFLib) DumpFailsafeMap() ([]ProtoPort, error) {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
prog := "bpftool"
args := []string{
"--json",
"--pretty",
"map",
"dump",
"pinned",
mapPath}
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to dump map (%s): %s\n%s", mapPath, err, output)
}
l := []mapEntry{}
err = json.Unmarshal(output, &l)
if err != nil {
return nil, fmt.Errorf("cannot parse json output: %v\n%s", err, output)
}
pp := []ProtoPort{}
for _, entry := range l {
proto, port, err := hexToFailsafe(entry.Key)
if err != nil {
return nil, err
}
pp = append(pp, ProtoPort{labelindex.IPSetPortProtocol(proto), port})
}
return pp, nil
}
func (b *BPFLib) GetCIDRMapID(ifName string, family IPFamily) (int, error) {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
m, err := getMapStruct(mapPath)
if err != nil {
return -1, err
}
return m.Id, nil
}
func (b *BPFLib) IsValidMap(ifName string, family IPFamily) (bool, error) {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
m, err := getMapStruct(mapPath)
if err != nil {
return false, err
}
switch family {
case IPFamilyV4:
if m.Type != "lpm_trie" || m.KeySize != 8 || m.ValueSize != 4 {
return false, nil
}
case IPFamilyV6:
return false, fmt.Errorf("IPv6 not implemented yet")
default:
return false, fmt.Errorf("unknown IP family %d", family)
}
return true, nil
}
func (b *BPFLib) LookupFailsafeMap(proto uint8, port uint16) (bool, error) {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return false, err
}
hexKey, err := failsafeToHex(proto, port)
if err != nil {
return false, err
}
prog := "bpftool"
args := []string{
"--json",
"--pretty",
"map",
"lookup",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return false, fmt.Errorf("failed to lookup in map (%s): %s\n%s", mapName, err, output)
}
l := mapEntry{}
err = json.Unmarshal(output, &l)
if err != nil {
return false, fmt.Errorf("cannot parse json output: %v\n%s", err, output)
}
if l.Err != "" {
return false, fmt.Errorf("%s", l.Err)
}
return true, err
}
func (b *BPFLib) LookupCIDRMap(ifName string, family IPFamily, ip net.IP, mask int) (uint32, error) {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return 0, err
}
cidr := fmt.Sprintf("%s/%d", ip.String(), mask)
hexKey, err := CidrToHex(cidr)
if err != nil {
return 0, err
}
prog := "bpftool"
args := []string{
"--json",
"--pretty",
"map",
"lookup",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return 0, fmt.Errorf("failed to lookup in map (%s): %s\n%s", mapName, err, output)
}
l := mapEntry{}
err = json.Unmarshal(output, &l)
if err != nil {
return 0, fmt.Errorf("cannot parse json output: %v\n%s", err, output)
}
if l.Err != "" {
return 0, fmt.Errorf("%s", l.Err)
}
val, err := hexToCIDRMapValue(l.Value)
if err != nil {
return 0, err
}
return val, err
}
type CIDRMapKey struct {
rawIP [16]byte
rawMask [16]byte
}
func (k *CIDRMapKey) ToIPNet() *net.IPNet {
ip := net.IP(k.rawIP[:]).To16()
mask := func() net.IPMask {
if ip.To4() != nil {
// it's an IPV4 address
return k.rawMask[12:16]
} else {
return k.rawMask[:]
}
}()
return &net.IPNet{
IP: ip,
Mask: mask,
}
}
func NewCIDRMapKey(n *net.IPNet) CIDRMapKey {
k := CIDRMapKey{
rawMask: [16]byte{
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
},
}
rawIPSlice := k.rawIP[:]
copy(rawIPSlice, n.IP.To16())
rawMaskSlice := k.rawMask[len(k.rawMask)-len(n.Mask):]
copy(rawMaskSlice, n.Mask)
return k
}
func (b *BPFLib) DumpCIDRMap(ifName string, family IPFamily) (map[CIDRMapKey]uint32, error) {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return nil, err
}
prog := "bpftool"
args := []string{
"--json",
"--pretty",
"map",
"dump",
"pinned",
mapPath}
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to dump in map (%s): %s\n%s", mapName, err, output)
}
var al []mapEntry
err = json.Unmarshal(output, &al)
if err != nil {
return nil, fmt.Errorf("cannot parse json output: %v\n%s", err, output)
}
m := make(map[CIDRMapKey]uint32, len(al))
for _, l := range al {
ipnet, err := hexToIPNet(l.Key, family)
if err != nil {
return nil, fmt.Errorf("failed to parse bpf map key (%v) to ip and mask: %v", l.Key, err)
}
value, err := hexToCIDRMapValue(l.Value)
if err != nil {
return nil, fmt.Errorf("failed to parse bpf map value (%v): %v", l.Value, err)
}
m[NewCIDRMapKey(ipnet)] = value
}
return m, nil
}
func (b *BPFLib) RemoveItemFailsafeMap(proto uint8, port uint16) error {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return err
}
hexKey, err := failsafeToHex(proto, port)
if err != nil {
return err
}
prog := "bpftool"
args := []string{
"map",
"delete",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to delete item (%d) from map (%s): %s\n%s", port, mapName, err, output)
}
return nil
}
func (b *BPFLib) RemoveItemCIDRMap(ifName string, family IPFamily, ip net.IP, mask int) error {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return err
}
cidr := fmt.Sprintf("%s/%d", ip.String(), mask)
hexKey, err := CidrToHex(cidr)
if err != nil {
return err
}
prog := "bpftool"
args := []string{
"map",
"delete",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to delete item (%v/%d) from map (%s): %s\n%s", ip, mask, mapName, err, output)
}
return nil
}
func (b *BPFLib) UpdateFailsafeMap(proto uint8, port uint16) error {
mapName := failsafeMapName
mapPath := filepath.Join(b.calicoDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return err
}
hexKey, err := failsafeToHex(proto, port)
if err != nil {
return err
}
prog := "bpftool"
args := []string{
"map",
"update",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
args = append(args, []string{
"value",
fmt.Sprintf("%d", 1), // it's just a set, so use 1 as value
}...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to update map (%s) with (%d): %s\n%s", mapName, port, err, output)
}
return nil
}
func (b *BPFLib) UpdateCIDRMap(ifName string, family IPFamily, ip net.IP, mask int, refCount uint32) error {
mapName := getCIDRMapName(ifName, family)
mapPath := filepath.Join(b.xdpDir, mapName)
if err := os.MkdirAll(b.xdpDir, 0700); err != nil {
return err
}
cidr := fmt.Sprintf("%s/%d", ip.String(), mask)
hexKey, err := CidrToHex(cidr)
if err != nil {
return err
}
hexValue := cidrMapValueToHex(refCount)
prog := "bpftool"
args := []string{
"map",
"update",
"pinned",
mapPath,
"key",
"hex"}
args = append(args, hexKey...)
args = append(args, "value", "hex")
args = append(args, hexValue...)
printCommand(prog, args...)
output, err := exec.Command(prog, args...).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to update map (%s) with (%v/%d): %s\n%s", mapName, ip, mask, err, output)
}
return nil
}
func (b *BPFLib) loadXDPRaw(objPath, ifName string, mode XDPMode, mapArgs []string) error {
progName := getProgName(ifName)
progPath := filepath.Join(b.xdpDir, progName)
if err := b.loadBPF(objPath, progPath, "xdp", mapArgs); err != nil {
return err
}