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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
|
package bridge
import (
"bytes"
"context"
"encoding/json"
"fmt"
"maps"
"net"
"net/netip"
"os/exec"
"slices"
"strconv"
"testing"
"github.com/docker/docker/internal/nlwrap"
"github.com/docker/docker/internal/testutils/netnsutils"
"github.com/docker/docker/internal/testutils/storeutils"
"github.com/docker/docker/libnetwork/driverapi"
"github.com/docker/docker/libnetwork/drivers/bridge/internal/firewaller"
"github.com/docker/docker/libnetwork/internal/netiputil"
"github.com/docker/docker/libnetwork/ipamapi"
"github.com/docker/docker/libnetwork/ipams/defaultipam"
"github.com/docker/docker/libnetwork/ipamutils"
"github.com/docker/docker/libnetwork/netlabel"
"github.com/docker/docker/libnetwork/netutils"
"github.com/docker/docker/libnetwork/options"
"github.com/docker/docker/libnetwork/portallocator"
"github.com/docker/docker/libnetwork/types"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/vishvananda/netlink"
"github.com/vishvananda/netns"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/icmd"
)
func TestEndpointMarshalling(t *testing.T) {
ip1, _ := types.ParseCIDR("172.22.0.9/16")
ip2, _ := types.ParseCIDR("2001:db8::9")
mac, _ := net.ParseMAC("ac:bd:24:57:66:77")
e := &bridgeEndpoint{
id: "d2c015a1fe5930650cbcd50493efba0500bcebd8ee1f4401a16319f8a567de33",
nid: "ee33fbb43c323f1920b6b35a0101552ac22ede960d0e5245e9738bccc68b2415",
addr: ip1,
addrv6: ip2,
macAddress: mac,
srcName: "veth123456",
containerConfig: &containerConfiguration{
ParentEndpoints: []string{"one", "due", "three"},
ChildEndpoints: []string{"four", "five", "six"},
},
extConnConfig: &connectivityConfiguration{
ExposedPorts: []types.TransportPort{
{
Proto: 6,
Port: 18,
},
},
PortBindings: []types.PortBinding{
{
Proto: 6,
IP: net.ParseIP("17210.33.9.56"),
Port: 18,
HostPort: 3000,
HostPortEnd: 14000,
},
},
},
portMapping: []portBinding{
{
PortBinding: types.PortBinding{
Proto: 17,
IP: net.ParseIP("172.33.9.56"),
Port: 99,
HostIP: net.ParseIP("10.10.100.2"),
HostPort: 9900,
HostPortEnd: 10000,
},
},
{
PortBinding: types.PortBinding{
Proto: 6,
IP: net.ParseIP("171.33.9.56"),
Port: 55,
HostIP: net.ParseIP("10.11.100.2"),
HostPort: 5500,
HostPortEnd: 55000,
},
},
},
}
b, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
ee := &bridgeEndpoint{}
err = json.Unmarshal(b, ee)
if err != nil {
t.Fatal(err)
}
if e.id != ee.id || e.nid != ee.nid || e.srcName != ee.srcName || !bytes.Equal(e.macAddress, ee.macAddress) ||
!types.CompareIPNet(e.addr, ee.addr) || !types.CompareIPNet(e.addrv6, ee.addrv6) ||
!compareContainerConfig(e.containerConfig, ee.containerConfig) ||
!compareConnConfig(e.extConnConfig, ee.extConnConfig) {
t.Fatalf("JSON marsh/unmarsh failed.\nOriginal:\n%#v\nDecoded:\n%#v", e, ee)
}
// On restore, the HostPortEnd in portMapping is set to HostPort (so that
// a different port cannot be selected on live-restore if the original is
// already in-use). So, fix up portMapping in the original before running
// the comparison.
epms := make([]portBinding, len(e.portMapping))
for i, p := range e.portMapping {
epms[i] = p
epms[i].HostPortEnd = epms[i].HostPort
}
if !compareBindings(epms, ee.portMapping) {
t.Fatalf("JSON marsh/unmarsh failed.\nOriginal portMapping:\n%#v\nDecoded portMapping:\n%#v", e, ee)
}
}
func compareContainerConfig(a, b *containerConfiguration) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
if len(a.ParentEndpoints) != len(b.ParentEndpoints) ||
len(a.ChildEndpoints) != len(b.ChildEndpoints) {
return false
}
for i := 0; i < len(a.ParentEndpoints); i++ {
if a.ParentEndpoints[i] != b.ParentEndpoints[i] {
return false
}
}
for i := 0; i < len(a.ChildEndpoints); i++ {
if a.ChildEndpoints[i] != b.ChildEndpoints[i] {
return false
}
}
return true
}
func compareConnConfig(a, b *connectivityConfiguration) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
if len(a.ExposedPorts) != len(b.ExposedPorts) ||
len(a.PortBindings) != len(b.PortBindings) {
return false
}
for i := 0; i < len(a.ExposedPorts); i++ {
if !a.ExposedPorts[i].Equal(&b.ExposedPorts[i]) {
return false
}
}
for i := 0; i < len(a.PortBindings); i++ {
if !comparePortBinding(&a.PortBindings[i], &b.PortBindings[i]) {
return false
}
}
return true
}
// comparePortBinding returns whether the given PortBindings are equal.
func comparePortBinding(p *types.PortBinding, o *types.PortBinding) bool {
if p == o {
return true
}
if o == nil {
return false
}
if p.Proto != o.Proto || p.Port != o.Port ||
p.HostPort != o.HostPort || p.HostPortEnd != o.HostPortEnd {
return false
}
if p.IP != nil {
if !p.IP.Equal(o.IP) {
return false
}
} else {
if o.IP != nil {
return false
}
}
if p.HostIP != nil {
if !p.HostIP.Equal(o.HostIP) {
return false
}
} else {
if o.HostIP != nil {
return false
}
}
return true
}
func compareBindings(a, b []portBinding) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !comparePortBinding(&a[i].PortBinding, &b[i].PortBinding) {
return false
}
}
return true
}
func TestNetworkConfigurationMarshalling(t *testing.T) {
nc := &networkConfiguration{
ID: "nid",
BridgeName: "bridgename",
EnableIPv4: true,
EnableIPv6: true,
EnableIPMasquerade: true,
GwModeIPv4: gwModeRouted,
GwModeIPv6: gwModeIsolated,
EnableICC: true,
TrustedHostInterfaces: []string{"foo0", "bar1"},
InhibitIPv4: true,
Mtu: 1234,
DefaultBindingIP: net.ParseIP("192.0.2.1"),
DefaultBridge: true,
HostIPv4: net.ParseIP("192.0.2.2"),
HostIPv6: net.ParseIP("2001:db8::1"),
ContainerIfacePrefix: "baz",
}
b, err := json.Marshal(nc)
assert.Assert(t, err)
nnc := &networkConfiguration{}
err = json.Unmarshal(b, nnc)
assert.Assert(t, err)
assert.Check(t, is.DeepEqual(nnc, nc, cmpopts.IgnoreUnexported(networkConfiguration{})))
}
func getIPv4Data(t *testing.T) []driverapi.IPAMData {
t.Helper()
a, _ := defaultipam.NewAllocator(ipamutils.GetLocalScopeDefaultNetworks(), nil)
alloc, err := a.RequestPool(ipamapi.PoolRequest{
AddressSpace: "LocalDefault",
Exclude: netutils.InferReservedNetworks(false),
})
assert.NilError(t, err)
gw, _, err := a.RequestAddress(alloc.PoolID, nil, nil)
assert.NilError(t, err)
return []driverapi.IPAMData{{AddressSpace: "LocalDefault", Pool: netiputil.ToIPNet(alloc.Pool), Gateway: gw}}
}
func getIPv6Data(t *testing.T) []driverapi.IPAMData {
ipd := driverapi.IPAMData{AddressSpace: "full"}
// There's no default IPv6 address pool, so use an arbitrary unique-local prefix.
addr, nw, _ := net.ParseCIDR("fdcd:d1b1:99d2:abcd::1/64")
ipd.Pool = nw
ipd.Gateway = &net.IPNet{IP: addr, Mask: nw.Mask}
return []driverapi.IPAMData{ipd}
}
func TestCreateFullOptions(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
config := &configuration{
EnableIPForwarding: true,
EnableIPTables: true,
}
// Test this scenario: Default gw address does not belong to
// container network and it's greater than bridge address
cnw, _ := types.ParseCIDR("172.16.122.0/24")
bnw, _ := types.ParseCIDR("172.16.0.0/24")
br, _ := types.ParseCIDR("172.16.0.1/16")
defgw, _ := types.ParseCIDR("172.16.0.100/16")
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.configure(genericOption); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
netOption := make(map[string]interface{})
netOption[netlabel.EnableIPv4] = true
netOption[netlabel.EnableIPv6] = true
netOption[netlabel.GenericData] = &networkConfiguration{
BridgeName: DefaultBridgeName,
}
ipdList := []driverapi.IPAMData{
{
Pool: bnw,
Gateway: br,
AuxAddresses: map[string]*net.IPNet{DefaultGatewayV4AuxKey: defgw},
},
}
err := d.CreateNetwork(context.Background(), "dummy", netOption, nil, ipdList, getIPv6Data(t))
if err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
// Verify the IP address allocated for the endpoint belongs to the container network
epOptions := make(map[string]interface{})
te := newTestEndpoint(cnw, 10)
err = d.CreateEndpoint(context.Background(), "dummy", "ep1", te.Interface(), epOptions)
if err != nil {
t.Fatalf("Failed to create an endpoint : %s", err.Error())
}
if !cnw.Contains(te.Interface().Address().IP) {
t.Fatalf("endpoint got assigned address outside of container network(%s): %s", cnw.String(), te.Interface().Address())
}
}
func TestCreateNoConfig(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
err := d.configure(nil)
assert.NilError(t, err)
netconfig := &networkConfiguration{BridgeName: DefaultBridgeName, EnableIPv4: true}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
if err := d.CreateNetwork(context.Background(), "dummy", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
}
func TestCreateFullOptionsLabels(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
config := &configuration{
EnableIPForwarding: true,
}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.configure(genericOption); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
bndIPs := "127.0.0.1"
testHostIPv4 := "1.2.3.4"
nwV6s := "2001:db8:2600:2700:2800::/80"
gwV6s := "2001:db8:2600:2700:2800::25/80"
nwV6, _ := types.ParseCIDR(nwV6s)
gwV6, _ := types.ParseCIDR(gwV6s)
labels := map[string]string{
BridgeName: DefaultBridgeName,
DefaultBridge: "true",
EnableICC: "true",
EnableIPMasquerade: "true",
DefaultBindingIP: bndIPs,
netlabel.HostIPv4: testHostIPv4,
}
netOption := make(map[string]interface{})
netOption[netlabel.EnableIPv4] = true
netOption[netlabel.EnableIPv6] = true
netOption[netlabel.GenericData] = labels
ipdList := getIPv4Data(t)
ipd6List := []driverapi.IPAMData{
{
Pool: nwV6,
AuxAddresses: map[string]*net.IPNet{
DefaultGatewayV6AuxKey: gwV6,
},
},
}
err := d.CreateNetwork(context.Background(), "dummy", netOption, nil, ipdList, ipd6List)
if err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
nw, ok := d.networks["dummy"]
if !ok {
t.Fatal("Cannot find dummy network in bridge driver")
}
if nw.config.BridgeName != DefaultBridgeName {
t.Fatal("incongruent name in bridge network")
}
if !nw.config.EnableIPv4 {
t.Fatal("incongruent EnableIPv4 in bridge network")
}
if !nw.config.EnableIPv6 {
t.Fatal("incongruent EnableIPv6 in bridge network")
}
if !nw.config.EnableICC {
t.Fatal("incongruent EnableICC in bridge network")
}
if !nw.config.EnableIPMasquerade {
t.Fatal("incongruent EnableIPMasquerade in bridge network")
}
bndIP := net.ParseIP(bndIPs)
if !bndIP.Equal(nw.config.DefaultBindingIP) {
t.Fatalf("Unexpected: %v", nw.config.DefaultBindingIP)
}
hostIP := net.ParseIP(testHostIPv4)
if !hostIP.Equal(nw.config.HostIPv4) {
t.Fatalf("Unexpected: %v", nw.config.HostIPv4)
}
if !types.CompareIPNet(nw.config.AddressIPv6, nwV6) {
t.Fatalf("Unexpected: %v", nw.config.AddressIPv6)
}
if !gwV6.IP.Equal(nw.config.DefaultGatewayIPv6) {
t.Fatalf("Unexpected: %v", nw.config.DefaultGatewayIPv6)
}
// Check that a MAC address is generated if not already configured.
te1 := newTestEndpoint(ipdList[0].Pool, 20)
err = d.CreateEndpoint(context.Background(), "dummy", "ep1", te1.Interface(), map[string]interface{}{})
assert.NilError(t, err)
assert.Check(t, is.Len(te1.iface.mac, 6))
// Check that a configured --mac-address isn't overwritten by a generated address.
te2 := newTestEndpoint(ipdList[0].Pool, 20)
const macAddr = "aa:bb:cc:dd:ee:ff"
te2.iface.mac = netutils.MustParseMAC(macAddr)
err = d.CreateEndpoint(context.Background(), "dummy", "ep2", te2.Interface(), map[string]interface{}{})
assert.NilError(t, err)
assert.Check(t, is.Equal(te2.iface.mac.String(), macAddr))
}
func TestCreateVeth(t *testing.T) {
tests := []struct {
name string
netnsName string
createNetns bool
expCreatedInContainer bool
}{
{
name: "host netns",
},
{
name: "container netns",
netnsName: "testnsctr",
createNetns: true,
expCreatedInContainer: true,
},
{
name: "netns not created",
netnsName: "testnsctr",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// Create a "host" network namespace with a netlink handle.
const hostNsName = "testnshost"
res := icmd.RunCommand("ip", "netns", "add", hostNsName)
assert.Assert(t, is.Equal(res.ExitCode, 0))
defer icmd.RunCommand("ip", "netns", "del", hostNsName)
nsh, err := netns.GetFromPath("/var/run/netns/" + hostNsName)
assert.NilError(t, err)
defer nsh.Close()
nlh, err := nlwrap.NewHandleAt(nsh)
assert.NilError(t, err)
defer nlh.Close()
netnsPath := ""
if tc.netnsName != "" {
netnsPath = "/var/run/netns/" + tc.netnsName
}
if tc.createNetns {
res := icmd.RunCommand("ip", "netns", "add", tc.netnsName)
assert.Assert(t, is.Equal(res.ExitCode, 0))
defer icmd.RunCommand("ip", "netns", "del", tc.netnsName)
}
const hostIfName = "vethtesth"
const containerIfName = "vethtestc"
defer func() {
// Just in case anything ends up in the host's netns, make sure it doesn't hang around ...
icmd.RunCommand("ip", "link", "del", hostIfName)
icmd.RunCommand("ip", "link", "del", containerIfName)
}()
iface := &testInterface{netnsPath: netnsPath}
nlhCtr, err := createVeth(context.Background(), hostIfName, containerIfName, iface, nlh)
assert.Check(t, err)
assert.Check(t, is.Equal(iface.createdInContainer, tc.expCreatedInContainer))
if tc.expCreatedInContainer {
assert.Check(t, nlhCtr != nil)
res := icmd.RunCommand("ip", "netns", "exec", hostNsName, "ip", "link", "show", hostIfName)
assert.Check(t, is.Equal(res.ExitCode, 0))
res = icmd.RunCommand("ip", "netns", "exec", hostNsName, "ip", "link", "show", containerIfName)
assert.Check(t, is.Equal(res.ExitCode, 1))
res = icmd.RunCommand("ip", "netns", "exec", tc.netnsName, "ip", "link", "show", containerIfName)
assert.Check(t, is.Equal(res.ExitCode, 0))
} else {
assert.Check(t, nlhCtr == nil)
res := icmd.RunCommand("ip", "netns", "exec", hostNsName, "ip", "link", "show", hostIfName)
assert.Check(t, is.Equal(res.ExitCode, 0))
res = icmd.RunCommand("ip", "netns", "exec", hostNsName, "ip", "link", "show", containerIfName)
assert.Check(t, is.Equal(res.ExitCode, 0))
}
})
}
}
func TestCreate(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
if err := d.configure(nil); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
netconfig := &networkConfiguration{BridgeName: DefaultBridgeName, EnableIPv4: true}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
if err := d.CreateNetwork(context.Background(), "dummy", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
err := d.CreateNetwork(context.Background(), "dummy", genericOption, nil, getIPv4Data(t), nil)
if err == nil {
t.Fatal("Expected bridge driver to refuse creation of second network with default name")
}
if _, ok := err.(types.ForbiddenError); !ok {
t.Fatal("Creation of second network with default name failed with unexpected error type")
}
}
func TestCreateFail(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
if err := d.configure(nil); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
netconfig := &networkConfiguration{BridgeName: "dummy0", DefaultBridge: true}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
if err := d.CreateNetwork(context.Background(), "dummy", genericOption, nil, getIPv4Data(t), nil); err == nil {
t.Fatal("Bridge creation was expected to fail")
}
}
func TestCreateMultipleNetworks(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
useStubFirewaller(t)
d := newDriver(storeutils.NewTempStore(t))
checkFirewallerNetworks := func() {
t.Helper()
fw := d.firewaller.(*firewaller.StubFirewaller)
got := maps.Clone(fw.Networks)
for _, wantNw := range d.networks {
_, ok := got[wantNw.config.BridgeName]
assert.Check(t, ok, "Rules for bridge %s (nid:%s) have been deleted", wantNw.config.BridgeName, wantNw.id)
delete(got, wantNw.config.BridgeName)
}
assert.Check(t, is.Len(slices.Collect(maps.Keys(got)), 0), "Rules for bridges have not been deleted")
}
config := &configuration{
EnableIPTables: true,
}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.configure(genericOption); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
config1 := &networkConfiguration{BridgeName: "net_test_1", EnableIPv4: true}
genericOption = make(map[string]interface{})
genericOption[netlabel.GenericData] = config1
if err := d.CreateNetwork(context.Background(), "1", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
checkFirewallerNetworks()
config2 := &networkConfiguration{BridgeName: "net_test_2", EnableIPv4: true}
genericOption[netlabel.GenericData] = config2
if err := d.CreateNetwork(context.Background(), "2", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
checkFirewallerNetworks()
config3 := &networkConfiguration{BridgeName: "net_test_3", EnableIPv4: true}
genericOption[netlabel.GenericData] = config3
if err := d.CreateNetwork(context.Background(), "3", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
checkFirewallerNetworks()
config4 := &networkConfiguration{BridgeName: "net_test_4", EnableIPv4: true}
genericOption[netlabel.GenericData] = config4
if err := d.CreateNetwork(context.Background(), "4", genericOption, nil, getIPv4Data(t), nil); err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
checkFirewallerNetworks()
if err := d.DeleteNetwork("1"); err != nil {
t.Log(err)
}
checkFirewallerNetworks()
if err := d.DeleteNetwork("2"); err != nil {
t.Log(err)
}
checkFirewallerNetworks()
if err := d.DeleteNetwork("3"); err != nil {
t.Log(err)
}
checkFirewallerNetworks()
if err := d.DeleteNetwork("4"); err != nil {
t.Log(err)
}
checkFirewallerNetworks()
}
type testInterface struct {
mac net.HardwareAddr
addr *net.IPNet
addrv6 *net.IPNet
srcName string
dstPrefix string
dstName string
createdInContainer bool
netnsPath string
}
type testEndpoint struct {
iface *testInterface
gw net.IP
gw6 net.IP
routes []types.StaticRoute
}
func newTestEndpoint(nw *net.IPNet, ordinal byte) *testEndpoint {
addr := types.GetIPNetCopy(nw)
addr.IP[len(addr.IP)-1] = ordinal
return &testEndpoint{iface: &testInterface{addr: addr}}
}
// newTestEndpoint46 is like newTestEndpoint, but assigns an IPv6 address as well as IPv4.
func newTestEndpoint46(nw4, nw6 *net.IPNet, ordinal byte) *testEndpoint {
addr4 := types.GetIPNetCopy(nw4)
addr4.IP[len(addr4.IP)-1] = ordinal
addr6 := types.GetIPNetCopy(nw6)
addr6.IP[len(addr6.IP)-1] = ordinal
return &testEndpoint{
iface: &testInterface{
addr: addr4,
addrv6: addr6,
},
}
}
func (te *testEndpoint) Interface() *testInterface {
return te.iface
}
func (i *testInterface) MacAddress() net.HardwareAddr {
return i.mac
}
func (i *testInterface) Address() *net.IPNet {
return i.addr
}
func (i *testInterface) AddressIPv6() *net.IPNet {
return i.addrv6
}
func (i *testInterface) SetMacAddress(mac net.HardwareAddr) error {
if i.mac != nil {
return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", i.mac, mac)
}
if mac == nil {
return types.InvalidParameterErrorf("tried to set nil MAC address to endpoint interface")
}
i.mac = types.GetMacCopy(mac)
return nil
}
func (i *testInterface) SetIPAddress(address *net.IPNet) error {
if address.IP == nil {
return types.InvalidParameterErrorf("tried to set nil IP address to endpoint interface")
}
if address.IP.To4() == nil {
return setAddress(&i.addrv6, address)
}
return setAddress(&i.addr, address)
}
func setAddress(ifaceAddr **net.IPNet, address *net.IPNet) error {
if *ifaceAddr != nil {
return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address)
}
*ifaceAddr = types.GetIPNetCopy(address)
return nil
}
func (i *testInterface) NetnsPath() string {
return i.netnsPath
}
func (i *testInterface) SetCreatedInContainer(cic bool) {
i.createdInContainer = cic
}
func (i *testInterface) SetNames(srcName, dstPrefix, dstName string) error {
i.srcName = srcName
i.dstPrefix = dstPrefix
i.dstName = dstName
return nil
}
func (te *testEndpoint) InterfaceName() driverapi.InterfaceNameInfo {
if te.iface != nil {
return te.iface
}
return nil
}
func (te *testEndpoint) SetGateway(gw net.IP) error {
te.gw = gw
return nil
}
func (te *testEndpoint) SetGatewayIPv6(gw6 net.IP) error {
te.gw6 = gw6
return nil
}
func (te *testEndpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error {
te.routes = append(te.routes, types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop})
return nil
}
func (te *testEndpoint) AddTableEntry(tableName string, key string, value []byte) error {
return nil
}
func (te *testEndpoint) DisableGatewayService() {}
func TestQueryEndpointInfo(t *testing.T) {
testQueryEndpointInfo(t, true)
}
func TestQueryEndpointInfoHairpin(t *testing.T) {
testQueryEndpointInfo(t, false)
}
func testQueryEndpointInfo(t *testing.T, ulPxyEnabled bool) {
defer netnsutils.SetupTestOSContext(t)()
useStubFirewaller(t)
d := newDriver(storeutils.NewTempStore(t))
portallocator.Get().ReleaseAll()
var proxyBinary string
var err error
if ulPxyEnabled {
proxyBinary, err = exec.LookPath("docker-proxy")
if err != nil {
t.Fatalf("failed to lookup userland-proxy binary: %v", err)
}
}
config := &configuration{
EnableIPTables: true,
EnableUserlandProxy: ulPxyEnabled,
UserlandProxyPath: proxyBinary,
}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.configure(genericOption); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
netconfig := &networkConfiguration{
BridgeName: DefaultBridgeName,
EnableIPv4: true,
EnableICC: false,
}
genericOption = make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
ipdList := getIPv4Data(t)
err = d.CreateNetwork(context.Background(), "net1", genericOption, nil, ipdList, nil)
if err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
sbOptions := make(map[string]interface{})
sbOptions[netlabel.PortMap] = getPortMapping()
te := newTestEndpoint(ipdList[0].Pool, 11)
err = d.CreateEndpoint(context.Background(), "net1", "ep1", te.Interface(), nil)
if err != nil {
t.Fatalf("Failed to create an endpoint : %s", err.Error())
}
err = d.Join(context.Background(), "net1", "ep1", "sbox", te, nil, sbOptions)
if err != nil {
t.Fatalf("Failed to join the endpoint: %v", err)
}
err = d.ProgramExternalConnectivity(context.Background(), "net1", "ep1", sbOptions)
if err != nil {
t.Fatalf("Failed to program external connectivity: %v", err)
}
network, ok := d.networks["net1"]
if !ok {
t.Fatalf("Cannot find network %s inside driver", "net1")
}
ep := network.endpoints["ep1"]
data, err := d.EndpointOperInfo(network.id, ep.id)
if err != nil {
t.Fatalf("Failed to ask for endpoint operational data: %v", err)
}
pmd, ok := data[netlabel.PortMap]
if !ok {
t.Fatal("Endpoint operational data does not contain port mapping data")
}
pm, ok := pmd.([]types.PortBinding)
if !ok {
t.Fatal("Unexpected format for port mapping in endpoint operational data")
}
if len(ep.portMapping) != len(pm) {
t.Fatal("Incomplete data for port mapping in endpoint operational data")
}
for i, pb := range ep.portMapping {
if !comparePortBinding(&pb.PortBinding, &pm[i]) {
t.Fatal("Unexpected data for port mapping in endpoint operational data")
}
}
err = d.RevokeExternalConnectivity("net1", "ep1")
if err != nil {
t.Fatal(err)
}
// release host mapped ports
err = d.Leave("net1", "ep1")
if err != nil {
t.Fatal(err)
}
}
func getExposedPorts() []types.TransportPort {
return []types.TransportPort{
{Proto: types.TCP, Port: 5000},
{Proto: types.UDP, Port: 400},
{Proto: types.TCP, Port: 600},
}
}
func getPortMapping() []types.PortBinding {
return []types.PortBinding{
{Proto: types.TCP, Port: 230, HostPort: 23000},
{Proto: types.UDP, Port: 200, HostPort: 22000},
{Proto: types.TCP, Port: 120, HostPort: 12000},
}
}
func TestLinkContainers(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
useStubFirewaller(t)
d := newDriver(storeutils.NewTempStore(t))
config := &configuration{
EnableIPTables: true,
}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.configure(genericOption); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
netconfig := &networkConfiguration{
BridgeName: DefaultBridgeName,
EnableIPv4: true,
EnableICC: false,
}
genericOption = make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
ipdList := getIPv4Data(t)
err := d.CreateNetwork(context.Background(), "net1", genericOption, nil, ipdList, nil)
if err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
te1 := newTestEndpoint(ipdList[0].Pool, 11)
err = d.CreateEndpoint(context.Background(), "net1", "ep1", te1.Interface(), nil)
if err != nil {
t.Fatalf("Failed to create an endpoint : %s", err.Error())
}
exposedPorts := getExposedPorts()
sbOptions := make(map[string]interface{})
sbOptions[netlabel.ExposedPorts] = exposedPorts
err = d.Join(context.Background(), "net1", "ep1", "sbox", te1, nil, sbOptions)
if err != nil {
t.Fatalf("Failed to join the endpoint: %v", err)
}
err = d.ProgramExternalConnectivity(context.Background(), "net1", "ep1", sbOptions)
if err != nil {
t.Fatalf("Failed to program external connectivity: %v", err)
}
addr1 := te1.iface.addr
if addr1.IP.To4() == nil {
t.Fatal("No Ipv4 address assigned to the endpoint: ep1")
}
te2 := newTestEndpoint(ipdList[0].Pool, 22)
err = d.CreateEndpoint(context.Background(), "net1", "ep2", te2.Interface(), nil)
if err != nil {
t.Fatalf("Failed to create an endpoint : %s", err.Error())
}
addr2 := te2.iface.addr
if addr2.IP.To4() == nil {
t.Fatal("No Ipv4 address assigned to the endpoint: ep2")
}
sbOptions = make(map[string]interface{})
sbOptions[netlabel.GenericData] = options.Generic{
"ChildEndpoints": []string{"ep1"},
}
err = d.Join(context.Background(), "net1", "ep2", "", te2, nil, sbOptions)
if err != nil {
t.Fatal("Failed to link ep1 and ep2")
}
err = d.ProgramExternalConnectivity(context.Background(), "net1", "ep2", sbOptions)
if err != nil {
t.Fatalf("Failed to program external connectivity: %v", err)
}
checkLink := func(expExists bool) {
t.Helper()
dnw, ok := d.networks["net1"]
assert.Assert(t, ok)
fnw := dnw.firewallerNetwork.(*firewaller.StubFirewallerNetwork)
parentAddr, ok := netip.AddrFromSlice(te2.iface.addr.IP)
assert.Assert(t, ok)
childAddr, ok := netip.AddrFromSlice(te1.iface.addr.IP)
assert.Assert(t, ok)
exists := fnw.LinkExists(parentAddr, childAddr, exposedPorts)
assert.Check(t, is.Equal(exists, expExists))
}
checkLink(true)
err = d.RevokeExternalConnectivity("net1", "ep2")
if err != nil {
t.Fatalf("Failed to revoke external connectivity: %v", err)
}
err = d.Leave("net1", "ep2")
if err != nil {
t.Fatal("Failed to unlink ep1 and ep2")
}
checkLink(false)
// Error condition test with an invalid endpoint-id "ep4"
sbOptions = make(map[string]interface{})
sbOptions[netlabel.GenericData] = options.Generic{
"ChildEndpoints": []string{"ep1", "ep4"},
}
err = d.Join(context.Background(), "net1", "ep2", "", te2, nil, sbOptions)
if err != nil {
t.Fatal(err)
}
err = d.ProgramExternalConnectivity(context.Background(), "net1", "ep2", sbOptions)
assert.Check(t, err != nil, "Expected Join to fail given link conditions are not satisfied")
checkLink(false)
}
func TestValidateConfig(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
// Bridge network
_, network, _ := net.ParseCIDR("172.28.0.0/16")
c := networkConfiguration{
AddressIPv4: network,
EnableIPv4: true,
}
err := c.Validate()
if err != nil {
t.Fatal("unexpected validation error:", err)
}
// Test mtu
c.Mtu = -2
err = c.Validate()
if err == nil {
t.Fatal("Failed to detect invalid MTU number")
}
c.Mtu = 9000
err = c.Validate()
if err != nil {
t.Fatal("unexpected validation error on MTU number:", err)
}
err = c.Validate()
if err != nil {
t.Fatal(err)
}
// Test v4 gw
c.DefaultGatewayIPv4 = net.ParseIP("172.27.30.234")
err = c.Validate()
if err == nil {
t.Fatal("Failed to detect invalid default gateway")
}
c.DefaultGatewayIPv4 = net.ParseIP("172.28.30.234")
err = c.Validate()
if err != nil {
t.Fatal("Unexpected validation error on default gateway")
}
// Test v6 gw
_, v6nw, _ := net.ParseCIDR("2001:db8:ae:b004::/64")
c = networkConfiguration{
EnableIPv6: true,
AddressIPv6: v6nw,
DefaultGatewayIPv6: net.ParseIP("2001:db8:ac:b004::bad:a55"),
}
err = c.Validate()
if err == nil {
t.Fatal("Failed to detect invalid v6 default gateway")
}
c.DefaultGatewayIPv6 = net.ParseIP("2001:db8:ae:b004::bad:a55")
err = c.Validate()
if err != nil {
t.Fatal("Unexpected validation error on v6 default gateway")
}
c.AddressIPv6 = nil
err = c.Validate()
if err == nil {
t.Fatal("Failed to detect invalid v6 default gateway")
}
c.AddressIPv6 = nil
err = c.Validate()
if err == nil {
t.Fatal("Failed to detect invalid v6 default gateway")
}
}
func TestValidateFixedCIDRV6(t *testing.T) {
tests := []struct {
doc, input, expectedErr string
}{
{
doc: "valid",
input: "2001:db8::/32",
},
{
// fixed-cidr-v6 doesn't have to be specified.
doc: "empty",
},
{
// Using the LL subnet prefix is ok.
doc: "Link-Local subnet prefix",
input: "fe80::/64",
},
{
// Using a nonstandard LL prefix that doesn't overlap with the standard LL prefix
// is ok.
doc: "non-overlapping link-local prefix",
input: "fe80:1234::/80",
},
{
// Overlapping with the standard LL prefix isn't allowed.
doc: "overlapping link-local prefix fe80::/63",
input: "fe80::/63",
expectedErr: "invalid fixed-cidr-v6: 'fe80::/63' clashes with the Link-Local prefix 'fe80::/64'",
},
{
// Overlapping with the standard LL prefix isn't allowed.
doc: "overlapping link-local subnet fe80::/65",
input: "fe80::/65",
expectedErr: "invalid fixed-cidr-v6: 'fe80::/65' clashes with the Link-Local prefix 'fe80::/64'",
},
{
// The address has to be valid IPv6 subnet.
doc: "invalid IPv6 subnet",
input: "2000:db8::",
expectedErr: "invalid fixed-cidr-v6: netip.ParsePrefix(\"2000:db8::\"): no '/'",
},
{
doc: "non-IPv6 subnet",
input: "10.3.4.5/24",
expectedErr: "invalid fixed-cidr-v6: '10.3.4.5/24' is not a valid IPv6 subnet",
},
{
doc: "IPv4-mapped subnet 1",
input: "::ffff:10.2.4.0/24",
expectedErr: "invalid fixed-cidr-v6: '::ffff:10.2.4.0/24' is not a valid IPv6 subnet",
},
{
doc: "IPv4-mapped subnet 2",
input: "::ffff:a01:203/24",
expectedErr: "invalid fixed-cidr-v6: '::ffff:10.1.2.3/24' is not a valid IPv6 subnet",
},
{
doc: "invalid subnet",
input: "nonsense",
expectedErr: "invalid fixed-cidr-v6: netip.ParsePrefix(\"nonsense\"): no '/'",
},
{
doc: "multicast IPv6 subnet",
input: "ff05::/64",
expectedErr: "invalid fixed-cidr-v6: multicast subnet 'ff05::/64' is not allowed",
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
err := ValidateFixedCIDRV6(tc.input)
if tc.expectedErr == "" {
assert.Check(t, err)
} else {
assert.Check(t, is.Error(err, tc.expectedErr))
}
})
}
}
func TestSetDefaultGw(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
if err := d.configure(nil); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
ipam4 := getIPv4Data(t)
gw4 := types.GetIPCopy(ipam4[0].Pool.IP).To4()
gw4[3] = 254
ipam6 := getIPv6Data(t)
gw6 := types.GetIPCopy(ipam6[0].Pool.IP)
gw6[15] = 0x42
option := map[string]interface{}{
netlabel.EnableIPv4: true,
netlabel.EnableIPv6: true,
netlabel.GenericData: &networkConfiguration{
BridgeName: DefaultBridgeName,
DefaultGatewayIPv4: gw4,
DefaultGatewayIPv6: gw6,
},
}
err := d.CreateNetwork(context.Background(), "dummy", option, nil, ipam4, ipam6)
if err != nil {
t.Fatalf("Failed to create bridge: %v", err)
}
te := newTestEndpoint(ipam4[0].Pool, 10)
err = d.CreateEndpoint(context.Background(), "dummy", "ep", te.Interface(), nil)
if err != nil {
t.Fatalf("Failed to create endpoint: %v", err)
}
err = d.Join(context.Background(), "dummy", "ep", "sbox", te, nil, nil)
if err != nil {
t.Fatalf("Failed to join endpoint: %v", err)
}
if !gw4.Equal(te.gw) {
t.Fatalf("Failed to configure default gateway. Expected %v. Found %v", gw4, te.gw)
}
if !gw6.Equal(te.gw6) {
t.Fatalf("Failed to configure default gateway. Expected %v. Found %v", gw6, te.gw6)
}
}
func TestCreateWithExistingBridge(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
if err := d.configure(nil); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
brName := "br111"
br := &netlink.Bridge{
LinkAttrs: netlink.LinkAttrs{
Name: brName,
},
}
if err := netlink.LinkAdd(br); err != nil {
t.Fatalf("Failed to create bridge interface: %v", err)
}
defer netlink.LinkDel(br)
if err := netlink.LinkSetUp(br); err != nil {
t.Fatalf("Failed to set bridge interface up: %v", err)
}
ip := net.IP{192, 168, 122, 1}
addr := &netlink.Addr{IPNet: &net.IPNet{
IP: ip,
Mask: net.IPv4Mask(255, 255, 255, 0),
}}
if err := netlink.AddrAdd(br, addr); err != nil {
t.Fatalf("Failed to add IP address to bridge: %v", err)
}
netconfig := &networkConfiguration{BridgeName: brName, EnableIPv4: true}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = netconfig
ipv4Data := []driverapi.IPAMData{{
AddressSpace: "full",
Pool: types.GetIPNetCopy(addr.IPNet),
Gateway: types.GetIPNetCopy(addr.IPNet),
}}
// Set network gateway to X.X.X.1
ipv4Data[0].Gateway.IP[len(ipv4Data[0].Gateway.IP)-1] = 1
if err := d.CreateNetwork(context.Background(), brName, genericOption, nil, ipv4Data, nil); err != nil {
t.Fatalf("Failed to create bridge network: %v", err)
}
nw, err := d.getNetwork(brName)
if err != nil {
t.Fatalf("Failed to getNetwork(%s): %v", brName, err)
}
addrs4, err := nw.bridge.addresses(netlink.FAMILY_V4)
if err != nil {
t.Fatalf("Failed to get the bridge network's address: %v", err)
}
if !addrs4[0].IP.Equal(ip) {
t.Fatal("Creating bridge network with existing bridge interface unexpectedly modified the IP address of the bridge")
}
if err := d.DeleteNetwork(brName); err != nil {
t.Fatalf("Failed to delete network %s: %v", brName, err)
}
if _, err := nlwrap.LinkByName(brName); err != nil {
t.Fatal("Deleting bridge network that using existing bridge interface unexpectedly deleted the bridge interface")
}
}
func TestCreateParallel(t *testing.T) {
c := netnsutils.SetupTestOSContextEx(t)
defer c.Cleanup(t)
d := newDriver(storeutils.NewTempStore(t))
portallocator.Get().ReleaseAll()
if err := d.configure(nil); err != nil {
t.Fatalf("Failed to setup driver config: %v", err)
}
ipV4Data := getIPv4Data(t)
ch := make(chan error, 100)
for i := 0; i < 100; i++ {
name := "net" + strconv.Itoa(i)
c.Go(t, func() {
config := &networkConfiguration{BridgeName: name, EnableIPv4: true}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = config
if err := d.CreateNetwork(context.Background(), name, genericOption, nil, ipV4Data, nil); err != nil {
ch <- fmt.Errorf("failed to create %s", name)
return
}
if err := d.CreateNetwork(context.Background(), name, genericOption, nil, ipV4Data, nil); err == nil {
ch <- fmt.Errorf("failed was able to create overlap %s", name)
return
}
ch <- nil
})
}
// wait for the go routines
var success int
for i := 0; i < 100; i++ {
val := <-ch
if val == nil {
success++
}
}
if success != 1 {
t.Fatalf("Success should be 1 instead: %d", success)
}
}
func useStubFirewaller(t *testing.T) {
origNewFirewaller := newFirewaller
newFirewaller = func(_ context.Context, config firewaller.Config) (firewaller.Firewaller, error) {
return firewaller.NewStubFirewaller(config), nil
}
t.Cleanup(func() { newFirewaller = origNewFirewaller })
}
// Regression test for https://github.com/moby/moby/issues/46445
func TestSetupIP6TablesWithHostIPv4(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
d := newDriver(storeutils.NewTempStore(t))
dc := &configuration{
EnableIPTables: true,
EnableIP6Tables: true,
}
if err := d.configure(map[string]interface{}{netlabel.GenericData: dc}); err != nil {
t.Fatal(err)
}
nc := &networkConfiguration{
BridgeName: DefaultBridgeName,
AddressIPv4: &net.IPNet{IP: net.ParseIP("192.168.42.1"), Mask: net.CIDRMask(16, 32)},
EnableIPMasquerade: true,
EnableIPv4: true,
EnableIPv6: true,
AddressIPv6: &net.IPNet{IP: net.ParseIP("2001:db8::1"), Mask: net.CIDRMask(64, 128)},
HostIPv4: net.ParseIP("192.0.2.2"),
}
// Create test bridge.
nh, err := nlwrap.NewHandle()
if err != nil {
t.Fatal(err)
}
br := &bridgeInterface{nlh: nh}
if err := setupDevice(nc, br); err != nil {
t.Fatalf("Failed to create the testing Bridge: %s", err.Error())
}
if err := setupBridgeIPv4(nc, br); err != nil {
t.Fatalf("Failed to bring up the testing Bridge: %s", err.Error())
}
if err := setupBridgeIPv6(nc, br); err != nil {
t.Fatalf("Failed to bring up the testing Bridge: %s", err.Error())
}
// Check firewall configuration succeeds.
nw := bridgeNetwork{
config: nc,
driver: d,
bridge: br,
}
fwn, err := nw.newFirewallerNetwork(context.Background())
assert.NilError(t, err)
assert.Check(t, fwn != nil, "no firewaller network")
}
|