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 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
|
package libnetwork_test
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
cerrdefs "github.com/containerd/errdefs"
"github.com/containerd/log"
"github.com/docker/docker/internal/nlwrap"
"github.com/docker/docker/internal/testutils/netnsutils"
"github.com/docker/docker/libnetwork"
"github.com/docker/docker/libnetwork/config"
"github.com/docker/docker/libnetwork/driverapi"
"github.com/docker/docker/libnetwork/drivers/bridge"
"github.com/docker/docker/libnetwork/ipams/defaultipam"
"github.com/docker/docker/libnetwork/ipams/null"
"github.com/docker/docker/libnetwork/ipamutils"
"github.com/docker/docker/libnetwork/netlabel"
"github.com/docker/docker/libnetwork/options"
"github.com/docker/docker/libnetwork/osl"
"github.com/docker/docker/libnetwork/types"
"github.com/docker/docker/pkg/plugins"
"github.com/moby/sys/reexec"
"github.com/pkg/errors"
"github.com/vishvananda/netns"
"golang.org/x/sync/errgroup"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
const (
bridgeNetType = "bridge"
)
func newController(t *testing.T) *libnetwork.Controller {
t.Helper()
c, err := libnetwork.New(
context.Background(),
config.OptionDataDir(t.TempDir()),
config.OptionDriverConfig(bridgeNetType, map[string]interface{}{
netlabel.GenericData: options.Generic{
"EnableIPForwarding": true,
},
}),
config.OptionDefaultAddressPoolConfig(ipamutils.GetLocalScopeDefaultNetworks()),
)
assert.NilError(t, err)
t.Cleanup(c.Stop)
return c
}
func createTestNetwork(c *libnetwork.Controller, networkType, networkName string, netOption options.Generic, ipamV4Configs, ipamV6Configs []*libnetwork.IpamConf) (*libnetwork.Network, error) {
return c.NewNetwork(context.Background(), networkType, networkName, "",
libnetwork.NetworkOptionGeneric(netOption),
libnetwork.NetworkOptionIpam(defaultipam.DriverName, "", ipamV4Configs, ipamV6Configs, nil))
}
func getEmptyGenericOption() map[string]interface{} {
return map[string]interface{}{netlabel.GenericData: map[string]string{}}
}
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},
{Proto: types.TCP, Port: 320, HostPort: 32000, HostPortEnd: 32999},
{Proto: types.UDP, Port: 420, HostPort: 42000, HostPortEnd: 42001},
}
}
func TestNull(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
cnt, err := controller.NewSandbox(context.Background(), "null_container",
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
network, err := createTestNetwork(controller, "null", "testnull", options.Generic{}, nil, nil)
assert.NilError(t, err)
ep, err := network.CreateEndpoint(context.Background(), "testep")
assert.NilError(t, err)
err = ep.Join(context.Background(), cnt)
assert.NilError(t, err)
err = ep.Leave(context.Background(), cnt)
assert.NilError(t, err)
err = ep.Delete(context.Background(), false)
assert.NilError(t, err)
err = cnt.Delete(context.Background())
assert.NilError(t, err)
// host type is special network. Cannot be removed.
err = network.Delete()
// TODO(thaJeztah): should this be an [errdefs.ErrInvalidParameter] ?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, `network of type "null" cannot be deleted`))
}
func TestUnknownDriver(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
_, err := createTestNetwork(controller, "unknowndriver", "testnetwork", options.Generic{}, nil, nil)
// TODO(thaJeztah): should attempting to use a non-existing plugin/driver return an [errdefs.ErrInvalidParameter] ?
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.Error(err, "could not find plugin unknowndriver in v1 plugin registry: plugin not found"))
}
func TestNilRemoteDriver(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
_, err := controller.NewNetwork(context.Background(), "framerelay", "dummy", "",
libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
// TODO(thaJeztah): should attempting to use a non-existing plugin/driver return an [errdefs.InvalidParameter] ?
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.Error(err, "could not find plugin framerelay in v1 plugin registry: plugin not found"))
}
func TestNetworkName(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
_, err := createTestNetwork(controller, bridgeNetType, "", netOption, nil, nil)
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail with ErrInvalidName error")
const networkName = "testnetwork"
n, err := createTestNetwork(controller, bridgeNetType, networkName, netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
assert.Check(t, is.Equal(n.Name(), networkName))
}
func TestNetworkType(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
assert.Check(t, is.Equal(n.Type(), bridgeNetType))
}
func TestNetworkID(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
assert.Check(t, n.ID() != "", "Expected non-empty network id")
}
func TestDeleteNetworkWithActiveEndpoints(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
option := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
network, err := createTestNetwork(controller, bridgeNetType, "testnetwork", option, nil, nil)
assert.NilError(t, err)
ep, err := network.CreateEndpoint(context.Background(), "testep")
assert.NilError(t, err)
err = network.Delete()
var activeEndpointsError *libnetwork.ActiveEndpointsError
assert.Check(t, errors.As(err, &activeEndpointsError))
assert.Check(t, is.ErrorContains(err, "has active endpoints"))
// TODO(thaJeztah): should this be [errdefs.ErrConflict] or [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
// Done testing. Now cleanup.
err = ep.Delete(context.Background(), false)
assert.NilError(t, err)
err = network.Delete()
assert.NilError(t, err)
}
func TestNetworkConfig(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
// Verify config network cannot inherit another config network
_, err := controller.NewNetwork(context.Background(), "bridge", "config_network0", "",
libnetwork.NetworkOptionConfigOnly(),
libnetwork.NetworkOptionConfigFrom("anotherConfigNw"),
)
// TODO(thaJeztah): should this be [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, "a configuration network cannot depend on another configuration network"))
// Create supported config network
option := options.Generic{
netlabel.GenericData: map[string]string{
bridge.EnableICC: "false",
},
}
ipamV4ConfList := []*libnetwork.IpamConf{{PreferredPool: "192.168.100.0/24", SubPool: "192.168.100.128/25", Gateway: "192.168.100.1"}}
ipamV6ConfList := []*libnetwork.IpamConf{{PreferredPool: "2001:db8:abcd::/64", SubPool: "2001:db8:abcd::ef99/80", Gateway: "2001:db8:abcd::22"}}
netOptions := []libnetwork.NetworkOption{
libnetwork.NetworkOptionConfigOnly(),
libnetwork.NetworkOptionEnableIPv4(true),
libnetwork.NetworkOptionEnableIPv6(true),
libnetwork.NetworkOptionGeneric(option),
libnetwork.NetworkOptionIpam("default", "", ipamV4ConfList, ipamV6ConfList, nil),
}
configNetwork, err := controller.NewNetwork(context.Background(), bridgeNetType, "config_network0", "", netOptions...)
assert.NilError(t, err)
// Verify a config-only network cannot be created with network operator configurations
for i, opt := range []libnetwork.NetworkOption{
libnetwork.NetworkOptionInternalNetwork(),
libnetwork.NetworkOptionAttachable(true),
libnetwork.NetworkOptionIngress(true),
} {
t.Run(fmt.Sprintf("config-only-%d", i), func(t *testing.T) {
_, err = controller.NewNetwork(context.Background(), bridgeNetType, "testBR", "",
libnetwork.NetworkOptionConfigOnly(), opt)
// TODO(thaJeztah): should this be [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, "configuration network can only contain network specific fields. Network operator fields like [ ingress | internal | attachable | scope ] are not supported."))
})
}
// Verify a network cannot be created with both config-from and network specific configurations
for i, opt := range []libnetwork.NetworkOption{
libnetwork.NetworkOptionEnableIPv4(false),
libnetwork.NetworkOptionEnableIPv6(true),
libnetwork.NetworkOptionIpam("my-ipam", "", nil, nil, nil),
libnetwork.NetworkOptionIpam("", "", ipamV4ConfList, nil, nil),
libnetwork.NetworkOptionIpam("", "", nil, ipamV6ConfList, nil),
libnetwork.NetworkOptionLabels(map[string]string{"number": "two"}),
libnetwork.NetworkOptionDriverOpts(map[string]string{"com.docker.network.driver.mtu": "1600"}),
} {
t.Run(fmt.Sprintf("config-from-%d", i), func(t *testing.T) {
_, err = controller.NewNetwork(context.Background(), bridgeNetType, "testBR", "",
libnetwork.NetworkOptionConfigFrom("config_network0"), opt)
// TODO(thaJeztah): should this be [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
//nolint:dupword // ignore "Duplicate words (network) found (dupword)"
// Doing a partial match here omn the error-string here, as this produces either;
//
// user specified configurations are not supported if the network depends on a configuration network
// network driver options are not supported if the network depends on a configuration network
//
// We can consider changing this to a proper test-table.
assert.Check(t, is.ErrorContains(err, `not supported if the network depends on a configuration network`))
})
}
// Create a valid network
network, err := controller.NewNetwork(context.Background(), bridgeNetType, "testBR", "",
libnetwork.NetworkOptionConfigFrom("config_network0"))
assert.NilError(t, err)
// Verify the config network cannot be removed
err = configNetwork.Delete()
// TODO(thaJeztah): should this be [errdefs.ErrConflict] or [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, `configuration network "config_network0" is in use`))
// Delete network
err = network.Delete()
assert.NilError(t, err)
// Verify the config network can now be removed
err = configNetwork.Delete()
assert.NilError(t, err)
}
func TestUnknownNetwork(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
option := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
network, err := createTestNetwork(controller, bridgeNetType, "testnetwork", option, nil, nil)
assert.NilError(t, err)
err = network.Delete()
assert.NilError(t, err)
err = network.Delete()
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.ErrorContains(err, "unknown network testnetwork id"))
}
func TestUnknownEndpoint(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
option := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
ipamV4ConfList := []*libnetwork.IpamConf{{PreferredPool: "192.168.100.0/24"}}
network, err := createTestNetwork(controller, bridgeNetType, "testnetwork", option, ipamV4ConfList, nil)
assert.NilError(t, err)
_, err = network.CreateEndpoint(context.Background(), "")
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail with ErrInvalidName error")
assert.Check(t, is.ErrorContains(err, "invalid name:"))
ep, err := network.CreateEndpoint(context.Background(), "testep")
assert.NilError(t, err)
err = ep.Delete(context.Background(), false)
assert.NilError(t, err)
// Done testing. Now cleanup
err = network.Delete()
assert.NilError(t, err)
}
func TestNetworkEndpointsWalkers(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
// Create network 1 and add 2 endpoint: ep11, ep12
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network1",
},
}
net1, err := createTestNetwork(controller, bridgeNetType, "network1", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, net1.Delete())
}()
ep11, err := net1.CreateEndpoint(context.Background(), "ep11")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep11.Delete(context.Background(), false))
}()
ep12, err := net1.CreateEndpoint(context.Background(), "ep12")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep12.Delete(context.Background(), false))
}()
// Test list methods on net1
epList1 := net1.Endpoints()
assert.Check(t, is.Len(epList1, 2), "Endpoints() returned wrong number of elements")
// endpoint order is not guaranteed
assert.Check(t, is.Contains(epList1, ep11), "Endpoints() did not return all the expected elements")
assert.Check(t, is.Contains(epList1, ep12), "Endpoints() did not return all the expected elements")
// Test Endpoint Walk method
var epName string
var epWanted *libnetwork.Endpoint
wlk := func(ep *libnetwork.Endpoint) bool {
if ep.Name() == epName {
epWanted = ep
return true
}
return false
}
// Look for ep1 on network1
epName = "ep11"
net1.WalkEndpoints(wlk)
assert.Assert(t, epWanted != nil)
assert.Assert(t, is.Equal(epWanted, ep11))
ctx := context.TODO()
current := len(controller.Networks(ctx))
// Create network 2
netOption = options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network2",
},
}
net2, err := createTestNetwork(controller, bridgeNetType, "network2", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, net2.Delete())
}()
// Test Networks method
assert.Assert(t, is.Len(controller.Networks(ctx), current+1))
// Test Network Walk method
var netName string
var netWanted *libnetwork.Network
nwWlk := func(nw *libnetwork.Network) bool {
if nw.Name() == netName {
netWanted = nw
return true
}
return false
}
// Look for network named "network1" and "network2"
netName = "network1"
controller.WalkNetworks(nwWlk)
assert.Assert(t, netWanted != nil)
assert.Check(t, is.Equal(net1.ID(), netWanted.ID()))
netName = "network2"
controller.WalkNetworks(nwWlk)
assert.Assert(t, netWanted != nil)
assert.Check(t, is.Equal(net2.ID(), netWanted.ID()))
}
func TestDuplicateEndpoint(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
ep, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
ep2, err := n.CreateEndpoint(context.Background(), "ep1")
defer func() {
// Cleanup ep2 as well, else network cleanup might fail for failure cases
if ep2 != nil {
assert.NilError(t, ep2.Delete(context.Background(), false))
}
}()
// TODO(thaJeztah): should this be [errdefs.ErrConflict] or [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, "endpoint with name ep1 already exists in network testnetwork"))
}
func TestControllerQuery(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
// Create network 1
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network1",
},
}
net1, err := createTestNetwork(controller, bridgeNetType, "network1", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, net1.Delete())
}()
// Create network 2
netOption = options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network2",
},
}
net2, err := createTestNetwork(controller, bridgeNetType, "network2", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, net2.Delete())
}()
_, err = controller.NetworkByName("")
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument))
assert.Check(t, is.ErrorContains(err, "invalid name:"))
_, err = controller.NetworkByID("")
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument))
assert.Check(t, is.Error(err, "invalid id: id is empty"))
g, err := controller.NetworkByID("network1")
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.Error(err, "network network1 not found"))
assert.Check(t, is.Nil(g), "search network using name as ID should not yield a result")
g, err = controller.NetworkByName("network1")
assert.NilError(t, err)
assert.Assert(t, g != nil, "NetworkByName() did not find the network")
assert.Assert(t, is.Equal(g, net1), "NetworkByName() returned the wrong network")
g, err = controller.NetworkByID(net1.ID())
assert.NilError(t, err)
assert.Assert(t, is.Equal(net1.ID(), g.ID()), "NetworkByID() returned unexpected element: %v", g)
g, err = controller.NetworkByName("network2")
assert.NilError(t, err)
assert.Check(t, g != nil, "NetworkByName() did not find the network")
assert.Check(t, is.Equal(g, net2), "NetworkByName() returned the wrong network")
g, err = controller.NetworkByID(net2.ID())
assert.NilError(t, err)
assert.Check(t, is.Equal(g.ID(), net2.ID()), "NetworkByID() returned unexpected element: %v", g)
}
func TestNetworkQuery(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
// Create network 1 and add 2 endpoint: ep11, ep12
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network1",
},
}
net1, err := createTestNetwork(controller, bridgeNetType, "network1", netOption, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, net1.Delete())
}()
ep11, err := net1.CreateEndpoint(context.Background(), "ep11")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep11.Delete(context.Background(), false))
}()
ep12, err := net1.CreateEndpoint(context.Background(), "ep12")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep12.Delete(context.Background(), false))
}()
e, err := net1.EndpointByName("ep11")
assert.NilError(t, err)
assert.Check(t, is.Equal(e, ep11), "EndpointByName() returned the wrong endpoint")
_, err = net1.EndpointByName("")
assert.Check(t, is.ErrorType(err, cerrdefs.IsInvalidArgument))
assert.Check(t, is.ErrorContains(err, "invalid name:"))
e, err = net1.EndpointByName("IamNotAnEndpoint")
assert.Check(t, is.ErrorType(err, cerrdefs.IsNotFound))
assert.Check(t, is.Error(err, "endpoint IamNotAnEndpoint not found"))
assert.Check(t, is.Nil(e), "EndpointByName() returned endpoint on error")
}
const containerID = "valid_c"
func TestEndpointDeleteWithActiveContainer(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
n2, err := createTestNetwork(controller, bridgeNetType, "testnetwork2", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork2",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n2.Delete())
}()
ep, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
cnt, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
defer func() {
assert.Check(t, cnt.Delete(context.Background()))
}()
err = ep.Join(context.Background(), cnt)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Leave(context.Background(), cnt))
}()
err = ep.Delete(context.Background(), false)
var activeContainerError *libnetwork.ActiveContainerError
assert.Check(t, errors.As(err, &activeContainerError))
assert.Check(t, is.ErrorContains(err, "has active containers"))
// TODO(thaJeztah): should this be [errdefs.ErrConflict] or [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
}
func TestEndpointMultipleJoins(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testmultiple", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testmultiple",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
ep, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
sbx1, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"),
)
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx1.Delete(context.Background()))
}()
sbx2, err := controller.NewSandbox(context.Background(), "c2")
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx2.Delete(context.Background()))
}()
err = ep.Join(context.Background(), sbx1)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Leave(context.Background(), sbx1))
}()
err = ep.Join(context.Background(), sbx2)
// TODO(thaJeztah): should this be [errdefs.ErrConflict] or [errdefs.ErrInvalidParameter]?
assert.Check(t, is.ErrorType(err, cerrdefs.IsPermissionDenied))
assert.Check(t, is.Error(err, "another container is attached to the same network endpoint"))
}
func TestLeaveAll(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
// If this goes through, it means cnt.Delete() effectively detached from all the endpoints
assert.Check(t, n.Delete())
}()
n2, err := createTestNetwork(controller, bridgeNetType, "testnetwork2", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork2",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n2.Delete())
}()
ep1, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
ep2, err := n2.CreateEndpoint(context.Background(), "ep2")
assert.NilError(t, err)
cnt, err := controller.NewSandbox(context.Background(), "leaveall")
assert.NilError(t, err)
err = ep1.Join(context.Background(), cnt)
assert.NilError(t, err, "Failed to join ep1")
err = ep2.Join(context.Background(), cnt)
assert.NilError(t, err, "Failed to join ep2")
err = cnt.Delete(context.Background())
assert.NilError(t, err)
}
func TestContainerInvalidLeave(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
ep, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
cnt, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
defer func() {
assert.Check(t, cnt.Delete(context.Background()))
}()
err = ep.Leave(context.Background(), cnt)
assert.Assert(t, is.ErrorType(err, cerrdefs.IsPermissionDenied), "Expected to fail leave from an endpoint which has no active join")
assert.Check(t, is.Error(err, "cannot leave endpoint with no attached sandbox"))
err = ep.Leave(context.Background(), nil)
assert.Assert(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail leave with a nil Sandbox")
// FIXME(thaJeztah): this error includes the raw data of the sandbox (as `<nil>`), which is not very informative
assert.Check(t, is.Error(err, "invalid Sandbox passed to endpoint leave: <nil>"))
fsbx := &libnetwork.Sandbox{}
err = ep.Leave(context.Background(), fsbx)
assert.Assert(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail leave with invalid Sandbox")
//nolint:dupword // Ignore "Duplicate words (map[]) found (dupword)"
// FIXME(thaJeztah): this error includes the raw data of the sandbox, which is not very human-readable or informative;
// invalid Sandbox passed to endpoint leave: &{ {{ []} { [] [] []} map[] false false []} [] <nil> <nil> <nil> {{{} 0} {0 0}} [] map[] map[] <nil> 0 false false false false false [] {0 0} {0 0}}
assert.Check(t, is.ErrorContains(err, "invalid Sandbox passed to endpoint leave"))
}
func TestEndpointUpdateParent(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
ep1, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
ep2, err := n.CreateEndpoint(context.Background(), "ep2")
assert.NilError(t, err)
sbx1, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx1.Delete(context.Background()))
}()
sbx2, err := controller.NewSandbox(context.Background(), "c2",
libnetwork.OptionHostname("test2"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionHostsPath("/var/lib/docker/test_network/container2/hosts"),
libnetwork.OptionExtraHost("web", "192.168.0.2"))
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx2.Delete(context.Background()))
}()
err = ep1.Join(context.Background(), sbx1)
assert.NilError(t, err)
err = ep2.Join(context.Background(), sbx2)
assert.NilError(t, err)
}
func TestInvalidRemoteDriver(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
defer server.Close()
mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", plugins.VersionMimetype)
_, _ = fmt.Fprintln(w, `{"Implements": ["InvalidDriver"]}`)
})
err := os.MkdirAll(specPath, 0o755)
assert.NilError(t, err)
defer func() {
assert.Check(t, os.RemoveAll(specPath))
}()
err = os.WriteFile(filepath.Join(specPath, "invalid-network-driver.spec"), []byte(server.URL), 0o644)
assert.NilError(t, err)
ctrlr, err := libnetwork.New(context.Background(), config.OptionDataDir(t.TempDir()))
assert.NilError(t, err)
defer ctrlr.Stop()
_, err = ctrlr.NewNetwork(context.Background(), "invalid-network-driver", "dummy", "",
libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
assert.Check(t, is.ErrorIs(err, plugins.ErrNotImplements))
}
func TestValidRemoteDriver(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
defer server.Close()
mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", plugins.VersionMimetype)
_, _ = fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
})
mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", plugins.VersionMimetype)
_, _ = fmt.Fprintf(w, `{"Scope":"local"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", plugins.VersionMimetype)
_, _ = fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", plugins.VersionMimetype)
_, _ = fmt.Fprintf(w, "null")
})
err := os.MkdirAll(specPath, 0o755)
assert.NilError(t, err)
defer func() {
assert.Check(t, os.RemoveAll(specPath))
}()
err = os.WriteFile(filepath.Join(specPath, "valid-network-driver.spec"), []byte(server.URL), 0o644)
assert.NilError(t, err)
controller := newController(t)
n, err := controller.NewNetwork(context.Background(), "valid-network-driver", "dummy", "",
libnetwork.NetworkOptionGeneric(getEmptyGenericOption()))
if err != nil {
// Only fail if we could not find the plugin driver
if cerrdefs.IsNotFound(err) {
t.Fatal(err)
}
return
}
defer func() {
assert.Check(t, n.Delete())
}()
}
func makeTesthostNetwork(t *testing.T, c *libnetwork.Controller) *libnetwork.Network {
t.Helper()
n, err := createTestNetwork(c, "host", "testhost", options.Generic{}, nil, nil)
assert.NilError(t, err)
return n
}
func makeTestIPv6Network(t *testing.T, c *libnetwork.Controller) *libnetwork.Network {
t.Helper()
netOptions := options.Generic{
netlabel.EnableIPv4: true,
netlabel.EnableIPv6: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}
ipamV6ConfList := []*libnetwork.IpamConf{
{PreferredPool: "fd81:fb6e:38ba:abcd::/64", Gateway: "fd81:fb6e:38ba:abcd::9"},
}
n, err := createTestNetwork(c,
"bridge",
"testnetwork",
netOptions,
nil,
ipamV6ConfList,
)
assert.NilError(t, err)
return n
}
func TestHost(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
sbx1, err := controller.NewSandbox(context.Background(), "host_c1",
libnetwork.OptionHostname("test1"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"),
libnetwork.OptionUseDefaultSandbox())
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx1.Delete(context.Background()))
}()
sbx2, err := controller.NewSandbox(context.Background(), "host_c2",
libnetwork.OptionHostname("test2"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"),
libnetwork.OptionUseDefaultSandbox())
assert.NilError(t, err)
defer func() {
assert.Check(t, sbx2.Delete(context.Background()))
}()
network := makeTesthostNetwork(t, controller)
ep1, err := network.CreateEndpoint(context.Background(), "testep1")
assert.NilError(t, err)
err = ep1.Join(context.Background(), sbx1)
assert.NilError(t, err)
ep2, err := network.CreateEndpoint(context.Background(), "testep2")
assert.NilError(t, err)
err = ep2.Join(context.Background(), sbx2)
assert.NilError(t, err)
err = ep1.Leave(context.Background(), sbx1)
assert.NilError(t, err)
err = ep2.Leave(context.Background(), sbx2)
assert.NilError(t, err)
err = ep1.Delete(context.Background(), false)
assert.NilError(t, err)
err = ep2.Delete(context.Background(), false)
assert.NilError(t, err)
// Try to create another host endpoint and join/leave that.
cnt3, err := controller.NewSandbox(context.Background(), "host_c3",
libnetwork.OptionHostname("test3"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"),
libnetwork.OptionUseDefaultSandbox())
assert.NilError(t, err)
defer func() {
assert.Check(t, cnt3.Delete(context.Background()))
}()
ep3, err := network.CreateEndpoint(context.Background(), "testep3")
assert.NilError(t, err)
err = ep3.Join(context.Background(), sbx2)
assert.NilError(t, err)
err = ep3.Leave(context.Background(), sbx2)
assert.NilError(t, err)
err = ep3.Delete(context.Background(), false)
assert.NilError(t, err)
}
func checkSandbox(t *testing.T, info libnetwork.EndpointInfo) {
key := info.Sandbox().Key()
sbNs, err := netns.GetFromPath(key)
assert.NilError(t, err, "Failed to get network namespace path %q", key)
defer func() {
assert.Check(t, sbNs.Close())
}()
nh, err := nlwrap.NewHandleAt(sbNs)
assert.NilError(t, err)
_, err = nh.LinkByName("eth0")
assert.NilError(t, err, "Could not find the interface eth0 inside the sandbox")
_, err = nh.LinkByName("eth1")
assert.NilError(t, err, "Could not find the interface eth1 inside the sandbox")
}
func TestEndpointJoin(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
// Create network 1 and add 2 endpoint: ep11, ep12
netOption := options.Generic{
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork1",
bridge.EnableICC: "true",
bridge.EnableIPMasquerade: "true",
},
}
ipamV6ConfList := []*libnetwork.IpamConf{{PreferredPool: "fe90::/64", Gateway: "fe90::22"}}
n1, err := controller.NewNetwork(context.Background(), bridgeNetType, "testnetwork1", "",
libnetwork.NetworkOptionGeneric(netOption),
libnetwork.NetworkOptionEnableIPv4(true),
libnetwork.NetworkOptionEnableIPv6(true),
libnetwork.NetworkOptionIpam(defaultipam.DriverName, "", nil, ipamV6ConfList, nil),
)
assert.NilError(t, err)
defer func() {
assert.Check(t, n1.Delete())
}()
ep1, err := n1.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep1.Delete(context.Background(), false))
}()
// Validate if ep.Info() only gives me IP address info and not names and gateway during CreateEndpoint()
info := ep1.Info()
iface := info.Iface()
if iface.Address() != nil {
assert.Check(t, iface.Address().IP.To4() != nil, "Invalid IP address returned: %v", iface.Address())
}
if iface.AddressIPv6() != nil {
// Should be nil if it's an IPv6 address;https://github.com/moby/moby/pull/49329#discussion_r1925981233
assert.Check(t, iface.AddressIPv6().IP.To4() == nil, "Invalid IPv6 address returned: %v", iface.AddressIPv6())
}
assert.Check(t, is.Len(info.Gateway(), 0), "Expected empty gateway for an empty endpoint. Instead found a gateway: %v", info.Gateway())
assert.Check(t, is.Len(info.GatewayIPv6(), 0), "Expected empty gateway for an empty ipv6 endpoint. Instead found a gateway: %v", info.GatewayIPv6())
assert.Check(t, is.Nil(info.Sandbox()), "Expected an empty sandbox key for an empty endpoint")
// test invalid joins
err = ep1.Join(context.Background(), nil)
assert.Assert(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail join with nil Sandbox")
// FIXME(thaJeztah): this error includes the raw data of the sandbox (as `<nil>`), which is not very informative
assert.Check(t, is.Error(err, "invalid Sandbox passed to endpoint join: <nil>"))
fsbx := &libnetwork.Sandbox{}
err = ep1.Join(context.Background(), fsbx)
assert.Assert(t, is.ErrorType(err, cerrdefs.IsInvalidArgument), "Expected to fail join with invalid Sandbox")
//nolint:dupword // ignore "Duplicate words (map[]) found (dupword)"
// FIXME(thaJeztah): this error includes the raw data of the sandbox, which is not very human-readable or informative;
// invalid Sandbox passed to endpoint join: &{ {{ []} { [] [] []} map[] false false []} [] <nil> <nil> <nil> {{{} 0} {0 0}} [] map[] map[] <nil> 0 false false false false false [] {0 0} {0 0}}
assert.Check(t, is.ErrorContains(err, "invalid Sandbox passed to endpoint join"))
sb, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
defer func() {
assert.Check(t, sb.Delete(context.Background()))
}()
err = ep1.Join(context.Background(), sb)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep1.Leave(context.Background(), sb))
}()
// Validate if ep.Info() only gives valid gateway and sandbox key after has container has joined.
info = ep1.Info()
assert.Check(t, len(info.Gateway()) > 0, "Expected a valid gateway for a joined endpoint")
assert.Check(t, len(info.GatewayIPv6()) > 0, "Expected a valid ipv6 gateway for a joined endpoint")
assert.Check(t, info.Sandbox() != nil, "Expected an non-empty sandbox key for a joined endpoint")
// Check endpoint provided container information
assert.Check(t, is.Equal(sb.Key(), ep1.Info().Sandbox().Key()), "Endpoint Info returned unexpected sandbox key: %s", sb.Key())
// Attempt retrieval of endpoint interfaces statistics
stats, err := sb.Statistics()
assert.NilError(t, err)
_, ok := stats["eth0"]
assert.Assert(t, ok, "Did not find eth0 statistics")
// Now test the container joining another network
n2, err := createTestNetwork(controller, bridgeNetType, "testnetwork2",
options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork2",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n2.Delete())
}()
ep2, err := n2.CreateEndpoint(context.Background(), "ep2")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep2.Delete(context.Background(), false))
}()
err = ep2.Join(context.Background(), sb)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep2.Leave(context.Background(), sb))
}()
assert.Check(t, is.Equal(ep1.Info().Sandbox().Key(), ep2.Info().Sandbox().Key()), "ep1 and ep2 returned different container sandbox key")
checkSandbox(t, info)
}
func TestExternalKey(t *testing.T) {
externalKeyTest(t, false)
}
func externalKeyTest(t *testing.T, reexec bool) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
n, err := createTestNetwork(controller, bridgeNetType, "testnetwork", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n.Delete())
}()
n2, err := createTestNetwork(controller, bridgeNetType, "testnetwork2", options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork2",
},
}, nil, nil)
assert.NilError(t, err)
defer func() {
assert.Check(t, n2.Delete())
}()
ep, err := n.CreateEndpoint(context.Background(), "ep1")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
ep2, err := n2.CreateEndpoint(context.Background(), "ep2")
assert.NilError(t, err)
defer func() {
assert.Check(t, ep2.Delete(context.Background(), false))
}()
cnt, err := controller.NewSandbox(context.Background(), containerID,
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("example.com"),
libnetwork.OptionUseExternalKey(),
libnetwork.OptionExtraHost("web", "192.168.0.1"))
assert.NilError(t, err)
defer func() {
assert.Check(t, cnt.Delete(context.Background()))
}()
// Join endpoint to sandbox before SetKey
err = ep.Join(context.Background(), cnt)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Leave(context.Background(), cnt))
}()
sbox := ep.Info().Sandbox()
assert.Assert(t, sbox != nil, "Expected to have a valid Sandbox")
if reexec {
err := reexecSetKey("this-must-fail", containerID, controller.ID())
if err == nil {
t.Fatalf("libnetwork-setkey must fail if the corresponding namespace is not created")
}
} else {
// Setting an non-existing key (namespace) must fail
if err := sbox.SetKey(context.Background(), "this-must-fail"); err == nil {
t.Fatalf("Setkey must fail if the corresponding namespace is not created")
}
}
// Create a new OS sandbox using the osl API before using it in SetKey
extOsBox, err := osl.NewSandbox("ValidKey", true, false)
assert.NilError(t, err, "Failed to create new osl sandbox")
defer func() {
if err := extOsBox.Destroy(); err != nil {
log.G(context.TODO()).Warnf("Failed to remove os sandbox: %v", err)
}
}()
if reexec {
err = reexecSetKey("ValidKey", containerID, controller.ID())
assert.NilError(t, err, "libnetwork-setkey failed")
} else {
err = sbox.SetKey(context.Background(), "ValidKey")
assert.NilError(t, err, "setkey failed")
}
// Join endpoint to sandbox after SetKey
err = ep2.Join(context.Background(), sbox)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep2.Leave(context.Background(), sbox))
}()
assert.Assert(t, is.Equal(ep.Info().Sandbox().Key(), ep2.Info().Sandbox().Key()), "ep1 and ep2 returned different container sandbox key")
checkSandbox(t, ep.Info())
}
func reexecSetKey(key string, containerID string, controllerID string) error {
type libcontainerState struct {
NamespacePaths map[string]string
}
var (
state libcontainerState
b []byte
err error
)
state.NamespacePaths = make(map[string]string)
state.NamespacePaths["NEWNET"] = key
if b, err = json.Marshal(state); err != nil {
return err
}
cmd := &exec.Cmd{
Path: reexec.Self(),
Args: append([]string{"libnetwork-setkey"}, containerID, controllerID),
Stdin: strings.NewReader(string(b)),
Stdout: os.Stdout,
Stderr: os.Stderr,
}
return cmd.Run()
}
func TestResolvConf(t *testing.T) {
tmpDir := t.TempDir()
originResolvConfPath := filepath.Join(tmpDir, "origin_resolv.conf")
resolvConfPath := filepath.Join(tmpDir, "resolv.conf")
// Strip comments that end in a newline (a comment with no newline at the end
// of the file will not be stripped).
stripCommentsRE := regexp.MustCompile(`(?m)^#.*\n`)
testcases := []struct {
name string
makeNet func(t *testing.T, c *libnetwork.Controller) *libnetwork.Network
delNet bool
epOpts []libnetwork.EndpointOption
sbOpts []libnetwork.SandboxOption
originResolvConf string
expResolvConf string
}{
{
name: "IPv6 network",
makeNet: makeTestIPv6Network,
delNet: true,
originResolvConf: "search pommesfrites.fr\nnameserver 12.34.56.78\nnameserver 2001:4860:4860::8888\n",
expResolvConf: "nameserver 127.0.0.11\nsearch pommesfrites.fr\noptions ndots:0",
},
{
name: "host network",
makeNet: makeTesthostNetwork,
epOpts: []libnetwork.EndpointOption{libnetwork.CreateOptionDisableResolution()},
sbOpts: []libnetwork.SandboxOption{libnetwork.OptionUseDefaultSandbox()},
originResolvConf: "search localhost.net\nnameserver 127.0.0.1\nnameserver 2001:4860:4860::8888\n",
expResolvConf: "nameserver 127.0.0.1\nnameserver 2001:4860:4860::8888\nsearch localhost.net",
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
c := newController(t)
err := os.WriteFile(originResolvConfPath, []byte(tc.originResolvConf), 0o644)
assert.NilError(t, err)
n := tc.makeNet(t, c)
if tc.delNet {
defer func() {
assert.Check(t, n.Delete())
}()
}
sbOpts := append(tc.sbOpts,
libnetwork.OptionResolvConfPath(resolvConfPath),
libnetwork.OptionOriginResolvConfPath(originResolvConfPath),
)
sb, err := c.NewSandbox(context.Background(), containerID, sbOpts...)
assert.NilError(t, err)
defer func() {
assert.Check(t, sb.Delete(context.Background()))
}()
ep, err := n.CreateEndpoint(context.Background(), "ep", tc.epOpts...)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Delete(context.Background(), false))
}()
err = ep.Join(context.Background(), sb)
assert.NilError(t, err)
defer func() {
assert.Check(t, ep.Leave(context.Background(), sb))
}()
finfo, err := os.Stat(resolvConfPath)
assert.NilError(t, err)
expFMode := (os.FileMode)(0o644)
assert.Check(t, is.Equal(finfo.Mode().String(), expFMode.String()))
content, err := os.ReadFile(resolvConfPath)
assert.NilError(t, err)
actual := stripCommentsRE.ReplaceAllString(string(content), "")
actual = strings.TrimSpace(actual)
assert.Check(t, is.Equal(actual, tc.expResolvConf))
})
}
}
type parallelTester struct {
osctx *netnsutils.OSContext
controller *libnetwork.Controller
net1, net2 *libnetwork.Network
iterCnt int
}
func (pt parallelTester) Do(t *testing.T, thrNumber int) error {
teardown, err := pt.osctx.Set()
if err != nil {
return err
}
defer teardown(t)
var ep *libnetwork.Endpoint
if thrNumber == 1 {
ep, err = pt.net1.EndpointByName(fmt.Sprintf("pep%d", thrNumber))
} else {
ep, err = pt.net2.EndpointByName(fmt.Sprintf("pep%d", thrNumber))
}
if err != nil {
return errors.WithStack(err)
}
if ep == nil {
return errors.New("got nil ep with no error")
}
cid := fmt.Sprintf("%drace", thrNumber)
sb, err := pt.controller.GetSandbox(cid)
if err != nil {
return err
}
for i := 0; i < pt.iterCnt; i++ {
if err := ep.Join(context.Background(), sb); err != nil {
if !cerrdefs.IsPermissionDenied(err) {
return errors.Wrapf(err, "thread %d", thrNumber)
}
}
if err := ep.Leave(context.Background(), sb); err != nil {
if !cerrdefs.IsPermissionDenied(err) {
return errors.Wrapf(err, "thread %d", thrNumber)
}
}
}
if err := errors.WithStack(sb.Delete(context.Background())); err != nil {
return err
}
return errors.WithStack(ep.Delete(context.Background(), false))
}
func TestParallel(t *testing.T) {
const (
first = 1
last = 3
numThreads = last - first + 1
iterCnt = 25
)
osctx := netnsutils.SetupTestOSContextEx(t)
defer osctx.Cleanup(t)
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "network",
},
}
net1 := makeTesthostNetwork(t, controller)
defer net1.Delete()
net2, err := createTestNetwork(controller, "bridge", "network2", netOption, nil, nil)
assert.NilError(t, err)
defer net2.Delete()
_, err = net1.CreateEndpoint(context.Background(), "pep1")
assert.NilError(t, err)
_, err = net2.CreateEndpoint(context.Background(), "pep2")
assert.NilError(t, err)
_, err = net2.CreateEndpoint(context.Background(), "pep3")
assert.NilError(t, err)
sboxes := make([]*libnetwork.Sandbox, numThreads)
sboxes[first-1], err = controller.NewSandbox(context.Background(), fmt.Sprintf("%drace", first), libnetwork.OptionUseDefaultSandbox())
assert.NilError(t, err)
for thd := first + 1; thd <= last; thd++ {
sboxes[thd-1], err = controller.NewSandbox(context.Background(), fmt.Sprintf("%drace", thd))
assert.NilError(t, err)
}
pt := parallelTester{
osctx: osctx,
controller: controller,
net1: net1,
net2: net2,
iterCnt: iterCnt,
}
var eg errgroup.Group
for i := first; i <= last; i++ {
eg.Go(func() error { return pt.Do(t, i) })
}
err = eg.Wait()
assert.NilError(t, err)
}
func TestBridge(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
netOption := options.Generic{
netlabel.EnableIPv4: true,
netlabel.EnableIPv6: true,
netlabel.GenericData: map[string]string{
bridge.BridgeName: "testnetwork",
bridge.EnableICC: "true",
bridge.EnableIPMasquerade: "true",
},
}
ipamV4ConfList := []*libnetwork.IpamConf{{PreferredPool: "192.168.100.0/24", Gateway: "192.168.100.1"}}
ipamV6ConfList := []*libnetwork.IpamConf{{PreferredPool: "fe90::/64", Gateway: "fe90::22"}}
network, err := createTestNetwork(controller, bridgeNetType, "testnetwork", netOption, ipamV4ConfList, ipamV6ConfList)
assert.NilError(t, err)
defer func() {
assert.Check(t, network.Delete())
}()
ep, err := network.CreateEndpoint(context.Background(), "testep")
assert.NilError(t, err)
sb, err := controller.NewSandbox(context.Background(), containerID, libnetwork.OptionPortMapping(getPortMapping()))
assert.NilError(t, err)
defer func() {
assert.Check(t, sb.Delete(context.Background()))
}()
err = ep.Join(context.Background(), sb)
assert.NilError(t, err)
epInfo, err := ep.DriverInfo()
assert.NilError(t, err)
pmd, ok := epInfo[netlabel.PortMap]
assert.Assert(t, ok, "Could not find expected info in endpoint data")
pm, ok := pmd.([]types.PortBinding)
assert.Assert(t, ok, "Unexpected format for port mapping in endpoint operational data")
expectedLen := 10
if !isV6Listenable() {
expectedLen = 5
}
assert.Check(t, is.Len(pm, expectedLen), "Incomplete data for port mapping in endpoint operational data")
}
var (
v6ListenableCached bool
v6ListenableOnce sync.Once
)
// This is copied from the bridge driver package b/c the bridge driver is not platform agnostic.
func isV6Listenable() bool {
v6ListenableOnce.Do(func() {
ln, err := net.Listen("tcp6", "[::1]:0")
if err != nil {
// When the kernel was booted with `ipv6.disable=1`,
// we get err "listen tcp6 [::1]:0: socket: address family not supported by protocol"
// https://github.com/moby/moby/issues/42288
log.G(context.TODO()).Debugf("port_mapping: v6Listenable=false (%v)", err)
} else {
v6ListenableCached = true
_ = ln.Close()
}
})
return v6ListenableCached
}
func TestBridgeRequiresIPAM(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
_, err := controller.NewNetwork(context.Background(), bridgeNetType, "testnetwork", "",
libnetwork.NetworkOptionIpam(null.DriverName, "", nil, nil, nil),
)
assert.Check(t, is.ErrorContains(err, "IPv4 or IPv6 must be enabled"))
}
func TestNullIpam(t *testing.T) {
defer netnsutils.SetupTestOSContext(t)()
controller := newController(t)
tests := []struct {
networkType string
}{
{networkType: bridgeNetType},
{networkType: "macvlan"},
{networkType: "ipvlan"},
}
for _, tc := range tests {
t.Run(tc.networkType, func(t *testing.T) {
_, err := controller.NewNetwork(context.Background(), tc.networkType, "tnet1-"+tc.networkType, "",
libnetwork.NetworkOptionEnableIPv4(true),
libnetwork.NetworkOptionIpam(null.DriverName, "", nil, nil, nil),
)
assert.Check(t, is.ErrorContains(err, "ipv4 pool is empty"))
_, err = controller.NewNetwork(context.Background(), tc.networkType, "tnet2-"+tc.networkType, "",
libnetwork.NetworkOptionEnableIPv6(true),
libnetwork.NetworkOptionIpam(null.DriverName, "", nil, nil, nil),
)
assert.Check(t, is.ErrorContains(err, "ipv6 pool is empty"))
})
}
}
|