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
|
package bridge
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
"testing"
"time"
containertypes "github.com/docker/docker/api/types/container"
networktypes "github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/versions"
ctr "github.com/docker/docker/integration/internal/container"
"github.com/docker/docker/integration/internal/network"
"github.com/docker/docker/internal/nlwrap"
"github.com/docker/docker/internal/testutils/networking"
"github.com/docker/docker/libnetwork/drivers/bridge"
"github.com/docker/docker/libnetwork/netlabel"
"github.com/docker/docker/testutil"
"github.com/docker/docker/testutil/daemon"
"github.com/docker/go-connections/nat"
"github.com/vishvananda/netlink"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/icmd"
"gotest.tools/v3/skip"
)
func TestCreateWithMultiNetworks(t *testing.T) {
skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.44"), "requires API v1.44")
ctx := setupTest(t)
apiClient := testEnv.APIClient()
network.CreateNoError(ctx, t, apiClient, "testnet1")
defer network.RemoveNoError(ctx, t, apiClient, "testnet1")
network.CreateNoError(ctx, t, apiClient, "testnet2")
defer network.RemoveNoError(ctx, t, apiClient, "testnet2")
attachCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
res := ctr.RunAttach(attachCtx, t, apiClient,
ctr.WithCmd("ip", "-o", "-4", "addr", "show"),
ctr.WithNetworkMode("testnet1"),
ctr.WithEndpointSettings("testnet1", &networktypes.EndpointSettings{}),
ctr.WithEndpointSettings("testnet2", &networktypes.EndpointSettings{}))
assert.Equal(t, res.ExitCode, 0)
assert.Equal(t, res.Stderr.String(), "")
// Only interfaces with an IPv4 address are printed by iproute2 when flag -4 is specified. Here, we should have two
// interfaces for testnet1 and testnet2, plus lo.
ifacesWithAddress := strings.Count(res.Stdout.String(), "\n")
assert.Equal(t, ifacesWithAddress, 3)
}
func TestCreateWithIPv6DefaultsToULAPrefix(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
const nwName = "testnetula"
network.CreateNoError(ctx, t, apiClient, nwName, network.WithIPv6())
defer network.RemoveNoError(ctx, t, apiClient, nwName)
nw, err := apiClient.NetworkInspect(ctx, "testnetula", networktypes.InspectOptions{})
assert.NilError(t, err)
for _, ipam := range nw.IPAM.Config {
ipr := netip.MustParsePrefix(ipam.Subnet)
if netip.MustParsePrefix("fd00::/8").Overlaps(ipr) {
return
}
}
t.Fatalf("Network %s has no ULA prefix, expected one.", nwName)
}
func TestCreateWithIPv6WithoutEnableIPv6Flag(t *testing.T) {
ctx := setupTest(t)
d := daemon.New(t)
d.StartWithBusybox(ctx, t, "-D", "--default-network-opt=bridge=com.docker.network.enable_ipv6=true")
defer d.Stop(t)
apiClient := d.NewClientT(t)
defer apiClient.Close()
const nwName = "testnetula"
network.CreateNoError(ctx, t, apiClient, nwName)
defer network.RemoveNoError(ctx, t, apiClient, nwName)
nw, err := apiClient.NetworkInspect(ctx, "testnetula", networktypes.InspectOptions{})
assert.NilError(t, err)
for _, ipam := range nw.IPAM.Config {
ipr := netip.MustParsePrefix(ipam.Subnet)
if netip.MustParsePrefix("fd00::/8").Overlaps(ipr) {
return
}
}
t.Fatalf("Network %s has no ULA prefix, expected one.", nwName)
}
// TestDefaultIPvOptOverride checks that when default-network-opts set enable_ipv4 or
// enable_ipv6, and those values are overridden for a network, the default option
// values don't show up in network inspect output. (Because it's confusing if the
// default shows up when it's been overridden with a different value.)
func TestDefaultIPvOptOverride(t *testing.T) {
ctx := setupTest(t)
d := daemon.New(t)
const opt4 = "false"
const opt6 = "true"
d.StartWithBusybox(ctx, t,
"--default-network-opt=bridge=com.docker.network.enable_ipv4="+opt4,
"--default-network-opt=bridge=com.docker.network.enable_ipv6="+opt6,
)
defer d.Stop(t)
c := d.NewClientT(t)
t.Run("TestDefaultIPvOptOverride", func(t *testing.T) {
for _, override4 := range []bool{false, true} {
for _, override6 := range []bool{false, true} {
t.Run(fmt.Sprintf("override4=%v,override6=%v", override4, override6), func(t *testing.T) {
t.Parallel()
netName := fmt.Sprintf("tdioo-%v-%v", override4, override6)
var nopts []func(*networktypes.CreateOptions)
if override4 {
nopts = append(nopts, network.WithIPv4(true))
}
if override6 {
nopts = append(nopts, network.WithIPv6())
}
network.CreateNoError(ctx, t, c, netName, nopts...)
defer network.RemoveNoError(ctx, t, c, netName)
insp, err := c.NetworkInspect(ctx, netName, networktypes.InspectOptions{})
assert.NilError(t, err)
t.Log("override4", override4, "override6", override6, "->", insp.Options)
gotOpt4, have4 := insp.Options[netlabel.EnableIPv4]
assert.Check(t, is.Equal(have4, !override4))
assert.Check(t, is.Equal(insp.EnableIPv4, override4))
if have4 {
assert.Check(t, is.Equal(gotOpt4, opt4))
}
gotOpt6, have6 := insp.Options[netlabel.EnableIPv6]
assert.Check(t, is.Equal(have6, !override6))
assert.Check(t, is.Equal(insp.EnableIPv6, true))
if have6 {
assert.Check(t, is.Equal(gotOpt6, opt6))
}
})
}
}
})
}
// Check that it's possible to create IPv6 networks with a 64-bit ip-range,
// in 64-bit and bigger subnets, with and without a gateway.
func Test64BitIPRange(t *testing.T) {
ctx := setupTest(t)
c := testEnv.APIClient()
type kv struct{ k, v string }
subnets := []kv{
{"64-bit-subnet", "fd2e:b68c:ce26::/64"},
{"56-bit-subnet", "fd2e:b68c:ce26::/56"},
}
ipRanges := []kv{
{"no-range", ""},
{"64-bit-range", "fd2e:b68c:ce26::/64"},
}
gateways := []kv{
{"no-gateway", ""},
{"with-gateway", "fd2e:b68c:ce26::1"},
}
for _, sn := range subnets {
for _, ipr := range ipRanges {
for _, gw := range gateways {
ipamSetter := network.WithIPAMRange(sn.v, ipr.v, gw.v)
t.Run(sn.k+"/"+ipr.k+"/"+gw.k, func(t *testing.T) {
ctx := testutil.StartSpan(ctx, t)
const netName = "test64br"
network.CreateNoError(ctx, t, c, netName, network.WithIPv6(), ipamSetter)
defer network.RemoveNoError(ctx, t, c, netName)
})
}
}
}
}
// Demonstrate a limitation of the IP address allocator, it can't
// allocate the last address in range that ends on a 64-bit boundary.
func TestIPRangeAt64BitLimit(t *testing.T) {
ctx := setupTest(t)
c := testEnv.APIClient()
tests := []struct {
name string
subnet string
ipRange string
}{
{
name: "ipRange before end of 64-bit subnet",
subnet: "fda9:8d04:086e::/64",
ipRange: "fda9:8d04:086e::ffff:ffff:ffff:ff0e/127",
},
{
name: "ipRange at end of 64-bit subnet",
subnet: "fda9:8d04:086e::/64",
ipRange: "fda9:8d04:086e::ffff:ffff:ffff:fffe/127",
},
{
name: "ipRange at 64-bit boundary inside 56-bit subnet",
subnet: "fda9:8d04:086e::/56",
ipRange: "fda9:8d04:086e:aa:ffff:ffff:ffff:fffe/127",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := testutil.StartSpan(ctx, t)
const netName = "test64bl"
network.CreateNoError(ctx, t, c, netName,
network.WithIPv6(),
network.WithIPAMRange(tc.subnet, tc.ipRange, ""),
)
defer network.RemoveNoError(ctx, t, c, netName)
id := ctr.Create(ctx, t, c, ctr.WithNetworkMode(netName))
defer c.ContainerRemove(ctx, id, containertypes.RemoveOptions{Force: true})
err := c.ContainerStart(ctx, id, containertypes.StartOptions{})
assert.NilError(t, err)
})
}
}
// TestFilterForwardPolicy tests that, if the daemon enables IP forwarding on the
// host, it also sets the iptables filter-FORWARD policy to DROP (unless it's
// told not to).
func TestFilterForwardPolicy(t *testing.T) {
skip.If(t, testEnv.IsRootless, "rootless has its own netns")
skip.If(t, networking.FirewalldRunning(), "can't use firewalld in host netns to add rules in L3Segment")
ctx := setupTest(t)
// Set up a netns for each test to avoid sysctl and iptables pollution.
addr4 := netip.MustParseAddr("192.168.125.1")
addr6 := netip.MustParseAddr("fd76:c828:41f9::1")
l3 := networking.NewL3Segment(t, "test-ffp",
netip.PrefixFrom(addr4, 24),
netip.PrefixFrom(addr6, 64),
)
t.Cleanup(func() { l3.Destroy(t) })
tests := []struct {
name string
initForwarding string
daemonArgs []string
expForwarding string
expPolicy string
}{
{
name: "enable forwarding",
initForwarding: "0",
expForwarding: "1",
expPolicy: "DROP",
},
{
name: "forwarding already enabled",
initForwarding: "1",
expForwarding: "1",
expPolicy: "ACCEPT",
},
{
name: "no drop",
initForwarding: "0",
daemonArgs: []string{"--ip-forward-no-drop"},
expForwarding: "1",
expPolicy: "ACCEPT",
},
{
name: "no forwarding",
initForwarding: "0",
daemonArgs: []string{"--ip-forward=false"},
expForwarding: "0",
expPolicy: "ACCEPT",
},
}
for i, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := testutil.StartSpan(ctx, t)
// Create a netns for this test.
addr4, addr6 = addr4.Next(), addr6.Next()
hostname := fmt.Sprintf("docker%d", i)
l3.AddHost(t, hostname, hostname+"-host", "eth0",
netip.PrefixFrom(addr4, 24),
netip.PrefixFrom(addr6, 64),
)
host := l3.Hosts[hostname]
getFwdPolicy := func(usingNftables bool, fam string) string {
t.Helper()
if usingNftables {
out := host.MustRun(t, "nft", "list chain "+fam+" docker-bridges filter-FORWARD")
if strings.Contains(out, "policy accept") {
return "ACCEPT"
}
if strings.Contains(out, "policy drop") {
return "DROP"
}
t.Fatalf("Failed to determine nftables filter-FORWARD policy: %s", out)
return ""
} else {
cmd := fam + "tables"
out := host.MustRun(t, cmd, "-S", "FORWARD")
if strings.HasPrefix(out, "-P FORWARD ACCEPT") {
return "ACCEPT"
}
if strings.HasPrefix(out, "-P FORWARD DROP") {
return "DROP"
}
t.Fatalf("Failed to determine %s FORWARD policy: %s", cmd, out)
return ""
}
}
type sysctls struct{ v4, v6def, v6all string }
getSysctls := func() sysctls {
t.Helper()
return sysctls{
host.MustRun(t, "sysctl", "-n", "net.ipv4.ip_forward")[:1],
host.MustRun(t, "sysctl", "-n", "net.ipv6.conf.default.forwarding")[:1],
host.MustRun(t, "sysctl", "-n", "net.ipv6.conf.all.forwarding")[:1],
}
}
// Initial settings for IP forwarding params.
host.MustRun(t, "sysctl", "-w", "net.ipv4.ip_forward="+tc.initForwarding)
host.MustRun(t, "sysctl", "-w", "net.ipv6.conf.all.forwarding="+tc.initForwarding)
// Start the daemon in its own network namespace.
var d *daemon.Daemon
host.Do(t, func() {
// Run without OTel because there's no routing from this netns for it - which
// means the daemon doesn't shut down cleanly, causing the test to fail.
d = daemon.New(t, daemon.WithEnvVars("OTEL_EXPORTER_OTLP_ENDPOINT="))
d.StartWithBusybox(ctx, t, tc.daemonArgs...)
t.Cleanup(func() { d.Stop(t) })
})
usingNftables := d.FirewallBackendDriver(t) == "nftables"
c := d.NewClientT(t)
t.Cleanup(func() { c.Close() })
// If necessary, the IPv4 policy should have been updated when the default bridge network was created.
assert.Check(t, is.Equal(getFwdPolicy(usingNftables, "ip"), tc.expPolicy))
// IPv6 policy should not have been updated yet.
assert.Check(t, is.Equal(getFwdPolicy(usingNftables, "ip6"), "ACCEPT"))
assert.Check(t, is.Equal(getSysctls(), sysctls{tc.expForwarding, tc.initForwarding, tc.initForwarding}))
// If necessary, creating an IPv6 network should update the sysctls and policy.
const netName = "testnetffp"
network.CreateNoError(ctx, t, c, netName, network.WithIPv6())
t.Cleanup(func() { network.RemoveNoError(ctx, t, c, netName) })
assert.Check(t, is.Equal(getFwdPolicy(usingNftables, "ip"), tc.expPolicy))
assert.Check(t, is.Equal(getFwdPolicy(usingNftables, "ip6"), tc.expPolicy))
assert.Check(t, is.Equal(getSysctls(), sysctls{tc.expForwarding, tc.expForwarding, tc.expForwarding}))
})
}
}
// TestPointToPoint checks that a "/31" --internal network with inhibit_ipv4,
// or gateway mode "isolated" has two addresses available for containers (no
// address is reserved for a gateway, because it won't be used).
func TestPointToPoint(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
testcases := []struct {
name string
netOpt func(*networktypes.CreateOptions)
}{
{
name: "inhibit_ipv4",
netOpt: network.WithOption(bridge.InhibitIPv4, "true"),
},
{
name: "isolated",
netOpt: network.WithOption(bridge.IPv4GatewayMode, "isolated"),
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
ctx := testutil.StartSpan(ctx, t)
const netName = "testp2pbridge"
network.CreateNoError(ctx, t, apiClient, netName,
network.WithIPAM("192.168.135.0/31", ""),
network.WithInternal(),
tc.netOpt,
)
defer network.RemoveNoError(ctx, t, apiClient, netName)
const ctrName = "ctr1"
id := ctr.Run(ctx, t, apiClient,
ctr.WithNetworkMode(netName),
ctr.WithName(ctrName),
)
defer apiClient.ContainerRemove(ctx, id, containertypes.RemoveOptions{Force: true})
attachCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
res := ctr.RunAttach(attachCtx, t, apiClient,
ctr.WithCmd([]string{"ping", "-c1", "-W3", ctrName}...),
ctr.WithNetworkMode(netName),
)
defer apiClient.ContainerRemove(ctx, res.ContainerID, containertypes.RemoveOptions{Force: true})
assert.Check(t, is.Equal(res.ExitCode, 0))
assert.Check(t, is.Equal(res.Stderr.Len(), 0))
assert.Check(t, is.Contains(res.Stdout.String(), "1 packets transmitted, 1 packets received"))
})
}
}
// TestIsolated tests an internal network with gateway mode "isolated".
func TestIsolated(t *testing.T) {
skip.If(t, testEnv.IsRootless, "can't inspect bridge addrs in rootless netns")
ctx := setupTest(t)
apiClient := testEnv.APIClient()
const netName = "testisol"
const bridgeName = "br-" + netName
network.CreateNoError(ctx, t, apiClient, netName,
network.WithIPv6(),
network.WithInternal(),
network.WithOption(bridge.IPv4GatewayMode, "isolated"),
network.WithOption(bridge.IPv6GatewayMode, "isolated"),
network.WithOption(bridge.BridgeName, bridgeName),
)
defer network.RemoveNoError(ctx, t, apiClient, netName)
// The bridge should not have any IP addresses.
link, err := nlwrap.LinkByName(bridgeName)
assert.NilError(t, err)
addrs, err := nlwrap.AddrList(link, netlink.FAMILY_ALL)
assert.NilError(t, err)
assert.Check(t, is.Equal(len(addrs), 0))
const ctrName = "ctr1"
id := ctr.Run(ctx, t, apiClient,
ctr.WithNetworkMode(netName),
ctr.WithName(ctrName),
)
defer apiClient.ContainerRemove(ctx, id, containertypes.RemoveOptions{Force: true})
ping := func(t *testing.T, ipv string) {
t.Helper()
attachCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
res := ctr.RunAttach(attachCtx, t, apiClient,
ctr.WithCmd([]string{"ping", "-c1", "-W3", ipv, "ctr1"}...),
ctr.WithNetworkMode(netName),
)
defer apiClient.ContainerRemove(ctx, res.ContainerID, containertypes.RemoveOptions{Force: true})
if ipv == "-6" && networking.FirewalldRunning() {
// FIXME(robmry) - this fails due to https://github.com/moby/moby/issues/49680
if res.ExitCode != 1 {
t.Log("Unexpected pass!")
t.Log(icmd.RunCommand("nft", "list ruleset").Stdout())
t.Log(icmd.RunCommand("ip", "a").Stdout())
t.Log(icmd.RunCommand("route", "-6").Stdout())
}
t.Skip("XFAIL - IPv6, firewalld, isolated - see https://github.com/moby/moby/issues/49680")
}
assert.Check(t, is.Equal(res.ExitCode, 0))
assert.Check(t, is.Equal(res.Stderr.Len(), 0))
assert.Check(t, is.Contains(res.Stdout.String(), "1 packets transmitted, 1 packets received"))
}
t.Run("ipv4", func(t *testing.T) { ping(t, "-4") })
t.Run("ipv6", func(t *testing.T) { ping(t, "-6") })
}
func TestEndpointWithCustomIfname(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
ctrID := ctr.Run(ctx, t, apiClient,
ctr.WithCmd("ip", "-o", "link", "show", "foobar"),
ctr.WithEndpointSettings("bridge", &networktypes.EndpointSettings{
DriverOpts: map[string]string{
netlabel.Ifname: "foobar",
},
}))
defer ctr.Remove(ctx, t, apiClient, ctrID, containertypes.RemoveOptions{Force: true})
out, err := ctr.Output(ctx, apiClient, ctrID)
assert.NilError(t, err)
assert.Assert(t, strings.Contains(out.Stdout, ": foobar@if"), "expected ': foobar@if' in 'ip link show':\n%s", out.Stdout)
}
// TestPublishedPortAlreadyInUse checks that a container that can't start
// because of one its published port being already in use doesn't end up
// triggering the restart loop.
//
// Regression test for: https://github.com/moby/moby/issues/49501
func TestPublishedPortAlreadyInUse(t *testing.T) {
ctx := setupTest(t)
apiClient := testEnv.APIClient()
ctr1 := ctr.Run(ctx, t, apiClient,
ctr.WithCmd("top"),
ctr.WithExposedPorts("80/tcp"),
ctr.WithPortMap(nat.PortMap{"80/tcp": {{HostPort: "8000"}}}))
defer ctr.Remove(ctx, t, apiClient, ctr1, containertypes.RemoveOptions{Force: true})
ctr2 := ctr.Create(ctx, t, apiClient,
ctr.WithCmd("top"),
ctr.WithRestartPolicy(containertypes.RestartPolicyAlways),
ctr.WithExposedPorts("80/tcp"),
ctr.WithPortMap(nat.PortMap{"80/tcp": {{HostPort: "8000"}}}))
defer ctr.Remove(ctx, t, apiClient, ctr2, containertypes.RemoveOptions{Force: true})
err := apiClient.ContainerStart(ctx, ctr2, containertypes.StartOptions{})
assert.Assert(t, is.ErrorContains(err, "failed to set up container networking"))
inspect, err := apiClient.ContainerInspect(ctx, ctr2)
assert.NilError(t, err)
assert.Check(t, is.Equal(inspect.State.Status, containertypes.StateCreated))
}
// TestAllPortMappingsAreReturned check that dual-stack ports mapped through
// different networks are correctly reported as dual-stakc.
//
// Regression test for https://github.com/moby/moby/issues/49654.
func TestAllPortMappingsAreReturned(t *testing.T) {
ctx := setupTest(t)
d := daemon.New(t)
d.StartWithBusybox(ctx, t, "--userland-proxy=false")
defer d.Stop(t)
apiClient := d.NewClientT(t)
defer apiClient.Close()
nwV4 := network.CreateNoError(ctx, t, apiClient, "testnetv4")
defer network.RemoveNoError(ctx, t, apiClient, nwV4)
nwV6 := network.CreateNoError(ctx, t, apiClient, "testnetv6",
network.WithIPv4(false),
network.WithIPv6())
defer network.RemoveNoError(ctx, t, apiClient, nwV6)
ctrID := ctr.Run(ctx, t, apiClient,
ctr.WithExposedPorts("80/tcp", "81/tcp"),
ctr.WithPortMap(nat.PortMap{"80/tcp": {{HostPort: "8000"}}}),
ctr.WithEndpointSettings("testnetv4", &networktypes.EndpointSettings{}),
ctr.WithEndpointSettings("testnetv6", &networktypes.EndpointSettings{}))
defer ctr.Remove(ctx, t, apiClient, ctrID, containertypes.RemoveOptions{Force: true})
inspect := ctr.Inspect(ctx, t, apiClient, ctrID)
assert.DeepEqual(t, inspect.NetworkSettings.Ports, nat.PortMap{
"80/tcp": []nat.PortBinding{
{HostIP: "0.0.0.0", HostPort: "8000"},
{HostIP: "::", HostPort: "8000"},
},
"81/tcp": nil,
})
}
// TestFirewalldReloadNoZombies checks that when firewalld is reloaded, rules
// belonging to deleted networks/containers do not reappear.
func TestFirewalldReloadNoZombies(t *testing.T) {
skip.If(t, !networking.FirewalldRunning(), "firewalld is not running")
skip.If(t, testEnv.IsRootless, "no firewalld in rootless netns")
ctx := setupTest(t)
d := daemon.New(t)
d.StartWithBusybox(ctx, t)
defer d.Stop(t)
c := d.NewClientT(t)
const bridgeName = "br-fwdreload"
removed := false
nw := network.CreateNoError(ctx, t, c, "testnet",
network.WithOption(bridge.BridgeName, bridgeName))
defer func() {
if !removed {
network.RemoveNoError(ctx, t, c, nw)
}
}()
cid := ctr.Run(ctx, t, c,
ctr.WithExposedPorts("80/tcp", "81/tcp"),
ctr.WithPortMap(nat.PortMap{"80/tcp": {{HostPort: "8000"}}}))
defer func() {
if !removed {
ctr.Remove(ctx, t, c, cid, containertypes.RemoveOptions{Force: true})
}
}()
iptablesSave := icmd.Command("iptables-save")
resBeforeDel := icmd.RunCmd(iptablesSave)
assert.NilError(t, resBeforeDel.Error)
assert.Check(t, strings.Contains(resBeforeDel.Combined(), bridgeName),
"With container: expected rules for %s in: %s", bridgeName, resBeforeDel.Combined())
// Delete the container and its network.
ctr.Remove(ctx, t, c, cid, containertypes.RemoveOptions{Force: true})
network.RemoveNoError(ctx, t, c, nw)
removed = true
// Check the network does not appear in iptables rules.
resAfterDel := icmd.RunCmd(iptablesSave)
assert.NilError(t, resAfterDel.Error)
assert.Check(t, !strings.Contains(resAfterDel.Combined(), bridgeName),
"After deletes: did not expect rules for %s in: %s", bridgeName, resAfterDel.Combined())
// firewall-cmd --reload, and wait for the daemon to restore rules.
networking.FirewalldReload(t, d)
// Check that rules for the deleted container/network have not reappeared.
resAfterReload := icmd.RunCmd(iptablesSave)
assert.NilError(t, resAfterReload.Error)
assert.Check(t, !strings.Contains(resAfterReload.Combined(), bridgeName),
"After deletes: did not expect rules for %s in: %s", bridgeName, resAfterReload.Combined())
}
// TestLegacyLink checks that a legacy link ("--link" in the default bridge network)
// sets up a hostname and opens ports when the daemon is running with icc=false.
func TestLegacyLink(t *testing.T) {
ctx := setupTest(t)
// Tidy up after the test by starting a new daemon, which will remove the icc=false
// rules this test will create for docker0.
defer func() {
d := daemon.New(t)
d.StartWithBusybox(ctx, t)
defer d.Stop(t)
}()
d := daemon.New(t)
d.StartWithBusybox(ctx, t, "--icc=false")
defer d.Stop(t)
c := d.NewClientT(t)
// Run an http server.
const svrName = "svr"
cid := ctr.Run(ctx, t, c,
ctr.WithExposedPorts("80/tcp"),
ctr.WithName(svrName),
ctr.WithCmd("httpd", "-f"),
)
defer ctr.Remove(ctx, t, c, cid, containertypes.RemoveOptions{Force: true})
insp := ctr.Inspect(ctx, t, c, cid)
svrAddr := insp.NetworkSettings.Networks["bridge"].IPAddress
const svrAlias = "thealias"
testcases := []struct {
name string
host string
links []string
expect string
}{
{
name: "no link",
host: svrAddr,
expect: "download timed out",
},
{
name: "access by address",
links: []string{svrName},
host: svrAddr,
expect: "404 Not Found", // Got a response, but the server has nothing to serve.
},
{
name: "access by name",
links: []string{svrName},
host: svrName,
expect: "404 Not Found", // Got a response, but the server has nothing to serve.
},
{
name: "access by alias",
links: []string{svrName + ":" + svrAlias},
host: svrAlias,
expect: "404 Not Found", // Got a response, but the server has nothing to serve.
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
ctx := testutil.StartSpan(ctx, t)
res := ctr.RunAttach(ctx, t, c,
ctr.WithLinks(tc.links...),
ctr.WithCmd("wget", "-T3", "http://"+tc.host),
)
assert.Check(t, is.Contains(res.Stderr.String(), tc.expect))
})
}
}
// TestRemoveLegacyLink checks that a legacy link can be deleted while the
// linked containers are running.
//
// Replacement for DockerDaemonSuite/TestDaemonLinksIpTablesRulesWhenLinkAndUnlink
func TestRemoveLegacyLink(t *testing.T) {
ctx := setupTest(t)
// Tidy up after the test by starting a new daemon, which will remove the icc=false
// rules this test will create for docker0.
defer func() {
d := daemon.New(t)
d.StartWithBusybox(ctx, t)
defer d.Stop(t)
}()
d := daemon.New(t)
d.StartWithBusybox(ctx, t, "--icc=false")
defer d.Stop(t)
c := d.NewClientT(t)
// Run an http server.
const svrName = "svr"
svrId := ctr.Run(ctx, t, c,
ctr.WithExposedPorts("80/tcp"),
ctr.WithName(svrName),
ctr.WithCmd("httpd", "-f"),
)
defer ctr.Remove(ctx, t, c, svrId, containertypes.RemoveOptions{Force: true})
// Run a container linked to the http server.
const svrAlias = "thealias"
const clientName = "client"
clientId := ctr.Run(ctx, t, c,
ctr.WithName(clientName),
ctr.WithLinks(svrName+":"+svrAlias),
)
defer ctr.Remove(ctx, t, c, clientId, containertypes.RemoveOptions{Force: true})
// Check the link works.
res := ctr.ExecT(ctx, t, c, clientId, []string{"wget", "-T3", "http://" + svrName})
assert.Check(t, is.Contains(res.Stderr(), "404 Not Found"))
// Remove the link ("docker rm --link client/thealias").
err := c.ContainerRemove(ctx, clientName+"/"+svrAlias, containertypes.RemoveOptions{RemoveLinks: true})
assert.Check(t, err)
// Check both containers are still running.
inspSvr := ctr.Inspect(ctx, t, c, svrId)
assert.Check(t, is.Equal(inspSvr.State.Running, true))
inspClient := ctr.Inspect(ctx, t, c, clientId)
assert.Check(t, is.Equal(inspClient.State.Running, true))
// Check the link's alias doesn't work.
res = ctr.ExecT(ctx, t, c, clientId, []string{"wget", "-T3", "http://" + svrName})
assert.Check(t, is.Contains(res.Stderr(), "bad address"))
// Check the icc=false rules now block access by address.
svrAddr := inspSvr.NetworkSettings.Networks["bridge"].IPAddress
res = ctr.ExecT(ctx, t, c, clientId, []string{"wget", "-T3", "http://" + svrAddr})
assert.Check(t, is.Contains(res.Stderr(), "download timed out"))
}
// TestPortMappingRestore check that port mappings are restored when a container
// is restarted after a daemon restart.
//
// Replacement for integration-cli test DockerDaemonSuite/TestDaemonIptablesCreate
func TestPortMappingRestore(t *testing.T) {
skip.If(t, testEnv.IsRootless(), "fails before and after restart")
ctx := setupTest(t)
d := daemon.New(t)
d.StartWithBusybox(ctx, t)
defer d.Stop(t)
c := d.NewClientT(t)
const svrName = "svr"
cid := ctr.Run(ctx, t, c,
ctr.WithExposedPorts("80/tcp"),
ctr.WithPortMap(nat.PortMap{"80/tcp": {}}),
ctr.WithName(svrName),
ctr.WithRestartPolicy(containertypes.RestartPolicyUnlessStopped),
ctr.WithCmd("httpd", "-f"),
)
defer func() { ctr.Remove(ctx, t, c, cid, containertypes.RemoveOptions{Force: true}) }()
check := func() {
t.Helper()
insp := ctr.Inspect(ctx, t, c, cid)
assert.Check(t, is.Equal(insp.State.Running, true))
if assert.Check(t, is.Contains(insp.NetworkSettings.Ports, nat.Port("80/tcp"))) &&
assert.Check(t, is.Len(insp.NetworkSettings.Ports["80/tcp"], 2)) {
hostPort := insp.NetworkSettings.Ports["80/tcp"][0].HostPort
res := ctr.RunAttach(ctx, t, c,
ctr.WithExtraHost("thehost:host-gateway"),
ctr.WithCmd("wget", "-T3", "http://"+net.JoinHostPort("thehost", hostPort)),
)
// 404 means the http request worked, but the http server had nothing to serve.
assert.Check(t, is.Contains(res.Stderr.String(), "404 Not Found"))
}
}
check()
d.Restart(t)
check()
}
// TestNoSuchExternalBridge checks that the daemon won't start if it's given a "--bridge"
// that doesn't exist.
//
// Replacement for part of DockerDaemonSuite/TestDaemonBridgeExternal
func TestNoSuchExternalBridge(t *testing.T) {
_ = setupTest(t)
d := daemon.New(t)
defer d.Stop(t)
err := d.StartWithError("--bridge", "nosuchbridge")
assert.Check(t, err != nil, "Expected daemon startup to fail")
}
|