diff --git a/docs/services/ecs.md b/docs/services/ecs.md index 308ebe94ac..8c29f75dd2 100644 --- a/docs/services/ecs.md +++ b/docs/services/ecs.md @@ -348,6 +348,14 @@ stops, and the ENI is released. Security-group enforcement (`FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED`) adds packet filtering on top of the ENI; it is not needed for the ENI itself. +With Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=true` and +`FLOCI_SERVICES_EC2_MOCK=false`), a Docker-mode task also joins its VPC's Docker network at the ENI +address, so an EC2 instance, a `VpcConfig` Lambda function or any other container on that network +reaches the task at the `privateIPv4Address` that `DescribeTasks` reports. AWS gives the whole task +that one address; Floci gives it to one container, the first in the task definition that maps a +port, else the first, and the task's other containers do not answer at it. A task in a +security-group protected namespace keeps that namespace and does not join the VPC network. + #### Capacity providers `capacityProviderStrategy` is honoured on `RunTask` and `CreateService`, including the built-in @@ -586,7 +594,7 @@ carries `AWS_INSTANCE_IPV4` and `AWS_INSTANCE_PORT`, chosen by network mode: | Network mode | `AWS_INSTANCE_IPV4` | `AWS_INSTANCE_PORT` | |---|---|---| -| `awsvpc` | the address the task's container holds on its Docker network | the entry's `containerPort` | +| `awsvpc` | the address the task's container holds on the Docker network it was created on | the entry's `containerPort` | | `bridge` or `host` | the address Floci reaches the container at: `127.0.0.1` when Floci runs natively, the container's Docker network address when Floci runs in Docker | the host port the entry's `containerPort` was published on, or the `containerPort` when it has no binding | An explicit `port` on the registry entry is registered as-is in every mode, as on AWS. The @@ -607,8 +615,9 @@ Known differences from AWS: only A records, so such a task registers its address and its published host port and resolves by address; the port is readable through `DiscoverInstances` rather than DNS. - An awsvpc task registers its container's Docker network address, not its ENI address. On - AWS the two are the same interface. In Floci a task's containers never join the subnet's - network, so the ENI address `DescribeTasks` reports is not one a peer can connect to. The + AWS the two are the same interface. In Floci the ENI address is held only on the VPC's + Docker network, when VPC networks are enabled, so it is not one a peer outside that network + can connect to. The registrar falls back to the ENI address only when it cannot read an address from a running container. Because the address is the container's own, the port is its `containerPort`, not any host port Floci also published it on. diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 221ef25251..7dae9a7d1a 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -1020,8 +1020,12 @@ group lists detach the function, and the response then omits `VpcConfig`. Publis versions retain their network configuration when `$LATEST` changes. These checks validate the declaration. Function containers still use the configured -Docker network; `VpcConfig` does not yet enforce VPC packet routing, security-group -rules, or NAT egress. +Docker network. With Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=true` +and `FLOCI_SERVICES_EC2_MOCK=false`) and a known `VpcId`, the container also joins that VPC's +Docker network at an address leased from the first subnet in `SubnetIds`, so it reaches EC2 +instances and `awsvpc` ECS tasks in the VPC at the private addresses they report. The address is +returned once the container is removed. `VpcConfig` does not yet enforce security-group rules or +NAT egress, and the other subnets are not used. `RuntimeVersionConfig.RuntimeVersionArn` is returned for managed (non-image) runtimes. Its value is derived from the runtime name, so it is stable across diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 7b6df598ee..78adbfc378 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -341,6 +341,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // region::subnetId → offset the next synthesised address is tried at. Only an ordering hint: // restart forgets it, and privateIpsInUse is what keeps addresses from being handed out twice. private final Map subnetIpCursors = new HashMap<>(); + // region::subnetId → addresses allocateVpcPrivateIp leased to containers no stored resource + // stands behind; guarded by privateIpAllocationLock. + private final Map> containerPrivateIps = new HashMap<>(); // Held from a synthesised address being chosen until the resource holding it is persisted, so // a concurrent allocation, which reads persisted resources to see what is taken, cannot pick // the same address in between. Taken after imageRegistryLock where a caller holds both. @@ -411,6 +414,43 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return false; } + /** Attaches a container to the VPC's Docker network at {@code address}; empty when it stays off it. */ + public Optional attachContainerToVpc(String region, String vpcId, String subnetId, + String containerId, String address) { + if (vpcNetworkManager == null) { + return Optional.empty(); + } + return vpcNetworkManager.attach(region, vpcId, subnetId, containerId, address); + } + + /** + * Leases an address of a Docker-backed subnet that nothing else holds, as an instance's is + * chosen; empty when the subnet is not Docker-backed or has none left. + */ + public Optional allocateVpcPrivateIp(String region, String subnetId) { + if (vpcNetworkManager == null) { + return Optional.empty(); + } + synchronized (privateIpAllocationLock) { + Optional allocated = vpcNetworkManager.allocatePrivateIp(region, subnetId) + .flatMap(first -> leaseNotHeld(region, subnetId, first, + privateIpsHeldOnVpcNetwork(region, subnetId))); + allocated.ifPresent(address -> containerPrivateIps + .computeIfAbsent(key(region, subnetId), ignored -> new HashSet<>()).add(address)); + return allocated; + } + } + + public void releaseVpcPrivateIp(String region, String subnetId, String address) { + synchronized (privateIpAllocationLock) { + containerPrivateIps.computeIfPresent(key(region, subnetId), (ignored, addresses) -> { + addresses.remove(address); + return addresses.isEmpty() ? null : addresses; + }); + releasePrivateIps(region, subnetId, List.of(address)); + } + } + public boolean isVpcNetworkEnabled() { return vpcNetworkManager != null && vpcNetworkManager.enabled(); } @@ -4544,6 +4584,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return assignPrivateIp(region, subnetId, List.of()); } + /** + * Keeps the lease on {@code first}, or on the next address the network offers, unless + * {@code held} contains it. Callers must hold {@link #privateIpAllocationLock}. + */ + private Optional leaseNotHeld(String region, String subnetId, String first, Set held) { + Optional allocated = Optional.of(first); + List skipped = new ArrayList<>(); + while (allocated.isPresent() && held.contains(allocated.get())) { + skipped.add(allocated.get()); + allocated = vpcNetworkManager.allocatePrivateIp(region, subnetId); + } + // Given back only once the walk is over, or the network would offer them again. Their + // holders took no lease, so the network must not count one for them. + releasePrivateIps(region, subnetId, skipped); + return allocated; + } + /** * Gives back the VPC network's lease on each address, so automatic allocation can offer it * again. Callers must hold {@link #privateIpAllocationLock}. @@ -4577,16 +4634,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (allocated.isPresent()) { held = privateIpsHeldOnVpcNetwork(region, subnetId); held.addAll(pending); + allocated = leaseNotHeld(region, subnetId, allocated.get(), held); } - List skipped = new ArrayList<>(); - while (allocated.isPresent() && held.contains(allocated.get())) { - skipped.add(allocated.get()); - allocated = vpcNetworkManager.allocatePrivateIp(region, subnetId); - } - // Given back only once the walk is over, or the network would offer them again. Their - // holders took no lease, and deleting an interface returns none, so a lease kept here - // would outlive the holder. - releasePrivateIps(region, subnetId, skipped); if (allocated.isPresent()) { return allocated.get(); } @@ -4670,10 +4719,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * lease to show for it: an interface created with its own address never takes one, and a * restart re-leases only instances. Any other subnet id belongs to one account, so for it the * wider scan finds nothing more. A lease with nothing in any account behind it does not fail - * the launch: it is stale (DeleteNetworkInterface never returns its lease), or it belongs to - * a launch that failed and has not given the address back yet, which it does once its - * container is detached. Either way the instance keeps the address without a lease of its - * own, and {@link #assignPrivateIp} still skips it, because the stored instance holds it. + * the launch: it belongs to a launch that failed and has not given the address back yet, + * which it does once its container is detached, or it outlived a holder that never returned + * it. Either way the instance keeps the address without a lease of its own, and + * {@link #assignPrivateIp} still skips it, because the stored instance holds it. * An address outside a substituted subnet's effective range is never leased at all, in which * case the instance keeps it the way it keeps a synthesised address. */ @@ -4687,9 +4736,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * The in-use half of {@link #claimRequestedPrivateIp}, without the lease. CreateNetworkInterface * and CreateNatGateway use it alone: neither an interface nor a NAT gateway has a container to * hold the address on the VPC network, and {@link #assignPrivateIp} already steps around - * addresses stored interfaces and NAT gateways hold. DeleteNetworkInterface returns no lease, - * so one taken here would keep the address from automatic allocation after the interface is - * gone. Callers must hold {@link #privateIpAllocationLock}. + * addresses stored interfaces and NAT gateways hold, so neither needs a lease. Callers must + * hold {@link #privateIpAllocationLock}. * * @return whether the address lies in a Docker-backed range, where a lease could be taken */ @@ -4749,7 +4797,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab /** * Every private address a live instance, network interface, NAT gateway or EC2 Instance Connect - * Endpoint holds in the subnet. + * Endpoint holds in the subnet, and those {@link #allocateVpcPrivateIp} leased to containers. */ private Set privateIpsInUse(String region, String subnetId) { return new HashSet<>(privateIpsBySubnet(region).getOrDefault(subnetId, Set.of())); @@ -4768,10 +4816,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private Map> privateIpsBySubnet(String region) { String regionPrefix = region + "::"; - return privateIpsBySubnet(networkInterfaces.scan(k -> k.startsWith(regionPrefix)), + Map> bySubnet = privateIpsBySubnet(networkInterfaces.scan(k -> k.startsWith(regionPrefix)), instances.scan(k -> k.startsWith(regionPrefix)), natGateways.scan(k -> k.startsWith(regionPrefix)), instanceConnectEndpoints.scan(k -> k.startsWith(regionPrefix))); + // Read here, the one occupancy every allocator and endpoint derivation shares, so a derived + // endpoint interface cannot land on a container's address. + synchronized (privateIpAllocationLock) { + containerPrivateIps.forEach((subnetKey, addresses) -> { + if (subnetKey.startsWith(regionPrefix)) { + bySubnet.computeIfAbsent(subnetKey.substring(regionPrefix.length()), ignored -> new HashSet<>()) + .addAll(addresses); + } + }); + } + return bySubnet; } private static Map> privateIpsBySubnet(List regionInterfaces, @@ -7372,8 +7431,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab /** * {@link #privateIpsInUse} as numeric IPv4 values, for endpoint derivation. Only persisted - * resources are read, never another endpoint's derived interfaces, so the derivation cannot - * recurse into itself through the allocator. + * resources and container leases are read, never another endpoint's derived interfaces, so the + * derivation cannot recurse into itself through the allocator. */ private Set persistedAddressValuesInUse(String region, String subnetId) { return addressValues(privateIpsInUse(region, subnetId)); @@ -12995,9 +13054,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // A CreateTags write that read the gateway before an earlier delete can store it back // marked deleted. That delete gave its addresses back, and the network may have leased // them to something else since. A requested address took no lease of its own. The one it - // can carry is either a stale lease DeleteNetworkInterface left behind, which should go, - // or a failed launch's, given back once its container is detached; giving that back - // sooner matters only if the allocator wraps around to it in between. + // can carry is either a stale lease, which should go, or a failed launch's, given back + // once its container is detached; giving that back sooner matters only if the allocator + // wraps around to it in between. if (!"deleted".equals(natGateway.getState())) { releasePrivateIps(region, natGateway.getSubnetId(), natGateway.getNatGatewayAddresses().stream() .map(NatGatewayAddress::getPrivateIp).toList()); @@ -15265,9 +15324,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } /** - * Deletes a standalone ENI. AWS refuses while it is still attached, floci-kt9, and equally - * while a service holds it: {@link #holdNetworkInterfaceForService} leaves no attachment - * behind, so the status is what says the interface is spoken for. + * Deletes a standalone ENI and gives the lease its primary address took back to the VPC + * network. A requested primary took no lease, so any it carries is a failed launch's, given + * back early as a deleted NAT gateway's is. AWS refuses while it is still attached, + * floci-kt9, and equally while a service holds it: {@link #holdNetworkInterfaceForService} + * leaves no attachment behind, so the status is what says the interface is spoken for. */ public void deleteNetworkInterface(String region, String networkInterfaceId) { synchronized (privateIpAllocationLock) { @@ -15278,6 +15339,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } releaseInterfaceAddresses(region, networkInterfaceId, true); networkInterfaces.delete(key(region, networkInterfaceId)); + releasePrivateIps(region, ni.getSubnetId(), List.of(ni.getPrivateIpAddress())); } } diff --git a/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java b/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java index 1ffb56e9f5..7d05874064 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsServiceDiscoveryRegistrar.java @@ -249,8 +249,9 @@ public class EcsServiceDiscoveryRegistrar { /** * Builds the instance attributes AWS records for an ECS-registered instance. On AWS the * address of an awsvpc task is its ENI address, because that is where the task answers. In - * Floci the ENI address belongs to no network the task's containers joined, so an awsvpc task - * registers the address its container actually holds, and falls back to the ENI address only + * Floci the ENI address is held at most on the VPC's Docker network, which peers outside that + * VPC cannot reach, so an awsvpc task registers the address its container holds on + * the network it was created on, and falls back to the ENI address only * when no running container can say what it holds. A bridge-mode task has no ENI and is * registered at the container's host address, as before. * diff --git a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java index 9ec80e49a6..1ae5809630 100644 --- a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java @@ -623,6 +623,9 @@ public class EcsContainerManager { } throw e; } + if (task.getNetworkInterfaceId() != null && protectedNetwork == null) { + joinTaskVpcNetwork(task, taskDef, containerIds, region); + } Map runtimeContainersByName = new LinkedHashMap<>(); for (Container container : runtimeContainers) { @@ -1150,6 +1153,30 @@ public class EcsContainerManager { } } + /** + * Puts one container of an awsvpc task on its VPC's Docker network at the task ENI address, so + * the address DescribeTasks reports answers. AWS gives the whole task that one address; here it + * goes to the first container that maps a port, else to the first container. Without + * Docker-backed VPC networks, or for an ENI address outside the subnet's planned range, the + * containers keep only the network they were created on. Removing the container disconnects + * it, before {@link #releaseTaskNetwork} returns the address. + */ + private void joinTaskVpcNetwork(EcsTask task, TaskDefinition taskDef, Map containerIds, + String region) { + String vpcId = taskVpcId(task, region); + if (vpcId == null) { + return; + } + List definitions = taskDef.getContainerDefinitions(); + ContainerDefinition holder = definitions.stream() + .filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty()) + .findFirst() + .orElse(definitions.getFirst()); + ec2Service.attachContainerToVpc(region, vpcId, + task.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst(), + containerIds.get(holder.getName()), task.getPrivateIpAddress()); + } + /** * Restates an EC2 lookup failure as the error RunTask declares. A caller naming a subnet or a * security group that is not there asked for something the task cannot have, and @@ -2168,8 +2195,9 @@ public class EcsContainerManager { * protected namespace has no network of its own, so the namespace holder's address is the one * it answers on. * - *

This is deliberately not the task ENI address. ECS containers never join the subnet's - * VPC network, so the ENI address is control-plane state that no peer can connect to. + *

This is deliberately not the task ENI address. One task container holds that address on + * the VPC's Docker network, when VPC networks are enabled, but peers outside that VPC reach the + * task on the network its container was created on, so that address is the one returned. * * @return the address, or empty when the container has not started or Docker cannot say */ @@ -2196,17 +2224,25 @@ public class EcsContainerManager { // A container can be on multiple networks; getNetworks() is unordered. // Pick an IP that the Floci/ELBv2 process can actually route to: - // 1. the explicitly-configured ECS Docker network, if set; - // 2. otherwise any user-defined network (Floci joins one when in Docker) - // in preference to the default bridge; - // 3. otherwise the first non-blank IP. - String configured = config.services().ecs().dockerNetwork().orElse(null); + // 1. the network ECS containers join: the configured one, or the one Floci runs on; + // 2. otherwise the network the container was created on, rather than the VPC + // network an awsvpc task also joins at its ENI address; + // 3. otherwise any user-defined network in preference to the default bridge; + // 4. otherwise the first non-blank IP. + String configured = containerBuilder.resolveDockerNetwork(config.services().ecs().dockerNetwork()) + .orElse(null); if (configured != null && !configured.isBlank()) { ContainerNetwork net = networks.get(configured); if (net != null && isUsableIp(net.getIpAddress())) { return Optional.of(net.getIpAddress()); } } + String ownNetwork = inspect.getHostConfig() == null ? null : inspect.getHostConfig().getNetworkMode(); + ContainerNetwork own = ownNetwork == null ? null + : networks.get("default".equals(ownNetwork) ? "bridge" : ownNetwork); + if (own != null && isUsableIp(own.getIpAddress())) { + return Optional.of(own.getIpAddress()); + } for (Map.Entry entry : networks.entrySet()) { if (!isDefaultDockerNetwork(entry.getKey()) && isUsableIp(entry.getValue().getIpAddress())) { diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java index 7f28577c3d..ece705501a 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.exception.NotFoundException; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerLifecycleManager; import io.floci.aws.core.common.docker.ContainerLogStreamer; @@ -14,6 +15,7 @@ import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.core.common.docker.RetryingTarCopier; +import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ecr.registry.EcrRegistryManager; import io.floci.aws.services.iam.model.SessionCreds; import io.floci.aws.services.lambda.LambdaLayerService; @@ -124,6 +126,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { private final LambdaLayerService layerService; private final LaunchedContainerAwsEnv awsEnv; private final LambdaExecutionRoleCredentials executionRoleCredentials; + private final Ec2Service ec2Service; + /** The VPC address each VpcConfig function's container holds, returned once it is removed. */ + private final Map vpcLeases = new ConcurrentHashMap<>(); @Inject public ContainerLauncher(ContainerBuilder containerBuilder, @@ -136,7 +141,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { EcrRegistryManager ecrRegistryManager, LambdaLayerService layerService, LaunchedContainerAwsEnv awsEnv, - LambdaExecutionRoleCredentials executionRoleCredentials) { + LambdaExecutionRoleCredentials executionRoleCredentials, + Ec2Service ec2Service) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.logStreamer = logStreamer; @@ -148,6 +154,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { this.layerService = layerService; this.awsEnv = awsEnv; this.executionRoleCredentials = executionRoleCredentials; + this.ec2Service = ec2Service; this.populateSemaphore = new Semaphore(resolvePopulateConcurrency(config)); } @@ -442,6 +449,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { } // Now start the container with code in place + joinVpcNetwork(fn, containerId, lambdaAccountId, lambdaRegion); lifecycleManager.startCreated(containerId, spec); runtimeApiServer.markContainerStarted(); watchForUnexpectedExit(dockerClient, containerId, runtimeApiServer); @@ -496,7 +504,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { fn.getFunctionName(), e.getMessage()); if (containerId != null) { try { - lifecycleManager.stopAndRemove(containerId, null); + lifecycleManager.stopAndRemoveStrict(containerId, null); + releaseVpcLease(containerId); } catch (Exception cleanupError) { LOG.warnv(cleanupError, "Could not remove failed Lambda container {0}", containerId); } @@ -656,6 +665,9 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { executionRoleCredentials.unregister( handle.getExecutionRoleSessionAccountId(), handle.getExecutionRoleAccessKeyId()); } + // Only once the container is gone: a failed removal is retried, and until then Docker + // still holds the address. + releaseVpcLease(handle.getContainerId()); // Only now close the runtime API socket. Any pollers that were still parked when // the container exited get terminated by their end of the connection closing; @@ -674,6 +686,38 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { } } + /** + * Puts a VpcConfig function's container on its VPC's Docker network at an address leased from + * its first subnet, before it starts, so it reaches what the VPC holds by private address. + * Without Docker-backed VPC networks it stays on the network it was created on. + */ + private void joinVpcNetwork(LambdaFunction fn, String containerId, String accountId, String region) { + Object subnetIds = fn.getVpcConfig() == null ? null : fn.getVpcConfig().get("SubnetIds"); + if (fn.getVpcId() == null || ec2Service == null || !(subnetIds instanceof List subnets) + || subnets.isEmpty() || !(subnets.getFirst() instanceof String subnetId)) { + return; + } + // Provisioned and cross-account launches run outside the owner's request scope. + Optional address = RequestScopes.callAs(accountId, region, + () -> ec2Service.allocateVpcPrivateIp(region, subnetId)); + if (address.isEmpty()) { + return; + } + if (ec2Service.attachContainerToVpc(region, fn.getVpcId(), subnetId, containerId, address.get()).isPresent()) { + vpcLeases.put(containerId, new VpcLease(region, subnetId, address.get())); + } else { + ec2Service.releaseVpcPrivateIp(region, subnetId, address.get()); + } + } + + /** Docker holds the address until the container is gone, so callers run this after removing it. */ + private void releaseVpcLease(String containerId) { + VpcLease lease = vpcLeases.remove(containerId); + if (lease != null) { + ec2Service.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address()); + } + } + public static boolean isAwsCredentialVariable(String name) { return "AWS_ACCESS_KEY_ID".equals(name) || "AWS_SECRET_ACCESS_KEY".equals(name) @@ -1389,6 +1433,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { /** Where a container's output is sent: the CloudWatch log group/stream and its region. */ private record LogDestination(String accountId, String logGroup, String logStream, String region) { } + private record VpcLease(String region, String subnetId, String address) { } + /** * Arms an async watch (via Docker's own wait-for-exit API, not polling) that notices when * this container's main process dies while nothing inside the runtime reported it - a diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index a75c3fd0d2..5dc56da77c 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -4779,18 +4779,16 @@ class Ec2ServiceTest { @Test void aRefusedLeaseDoesNotTurnAFreeAddressIntoOneInUse() { - // DeleteNetworkInterface does not return its lease, so the lease table can outlive the - // resource that took one. With nothing in any account holding the address any more, the - // stale lease must not fail the launch. + // A failed launch gives its lease back only once its container is detached, so the lease + // table can hold an address nothing stored in any account stands behind. That lease must + // not fail the launch. RequestContext context = new RequestContext(); - Ec2Service service = realVpcNetworkService(context); + RealVpcNetworkFixture fixture = realVpcNetworkFixture(context, Map.of()); + Ec2Service service = fixture.service(); String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); context.setAccountId("111122223333"); service.describeSubnets("us-east-1", List.of(), Map.of()); - NetworkInterface deleted = service.createNetworkInterface("us-east-1", subnetId, "deleted", null, - List.of(), List.of(), List.of()); - service.deleteNetworkInterface("us-east-1", deleted.getNetworkInterfaceId()); - String stale = deleted.getPrivateIpAddress(); + String stale = fixture.vpcNetworks().allocatePrivateIp("us-east-1", subnetId).orElseThrow(); context.setAccountId("000000000000"); @@ -4974,8 +4972,7 @@ class Ec2ServiceTest { @Test void anAddressTheWalkSkipsIsGivenBackToTheVpcNetwork() { - // Its holder took no lease, and deleting an interface returns none, so a lease the walk - // kept would outlive the holder. + // Its holder took no lease, so the network must not count one for it. MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10", "10.50.1.11"); fixture.service().createNetworkInterface("us-east-1", fixture.subnetId(), "holder", "10.50.1.10", List.of(), List.of(), List.of()); @@ -4984,6 +4981,17 @@ class Ec2ServiceTest { assertEquals(List.of("10.50.1.10"), fixture.released()); } + @Test + void deletingAnInterfaceGivesBackTheLeaseOfItsAddress() { + MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10"); + String eniId = fixture.service().createNetworkInterface("us-east-1", fixture.subnetId(), "task", null, + List.of(), List.of(), List.of()).getNetworkInterfaceId(); + + fixture.service().deleteNetworkInterface("us-east-1", eniId); + + assertEquals(List.of("10.50.1.10"), fixture.released()); + } + @Test void anInterfaceRefusedForAHeldSecondaryLeasesNoPrimaryOnTheVpcNetwork() { MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/24", "10.50.1.10"); @@ -5053,6 +5061,69 @@ class Ec2ServiceTest { assertEquals(List.of("172.31.0.11"), launchAddresses(service, subnetId, 1)); } + @Test + void aVpcAddressLeasedOutsideEc2SkipsAnAddressAnInterfaceHolds() { + RequestContext context = new RequestContext(); + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = mockedVpcNetworkService(context, Map.of(), vpcNetworks); + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + service.describeSubnets("us-east-1", List.of(), Map.of()); + service.createNetworkInterface("us-east-1", subnetId, "holder", "172.31.0.10", + List.of(), List.of(), List.of()); + when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId)) + .thenReturn(Optional.of("172.31.0.10"), Optional.of("172.31.0.11")); + + assertEquals(Optional.of("172.31.0.11"), service.allocateVpcPrivateIp("us-east-1", subnetId)); + verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "172.31.0.10"); + } + + @Test + void anAddressAContainerLeasedIsInUseUntilItIsGivenBack() { + VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class); + Ec2Service service = mockedVpcNetworkService(new RequestContext(), Map.of(), vpcNetworks); + String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a"); + service.describeSubnets("us-east-1", List.of(), Map.of()); + when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId)) + .thenReturn(Optional.of("172.31.0.10"), Optional.empty()); + service.allocateVpcPrivateIp("us-east-1", subnetId); + + AwsException inUse = assertThrows(AwsException.class, () -> service.createNetworkInterface("us-east-1", + subnetId, "named", "172.31.0.10", List.of(), List.of(), List.of())); + assertEquals("InvalidIPAddress.InUse", inUse.getErrorCode()); + // The network's range is exhausted, so the address is synthesised. + assertEquals("172.31.0.11", service.createNetworkInterface("us-east-1", subnetId, "automatic", null, + List.of(), List.of(), List.of()).getPrivateIpAddress()); + + service.releaseVpcPrivateIp("us-east-1", subnetId, "172.31.0.10"); + assertEquals("172.31.0.10", service.createNetworkInterface("us-east-1", subnetId, "named", "172.31.0.10", + List.of(), List.of(), List.of()).getPrivateIpAddress()); + } + + @Test + void anInterfaceEndpointCreatedAfterContainerLeasesTakesAnAddressNoContainerHolds() { + // Ten of a /28's eleven assignable addresses leased to containers, so whatever the endpoint + // id prefers, its interface must land on the one left over. + List leased = new ArrayList<>(); + for (int host = 4; host <= 13; host++) { + leased.add("10.50.1." + host); + } + MockedNetworkFixture fixture = mockedNetworkFixture("10.50.1.0/28", leased.toArray(String[]::new)); + Ec2Service service = fixture.service(); + for (int i = 0; i < leased.size(); i++) { + service.allocateVpcPrivateIp("us-east-1", fixture.subnetId()); + } + String vpcId = service.describeSubnets("us-east-1", List.of(fixture.subnetId()), Map.of()) + .getFirst().getVpcId(); + + service.createVpcEndpoint("us-east-1", vpcId, "com.amazonaws.us-east-1.ecs", "Interface", List.of(), + List.of(fixture.subnetId()), List.of(), null, null, List.of()); + + assertEquals("10.50.1.14", endpointAddressesBySubnet(service).get(fixture.subnetId())); + AwsException inUse = assertThrows(AwsException.class, () -> service.createNetworkInterface("us-east-1", + fixture.subnetId(), "named", "10.50.1.14", List.of(), List.of(), List.of())); + assertEquals("InvalidIPAddress.InUse", inUse.getErrorCode()); + } + @Test void anAddressALaunchNamedWithoutLeasingItIsNotHandedOutAgain() { // A failed launch is marked terminated before its container is detached and its lease given @@ -5124,13 +5195,18 @@ class Ec2ServiceTest { return realVpcNetworkService(context, Map.of()); } + private static Ec2Service realVpcNetworkService(RequestContext context, + Map> stores) { + return realVpcNetworkFixture(context, stores).service(); + } + /** * Ec2Service in container mode over a real VpcNetworkManager, whose Docker daemon has no * networks yet, with the caller's account taken from {@code context} and {@code stores} * standing in for what a previous run persisted. */ - private static Ec2Service realVpcNetworkService(RequestContext context, - Map> stores) { + private static RealVpcNetworkFixture realVpcNetworkFixture(RequestContext context, + Map> stores) { EmulatorConfig config = mockConfig(false); EmulatorConfig.VpcNetworksConfig networks = mock(EmulatorConfig.VpcNetworksConfig.class); when(config.services().ec2().vpcNetworks()).thenReturn(networks); @@ -5142,9 +5218,14 @@ class Ec2ServiceTest { AmiImageResolver images = mock(AmiImageResolver.class); when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); jakarta.enterprise.inject.Instance contexts = requestContexts(context); - return new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), images, - mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(stores, contexts), - contexts, new VpcNetworkManager(config, docker, null), null, null, null); + VpcNetworkManager vpcNetworks = new VpcNetworkManager(config, docker, null); + Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), + images, mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), + new InMemoryStorageFactory(stores, contexts), contexts, vpcNetworks, null, null, null); + return new RealVpcNetworkFixture(service, vpcNetworks); + } + + private record RealVpcNetworkFixture(Ec2Service service, VpcNetworkManager vpcNetworks) { } /** diff --git a/src/test/java/io/floci/aws/services/ecs/EcsAwsvpcTaskAddressDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ecs/EcsAwsvpcTaskAddressDockerIntegrationTest.java new file mode 100644 index 0000000000..9cba07daa6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecs/EcsAwsvpcTaskAddressDockerIntegrationTest.java @@ -0,0 +1,152 @@ +package io.floci.aws.services.ecs; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.HostConfig; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.net.VpcNetworkManager; +import io.floci.aws.services.ecs.model.AwsVpcConfiguration; +import io.floci.aws.services.ecs.model.ContainerDefinition; +import io.floci.aws.services.ecs.model.EcsTask; +import io.floci.aws.services.ecs.model.LaunchType; +import io.floci.aws.services.ecs.model.NetworkConfiguration; +import io.floci.aws.services.ecs.model.NetworkMode; +import io.floci.aws.services.ecs.model.PortMapping; +import io.floci.aws.services.ecs.model.TaskDefinition; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.TestImages; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * An awsvpc task answers at the address DescribeTasks reports for it, for a peer on its VPC's + * Docker network: the stand-in for a Lambda function or an instance in the same VPC. + */ +@QuarkusTest +@TestProfile(EcsAwsvpcTaskAddressDockerIntegrationTest.VpcNetworksProfile.class) +class EcsAwsvpcTaskAddressDockerIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String SUBNET = "subnet-default-us-east-1-a"; + private static final int PORT = 8080; + + /** + * Docker-backed ECS and VPC networks, which need EC2 unmocked. Security-group enforcement keeps + * its shipped default of off, and a namespace of its own keeps the VPC network this test + * creates apart from any other Floci on the daemon. + */ + public static final class VpcNetworksProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ecs.mock", "false", + "floci.services.ec2.mock", "false", + "floci.services.ec2.vpc-networks.enabled", "true", + "floci.network.security-group-enforcement.enabled", "false", + "floci.docker.resource-namespace", "ecs-awsvpc-address-it"); + } + } + + @Inject + EcsService ecsService; + + @Inject + Ec2Service ec2Service; + + @Inject + VpcNetworkManager vpcNetworkManager; + + @Inject + DockerClient dockerClient; + + @BeforeEach + void requireDocker() throws InterruptedException { + assumeTrue(DockerAvailability.isAvailable(), "Docker must be available for the awsvpc address test"); + } + + @Test + void peerOnTheVpcNetworkReachesTheAddressDescribeTasksReports() throws InterruptedException { + String clusterName = unique("awsvpc-address"); + ecsService.createCluster(clusterName, REGION); + EcsTask task = ecsService.runTask(clusterName, registerWebServer().getTaskDefinitionArn(), 1, + LaunchType.FARGATE, null, null, List.of(), awsvpcNetwork(), REGION).getFirst(); + String vpcId = ec2Service.describeSubnets(REGION, List.of(SUBNET), Map.of()).getFirst().getVpcId(); + String network = null; + String probe = null; + try { + EcsTask described = ecsService.describeTasks(clusterName, List.of(task.getTaskArn()), REGION).getFirst(); + assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason()); + String address = described.getPrivateIpAddress(); + assertNotNull(address, "an awsvpc task must report its ENI address"); + network = vpcNetworkManager.networkNameFor(REGION, vpcId).orElseThrow(); + String dockerId = described.getContainers().getFirst().getDockerId(); + ContainerNetwork onVpc = dockerClient.inspectContainerCmd(dockerId).exec() + .getNetworkSettings().getNetworks().get(network); + assertNotNull(onVpc, "the task container must join the VPC network " + network); + assertEquals(address, onVpc.getIpAddress(), "the task container must hold its ENI address"); + + probe = dockerClient.createContainerCmd(TestImages.BUSYBOX) + .withHostConfig(HostConfig.newHostConfig().withNetworkMode(network)) + .withCmd("sh", "-c", "for i in 1 2 3 4 5 6 7 8 9 10; do " + + "[ \"$(wget -q -O- -T 1 http://" + address + ":" + PORT + "/)\" = ok ] && exit 0; " + + "sleep 0.1; done; exit 1") + .exec().getId(); + dockerClient.startContainerCmd(probe).exec(); + assertEquals(0, dockerClient.waitContainerCmd(probe).start().awaitStatusCode(60, TimeUnit.SECONDS), + "a peer on the VPC network must reach the task at " + address); + + ecsService.stopTask(clusterName, task.getTaskArn(), "awsvpc address test", REGION); + task = null; + assertFalse(dockerClient.inspectNetworkCmd().withNetworkId(network).exec() + .getContainers().containsKey(dockerId), + "a stopped task must leave the VPC network"); + } finally { + if (task != null) { + ecsService.stopTask(clusterName, task.getTaskArn(), "test teardown", REGION); + } + if (probe != null) { + dockerClient.removeContainerCmd(probe).withForce(true).exec(); + } + if (network != null) { + // Also disconnects the endpoint Floci gives itself on the network when it runs in a container. + vpcNetworkManager.deleteVpcNetwork(REGION, vpcId); + } + } + } + + private TaskDefinition registerWebServer() { + ContainerDefinition web = new ContainerDefinition(); + web.setName("web"); + web.setImage(TestImages.BUSYBOX); + web.setCommand(List.of("sh", "-c", + "mkdir -p /www && echo ok > /www/index.html && exec httpd -f -p " + PORT + " -h /www")); + web.setPortMappings(List.of(new PortMapping(PORT))); + return ecsService.registerTaskDefinition(unique("awsvpc-address-td"), List.of(web), NetworkMode.awsvpc, + null, null, null, null, null, REGION); + } + + private static NetworkConfiguration awsvpcNetwork() { + AwsVpcConfiguration awsvpc = new AwsVpcConfiguration(); + awsvpc.setSubnets(List.of(SUBNET)); + NetworkConfiguration networkConfiguration = new NetworkConfiguration(); + networkConfiguration.setAwsvpcConfiguration(awsvpc); + return networkConfiguration; + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java new file mode 100644 index 0000000000..a08d66d960 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java @@ -0,0 +1,227 @@ +package io.floci.aws.services.ecs.container; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.HostConfig; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo; +import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.SecurityGroupFirewallManager; +import io.floci.aws.services.ec2.model.GroupIdentifier; +import io.floci.aws.services.ec2.model.NetworkInterface; +import io.floci.aws.services.ec2.model.SecurityGroup; +import io.floci.aws.services.ec2.model.Subnet; +import io.floci.aws.services.ecr.registry.EcrRegistryManager; +import io.floci.aws.services.ecs.model.AwsVpcConfiguration; +import io.floci.aws.services.ecs.model.Container; +import io.floci.aws.services.ecs.model.ContainerDefinition; +import io.floci.aws.services.ecs.model.EcsTask; +import io.floci.aws.services.ecs.model.NetworkConfiguration; +import io.floci.aws.services.ecs.model.NetworkMode; +import io.floci.aws.services.ecs.model.PortMapping; +import io.floci.aws.services.ecs.model.TaskDefinition; +import io.floci.aws.services.lambda.launcher.ImageCacheService.LaunchImage; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.services.ssm.SsmService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * An awsvpc task reports its ENI address, so one of its containers has to hold that address on + * the VPC's Docker network. Peers that reach the task through Cloud Map or ELBv2 keep using the + * address on the network the container was created on. + */ +class EcsContainerManagerTaskAddressTest { + + private static final String REGION = "us-east-1"; + + private ContainerLifecycleManager lifecycleManager; + private DockerClient dockerClient; + private Ec2Service ec2Service; + private SecurityGroupFirewallManager firewallManager; + private ContainerBuilder containerBuilder; + private EcsContainerManager manager; + + @BeforeEach + void setUp() { + ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF); + containerBuilder = mock(ContainerBuilder.class); + when(containerBuilder.newContainer(anyString())).thenReturn(builder); + when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0)); + + lifecycleManager = mock(ContainerLifecycleManager.class); + when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) + .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); + when(lifecycleManager.createAndStartEphemeral(any(), any())) + .thenReturn(new ContainerInfo("sidecar-id", Map.of()), new ContainerInfo("web-id", Map.of())); + dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS); + when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + + ContainerDetector containerDetector = mock(ContainerDetector.class); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + RegionResolver regionResolver = mock(RegionResolver.class); + when(regionResolver.getAccountId()).thenReturn("000000000000"); + LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class); + when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of()); + EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class); + when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0)); + + ec2Service = mock(Ec2Service.class); + Subnet subnet = new Subnet(); + subnet.setSubnetId("subnet-1"); + subnet.setVpcId("vpc-1"); + when(ec2Service.describeSubnets(eq(REGION), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet)); + firewallManager = mock(SecurityGroupFirewallManager.class); + + manager = new EcsContainerManager( + containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), + containerDetector, config, regionResolver, awsEnv, + mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class), + ecrRegistryManager, mock(HostVolumePolicy.class), + ec2Service, firewallManager, + mock(EcsTaskRoleCredentials.class), mock(EcsCredentialsProxy.class), + new EcsTaskLinkLocalAddresses()); + } + + @Test + void awsvpcTaskGivesItsEniAddressToTheFirstContainerThatMapsAPort() { + manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc, + container("sidecar", List.of()), container("web", List.of(new PortMapping(80, 80, "tcp")))), + List.of(), REGION); + + verify(ec2Service).attachContainerToVpc(REGION, "vpc-1", "subnet-1", "web-id", "10.0.0.10"); + } + + @Test + void awsvpcTaskWithoutPortMappingsGivesItsEniAddressToItsFirstContainer() { + manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc, + container("sidecar", List.of()), container("web", List.of())), List.of(), REGION); + + verify(ec2Service).attachContainerToVpc(REGION, "vpc-1", "subnet-1", "sidecar-id", "10.0.0.10"); + } + + @Test + void bridgeTaskJoinsNoVpcNetwork() { + EcsTask task = new EcsTask(); + task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123"); + + manager.startTask(task, taskDefinition(NetworkMode.bridge, + container("web", List.of(new PortMapping(80, 80, "tcp")))), List.of(), REGION); + + verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any()); + } + + @Test + void securityGroupProtectedTaskKeepsItsOwnNamespace() { + when(firewallManager.enabled()).thenReturn(true); + when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any())) + .thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5")); + NetworkInterface eni = new NetworkInterface(); + eni.setNetworkInterfaceId("eni-1"); + eni.setVpcId("vpc-1"); + eni.setPrivateIpAddress("10.0.0.10"); + eni.setGroups(List.of(new GroupIdentifier("sg-1", "default"))); + when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any())) + .thenReturn(eni); + SecurityGroup sg = new SecurityGroup(); + sg.setGroupId("sg-1"); + when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any())).thenReturn(List.of(sg)); + EcsTask task = taskWithEni(); + task.setNetworkInterfaceId(null); + + manager.startTask(task, taskDefinition(NetworkMode.awsvpc, + container("web", List.of(new PortMapping(80, 80, "tcp")))), List.of(), REGION); + + assertEquals("eni-1", task.getNetworkInterfaceId()); + verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"bridge", "default"}) + void peerAddressStaysOnTheNetworkTheContainerWasCreatedOn(String networkMode) { + InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS); + when(inspect.getHostConfig()).thenReturn(new HostConfig().withNetworkMode(networkMode)); + Map networks = new LinkedHashMap<>(); + networks.put("floci-vpc-4566-us-east-1-vpc-1", new ContainerNetwork().withIpv4Address("10.0.0.10")); + networks.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.5")); + when(inspect.getNetworkSettings().getNetworks()).thenReturn(networks); + when(dockerClient.inspectContainerCmd("web-id").exec()).thenReturn(inspect); + Container container = new Container(); + container.setDockerId("web-id"); + + assertEquals(Optional.of("172.17.0.5"), manager.resolvePeerAddress(container)); + } + + @Test + void peerAddressPrefersTheNetworkEcsContainersJoin() { + when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of("floci-net")); + InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS); + // Created on the default bridge to publish its ports, then connected to Floci's network. + when(inspect.getHostConfig()).thenReturn(new HostConfig().withNetworkMode("default")); + Map networks = new LinkedHashMap<>(); + networks.put("bridge", new ContainerNetwork().withIpv4Address("172.17.0.5")); + networks.put("floci-net", new ContainerNetwork().withIpv4Address("172.20.0.5")); + when(inspect.getNetworkSettings().getNetworks()).thenReturn(networks); + when(dockerClient.inspectContainerCmd("web-id").exec()).thenReturn(inspect); + Container container = new Container(); + container.setDockerId("web-id"); + + assertEquals(Optional.of("172.20.0.5"), manager.resolvePeerAddress(container)); + } + + private static EcsTask taskWithEni() { + AwsVpcConfiguration awsvpc = new AwsVpcConfiguration(); + awsvpc.setSubnets(List.of("subnet-1")); + awsvpc.setSecurityGroups(List.of("sg-1")); + NetworkConfiguration network = new NetworkConfiguration(); + network.setAwsvpcConfiguration(awsvpc); + EcsTask task = new EcsTask(); + task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123"); + task.setNetworkConfiguration(network); + task.setNetworkInterfaceId("eni-1"); + task.setPrivateIpAddress("10.0.0.10"); + return task; + } + + private static ContainerDefinition container(String name, List ports) { + ContainerDefinition definition = new ContainerDefinition(); + definition.setName(name); + definition.setImage(name + ":latest"); + definition.setPortMappings(ports); + return definition; + } + + private static TaskDefinition taskDefinition(NetworkMode mode, ContainerDefinition... containers) { + TaskDefinition taskDef = new TaskDefinition(); + taskDef.setFamily("test-family"); + taskDef.setNetworkMode(mode); + taskDef.setContainerDefinitions(List.of(containers)); + return taskDef; + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java index 4f4b708f90..2eb460097b 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java @@ -255,7 +255,7 @@ class LambdaImageConfigTest { launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, mock(LambdaLayerService.class), awsEnv, - mock(LambdaExecutionRoleCredentials.class)); + mock(LambdaExecutionRoleCredentials.class), null); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java index 799fc38bb5..2ca32b0c8e 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCodeVolumeReuseTest.java @@ -68,7 +68,7 @@ class ContainerLauncherCodeVolumeReuseTest { mock(ImageResolver.class), mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class), mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class), - mock(LambdaExecutionRoleCredentials.class)); + mock(LambdaExecutionRoleCredentials.class), null); } @Override @@ -283,7 +283,7 @@ class ContainerLauncherCodeVolumeReuseTest { mock(ContainerLogStreamer.class), mock(ImageResolver.class), mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class), mock(LambdaLayerService.class), - mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class)); + mock(LaunchedContainerAwsEnv.class), mock(LambdaExecutionRoleCredentials.class), null); assertThrows(IllegalStateException.class, () -> real.populateCodeVolume("vol", fn("sha"), "img")); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java index 7e9a79526f..6b0141a88e 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherCopyRetryTest.java @@ -33,7 +33,7 @@ class ContainerLauncherCopyRetryTest { // no longer builds; the copy paths under test read nothing else from it. EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().lambda().codeVolumePopulateConcurrency()).thenReturn(Optional.empty()); - return new ContainerLauncher(null, null, null, null, null, null, config, null, null, null, null); + return new ContainerLauncher(null, null, null, null, null, null, config, null, null, null, null, null); } @Test diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java index a6efde673f..5320bb23c1 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java @@ -15,6 +15,7 @@ import com.github.dockerjava.api.model.MountType; import com.github.dockerjava.api.model.StreamType; import com.github.dockerjava.api.model.VersionComponent; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.dns.EmbeddedDnsServer; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerEngineDetector; @@ -26,6 +27,7 @@ import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver; import io.floci.aws.core.common.docker.DockerHostResolver; import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; +import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ecr.registry.EcrRegistryManager; import io.floci.aws.services.iam.model.SessionCreds; import io.floci.aws.services.lambda.LambdaLayerFixtures; @@ -49,6 +51,8 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; +import org.mockito.MockMakers; +import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; import java.io.ByteArrayInputStream; @@ -70,6 +74,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; import java.util.stream.Stream; import static io.floci.aws.testing.DockerDaemonVersionFixtures.stubDaemonVersion; @@ -101,6 +106,7 @@ class ContainerLauncherTest { @Mock DockerClient dockerClient; @Mock LambdaExecutionRoleCredentials executionRoleCredentials; @Mock LambdaLayerService layerService; + @Mock Ec2Service ec2Service; @TempDir Path tempDir; @@ -242,7 +248,7 @@ class ContainerLauncherTest { new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), lifecycleManager, logStreamer, imageResolver, runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, layers, - new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials); + new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service); LambdaFunction fn = new LambdaFunction(); fn.setFunctionName("background-layer"); fn.setFunctionArn("arn:aws:lambda:" + region + ":" + account + ":function:background-layer"); @@ -463,7 +469,7 @@ class ContainerLauncherTest { return new ContainerLauncher(builder, lifecycleManager, logStreamer, selectedResolver, runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, layerService, new LaunchedContainerAwsEnv(endpoint), - executionRoleCredentials); + executionRoleCredentials, ec2Service); } @ParameterizedTest @@ -854,7 +860,7 @@ class ContainerLauncherTest { // No populate helper is created/discarded for small code. verify(lifecycleManager, times(1)).create(any()); - verify(lifecycleManager, never()).stopAndRemove(any(), any()); + verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any()); // createAndStart must NOT be called — Lambda uses the split path verify(lifecycleManager, never()).createAndStart(any()); @@ -984,7 +990,7 @@ class ContainerLauncherTest { () -> launcher.launchProvisioned(fn)); assertTrue(error.getMessage().startsWith("Configured layer is unavailable for provisioned initialization:")); verify(lifecycleManager, never()).startCreated(anyString(), any()); - verify(lifecycleManager).stopAndRemove("container-123", null); + verify(lifecycleManager).stopAndRemoveStrict("container-123", null); verify(runtimeApiServerFactory).release(runtimeApiServer); verify(runtimeApiServer, never()).expectExtensions(anyInt()); verify(runtimeApiServer, never()).enqueue(any()); @@ -1258,7 +1264,7 @@ class ContainerLauncherTest { // No populate helper for small code. verify(lifecycleManager, times(1)).create(any()); - verify(lifecycleManager, never()).stopAndRemove(any(), any()); + verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any()); verify(lifecycleManager, never()).createAndStart(any()); } @@ -1407,6 +1413,140 @@ class ContainerLauncherTest { verify(executionRoleCredentials).unregister("222233334444", "ASIAFAILEDSESSION"); } + @Test + void vpcFunctionJoinsItsVpcNetworkBeforeStartAndReturnsTheAddressAfterRemoval() throws Exception { + LambdaFunction fn = vpcFunction("vpc-join-fn"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.20")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.20")) + .thenReturn(Optional.of("floci-vpc-1")); + + ContainerHandle handle = launcher.launch(fn); + verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any()); + launcher.stop(handle); + + InOrder order = inOrder(ec2Service, lifecycleManager); + order.verify(ec2Service).allocateVpcPrivateIp("us-east-1", "subnet-a"); + order.verify(ec2Service).attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", + "172.31.0.20"); + order.verify(lifecycleManager).startCreated(eq("container-123"), any()); + order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null, 1); + order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.20"); + } + + @Test + void vpcFunctionKeepsItsAddressUntilARetriedRemovalSucceeds() throws Exception { + LambdaFunction fn = vpcFunction("vpc-retry-fn"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.23")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.23")) + .thenReturn(Optional.of("floci-vpc-1")); + ContainerHandle handle = launcher.launch(fn); + doThrow(new RuntimeException("removal failed")).doNothing() + .when(lifecycleManager).stopAndRemoveStrict("container-123", null, 1); + + assertThrows(RuntimeException.class, () -> launcher.stop(handle)); + verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any()); + + launcher.stop(handle); + verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.23"); + } + + @Test + void vpcFunctionReturnsTheAddressOnceAFailedLaunchRemovesItsContainer() throws Exception { + LambdaFunction fn = vpcFunction("vpc-launch-failure-fn"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.21")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.21")) + .thenReturn(Optional.of("floci-vpc-1")); + doThrow(new RuntimeException("start failed")).when(lifecycleManager).startCreated(eq("container-123"), any()); + + assertThrows(RuntimeException.class, () -> launcher.launch(fn)); + + InOrder order = inOrder(lifecycleManager, ec2Service); + order.verify(lifecycleManager).stopAndRemoveStrict("container-123", null); + order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.21"); + } + + @Test + void vpcFunctionKeepsTheAddressWhenAFailedLaunchCannotRemoveItsContainer() throws Exception { + LambdaFunction fn = vpcFunction("vpc-launch-removal-failure-fn"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.24")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.24")) + .thenReturn(Optional.of("floci-vpc-1")); + doThrow(new RuntimeException("start failed")).when(lifecycleManager).startCreated(eq("container-123"), any()); + doThrow(new IllegalStateException("removal failed")) + .when(lifecycleManager).stopAndRemoveStrict("container-123", null); + + assertThrows(RuntimeException.class, () -> launcher.launch(fn)); + + verify(ec2Service, never()).releaseVpcPrivateIp(any(), any(), any()); + } + + @Test + void vpcFunctionReturnsTheAddressAtOnceWhenItCannotJoinTheNetwork() throws Exception { + LambdaFunction fn = vpcFunction("vpc-attach-failure-fn"); + when(ec2Service.allocateVpcPrivateIp("us-east-1", "subnet-a")).thenReturn(Optional.of("172.31.0.22")); + when(ec2Service.attachContainerToVpc("us-east-1", "vpc-1", "subnet-a", "container-123", "172.31.0.22")) + .thenReturn(Optional.empty()); + + ContainerHandle handle = launcher.launch(fn); + launcher.stop(handle); + + InOrder order = inOrder(ec2Service, lifecycleManager); + order.verify(ec2Service).releaseVpcPrivateIp("us-east-1", "subnet-a", "172.31.0.22"); + order.verify(lifecycleManager).startCreated(eq("container-123"), any()); + verify(ec2Service, times(1)).releaseVpcPrivateIp(any(), any(), any()); + } + + @Test + void vpcFunctionLeasesItsAddressInTheFunctionsAccountOutsideARequest() throws Exception { + // A provisioned or cross-account launch has no caller scope of the function's owner, and + // the allocator reads the owner's endpoint interfaces from the ambient account. + LambdaFunction fn = vpcFunction("vpc-account-fn"); + fn.setFunctionArn("arn:aws:lambda:eu-west-1:222233334444:function:vpc-account-fn"); + AtomicBoolean inOwnerScope = new AtomicBoolean(); + when(ec2Service.allocateVpcPrivateIp("eu-west-1", "subnet-a")) + .thenAnswer(invocation -> inOwnerScope.get() ? Optional.of("172.31.0.25") : Optional.empty()); + when(ec2Service.attachContainerToVpc("eu-west-1", "vpc-1", "subnet-a", "container-123", "172.31.0.25")) + .thenReturn(Optional.of("floci-vpc-1")); + try (MockedStatic scopes = + mockStatic(RequestScopes.class, withSettings().mockMaker(MockMakers.INLINE))) { + scopes.when(() -> RequestScopes.callAs(eq("222233334444"), eq("eu-west-1"), any(Supplier.class))) + .thenAnswer(invocation -> { + inOwnerScope.set(true); + try { + return invocation.>getArgument(2).get(); + } finally { + inOwnerScope.set(false); + } + }); + + launcher.launch(fn); + } + + verify(ec2Service).attachContainerToVpc("eu-west-1", "vpc-1", "subnet-a", "container-123", "172.31.0.25"); + } + + @Test + void functionWithoutVpcConfigNeverCallsEc2() throws Exception { + LambdaFunction fn = vpcFunction("no-vpc-fn"); + fn.setVpcId(null); + fn.setVpcConfig(null); + + launcher.stop(launcher.launch(fn)); + + verifyNoInteractions(ec2Service); + } + + private LambdaFunction vpcFunction(String name) throws IOException { + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName(name); + fn.setRuntime("nodejs20.x"); + fn.setHandler("index.handler"); + fn.setCodeLocalPath(Files.createDirectory(tempDir.resolve(name)).toString()); + fn.setVpcId("vpc-1"); + fn.setVpcConfig(Map.of("SubnetIds", List.of("subnet-a", "subnet-b"), "SecurityGroupIds", List.of("sg-1"))); + return fn; + } + @Test void publishedVersionUnregistersUnderTheAccountItRegisteredWith() throws Exception { // A published version has no accountId, so both the handle stamp and the revoke must take @@ -1552,7 +1692,7 @@ class ContainerLauncherTest { verify(lifecycleManager, times(2)).create(any()); verify(lifecycleManager, atLeastOnce()).ensureVolume(any()); verify(lifecycleManager).stopAndRemove("helper-123", null, 0); - verify(lifecycleManager, never()).stopAndRemove(any(), any()); + verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any()); InOrder order = inOrder(lifecycleManager); order.verify(lifecycleManager).stopAndRemove("helper-123", null, 0); order.verify(lifecycleManager).create(any()); @@ -1587,7 +1727,7 @@ class ContainerLauncherTest { order.verify(dockerClient).copyArchiveToContainerCmd("helper-123"); order.verify(lifecycleManager).stopAndRemove("helper-123", null, 0); verify(lifecycleManager, times(1)).create(any()); - verify(lifecycleManager, never()).stopAndRemove(any(), any()); + verify(lifecycleManager, never()).stopAndRemoveStrict(any(), any()); verify(lifecycleManager, never()).removeVolume(any()); verify(runtimeApiServerFactory).release(runtimeApiServer); assertFalse(Files.exists(tempDir.resolve("lambda-codevol-markers") @@ -2259,7 +2399,7 @@ class ContainerLauncherTest { ecrRegistryManager, mock(LambdaLayerService.class), new LaunchedContainerAwsEnv(reachableEndpoint), - executionRoleCredentials); + executionRoleCredentials, ec2Service); stubExtensionDiscovery("otel-collector"); // Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.