fix(ec2): skip addresses stored resources hold when the VPC network allocates (#6284)

* fix(ec2): skip addresses stored resources hold when the VPC network allocates

The VPC network's allocator reads only its lease table, but a launch that
names an address while a failed launch is still giving it back keeps the
address without a lease, and so does a network interface created with its
own address. assignPrivateIp now asks for another address while the one it
got is held by a stored instance, network interface or NAT gateway in any
account, so a later launch's Docker attach no longer fails on an address
that is already in use. The addresses it walks past are given back once it
is done, since their holders took no lease of their own.

Closes #6283

* fix(ec2): keep the fallback off addresses the VPC network walk skipped

When the walk past held addresses runs the Docker-backed allocator dry,
the synthesised fallback checked only the caller's account, so on a shared
default subnet it could hand out the address another account's resource
holds. It now skips the addresses the walk found held as well.

* test(ec2): share the mocked-network and RequestContext setup in Ec2ServiceTest

requestContexts builds the RequestContext CDI mock that four helpers and
tests each built for themselves, and mockedVpcNetworkService replaces the
mock-mode new Ec2Service(..., vpcNetworks) the private-address tests
repeated. The comment on why jakarta.enterprise.inject.Instance is written
out in full lives in requestContexts.
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-10-22 22:33:30 -04:00
1 parent 95387d1906
commit d3c2dbb1d9
4 files changed
+173 -27

No files matched your search

+4
View File
@@ -1155,6 +1155,10 @@ network per subnet would manufacture a partition AWS does not have. Per-subnet a
anyway: the network's IPAM pool is the whole VPC CIDR and each subnet allocates static addresses
out of its own slice of it.
An address a subnet picks on its own is never one that an instance, network interface or NAT
gateway in the subnet already holds. Default subnet ids are the same in every account, so those
subnets share a network, and what any account holds there counts.
The declared CIDR is used verbatim whenever it can be. It cannot be when it is absent, malformed,
outside RFC 1918, or already claimed on the Docker daemon, including by another Floci VPC, since
two VPCs may legally declare the same CIDR in AWS but one daemon cannot route two identical
@@ -4203,6 +4203,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
/**
* Callers must hold {@link #privateIpAllocationLock}, so an address found free here cannot be
* taken before the resource it is handed to is stored.
*
* @param pending addresses already handed out to resources that are not stored yet, which the
* synthesised fallback must not hand out again
*/
@@ -4210,8 +4213,26 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// A Docker-backed subnet allocates the real thing: an address on the network the
// instance's container will actually hold. Only when there is no such network does
// this fall back to the synthesised address below, which nothing can connect to.
Set<String> held = Set.of();
if (vpcNetworkManager != null) {
Optional<String> allocated = vpcNetworkManager.allocatePrivateIp(region, subnetId);
// The network's lease table is not the whole story: an interface created with its
// own address never takes a lease, and a launch that names an address while a
// failed launch is still giving it back keeps it without one.
if (allocated.isPresent()) {
held = privateIpsHeldOnVpcNetwork(region, subnetId);
}
List<String> 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 or NAT gateway returns none, so a
// lease kept here would outlive the holder.
for (String address : skipped) {
vpcNetworkManager.releasePrivateIp(region, subnetId, address);
}
if (allocated.isPresent()) {
return allocated.get();
}
@@ -4232,6 +4253,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// cursor, never hands out an address that is still in use.
Set<String> inUse = privateIpsTaken(region, subnetId);
inUse.addAll(pending);
// A walk that ran the network dry skipped only held addresses, other accounts' among
// them, so none of those is handed out here instead.
inUse.addAll(held);
long start = Math.clamp(subnetIpCursors.getOrDefault(cursorKey, SYNTHETIC_FIRST_OFFSET), first, last);
long span = last - first + 1;
for (long step = 0; step < span; step++) {
@@ -4291,10 +4315,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* account's instance, network interface or NAT gateway there may hold the address with no
* 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 is stale
* (DeleteNetworkInterface and DeleteNatGateway never return theirs) and does not fail the
* launch, and 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.
* wider scan finds nothing more. A lease with nothing in any account behind it does not fail
* the launch: it is stale (DeleteNetworkInterface and DeleteNatGateway never return theirs),
* 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.
* 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.
*/
private void claimRequestedPrivateIp(String region, String subnetId, String address) {
if (privateIpsTaken(region, subnetId).contains(address)) {
@@ -4324,6 +4351,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.getOrDefault(subnetId, Set.of());
}
/**
* Every address a stored resource holds in the subnet: {@link #privateIpsTaken}, plus what the
* instances, network interfaces and NAT gateways of every account hold there. Default subnet
* ids are the same in every account, so their Docker network, and its lease table, is shared.
*/
private Set<String> privateIpsHeldOnVpcNetwork(String region, String subnetId) {
Set<String> held = privateIpsTaken(region, subnetId);
held.addAll(privateIpsInUseInEveryAccount(region, subnetId));
return held;
}
private static <T> List<T> valuesOfEveryAccount(StorageBackend<String, T> store, String keyPrefix) {
return entriesOfEveryAccount(store).stream()
.filter(entry -> entry.key().startsWith(keyPrefix))
@@ -476,7 +476,8 @@ public class VpcNetworkManager {
*
* <p>Unlike {@link #reservePrivateIp}, it leaves the allocation cursor where it is, so the
* addresses the subnet picks on its own keep their order, and it logs no refusal: the caller
* has already found the address free, so a lease it meets is one its holder never returned.
* has already found the address free, so a lease it meets is one its holder never returned,
* or one a failed launch returns only once its container is detached.
*
* @return true when the address is now leased; false when the subnet has no Docker-backed
* range, the address is unparseable or outside that range, or it is already leased
@@ -3941,9 +3941,7 @@ class Ec2ServiceTest {
@Test
void aRequestedPrivateIpIsLeasedOnTheVpcNetworkInsteadOfTheNextFreeAddress() {
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks);
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
String subnetId = privateIpSubnet(service);
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.50.1.0/24"));
when(vpcNetworks.claimPrivateIp("us-east-1", subnetId, "10.50.1.50")).thenReturn(true);
@@ -4061,10 +4059,7 @@ class Ec2ServiceTest {
defaultSubnetInstance("i-other", "172.31.0.50", InstanceState.running()));
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.240.0.0/20"));
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-instances.json", instanceStore)), vpcNetworks);
Ec2Service service = mockedVpcNetworkService(Map.of("ec2-instances.json", instanceStore), vpcNetworks);
assertEquals("172.31.0.50", launchWithPrivateIp(service, subnetId, 1, "172.31.0.50")
.getInstances().getFirst().getPrivateIpAddress());
@@ -4098,9 +4093,7 @@ class Ec2ServiceTest {
@Test
void aDryRunWithARequestedPrivateIpLeasesNothing() {
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(), vpcNetworks);
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
String subnetId = privateIpSubnet(service);
AwsException dryRun = assertThrows(AwsException.class,
@@ -4113,6 +4106,91 @@ class Ec2ServiceTest {
assertTrue(instancesIn(service, subnetId).isEmpty());
}
@Test
void anAddressAnInterfaceWasCreatedWithIsNotHandedOutByTheRealVpcNetwork() {
// CreateNetworkInterface with its own address takes no lease, and the network's allocator
// reads only its lease table, so it would hand a fresh /24's first address, offset 10, to
// the next launch as well.
Ec2Service service = realVpcNetworkService(new RequestContext());
String subnetId = privateIpSubnet(service);
service.createNetworkInterface("us-east-1", subnetId, "holder", "10.50.1.10",
List.of(), List.of(), List.of());
assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1));
}
@Test
void anAddressAnotherAccountsInterfaceWasCreatedWithIsNotHandedOutOnASharedVpcNetwork() {
// Default subnet ids are the same in every account, so their Docker network is shared, and
// only the other account's stored interface says its address is held.
RequestContext context = new RequestContext();
Ec2Service service = realVpcNetworkService(context);
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
context.setAccountId("111122223333");
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());
context.setAccountId("000000000000");
assertEquals(List.of("172.31.0.11"), launchAddresses(service, subnetId, 1));
}
@Test
void anAddressTheWalkSkipsIsGivenBackToTheVpcNetwork() {
// Its holder took no lease, and deleting an interface or NAT gateway returns none, so a
// lease the walk kept would outlive the holder.
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
String subnetId = privateIpSubnet(service);
service.createNetworkInterface("us-east-1", subnetId, "holder", "10.50.1.10",
List.of(), List.of(), List.of());
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
.thenReturn(Optional.of("10.50.1.10"), Optional.of("10.50.1.11"), Optional.empty());
assertEquals(List.of("10.50.1.11"), launchAddresses(service, subnetId, 1));
verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "10.50.1.10");
verify(vpcNetworks, never()).releasePrivateIp("us-east-1", subnetId, "10.50.1.11");
}
@Test
void anAddressAnotherAccountHoldsIsNotHandedOutWhenTheWalkRunsTheNetworkDry() {
// The walk skips the only address the shared network still offers, which another account's
// interface holds, and the synthesised fallback's own scan sees only the caller's account.
RequestContext context = new RequestContext();
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = mockedVpcNetworkService(context, Map.of(), vpcNetworks);
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
context.setAccountId("111122223333");
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.empty());
context.setAccountId("000000000000");
assertEquals(List.of("172.31.0.11"), launchAddresses(service, subnetId, 1));
}
@Test
void anAddressALaunchNamedWithoutLeasingItIsNotHandedOutAgain() {
// A failed launch is marked terminated before its container is detached and its lease given
// back. A launch that names the address in between finds nothing holding it and keeps it
// although the lease is refused, and the late release then leaves the network offering an
// address that launch's instance holds.
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
String subnetId = privateIpSubnet(service);
when(vpcNetworks.effectiveSubnetCidr("us-east-1", subnetId)).thenReturn(Optional.of("10.50.1.0/24"));
when(vpcNetworks.claimPrivateIp("us-east-1", subnetId, "10.50.1.50")).thenReturn(false);
launchWithPrivateIp(service, subnetId, 1, "10.50.1.50");
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
.thenReturn(Optional.of("10.50.1.50"), Optional.of("10.50.1.51"), Optional.empty());
assertEquals(List.of("10.50.1.51"), launchAddresses(service, subnetId, 1));
}
private static String privateIpSubnet(Ec2Service service) {
String vpcId = service.createVpc("us-east-1", "10.50.0.0/16", false).getVpcId();
return service.createSubnet("us-east-1", vpcId, "10.50.1.0/24", "us-east-1a").getSubnetId();
@@ -4146,15 +4224,46 @@ class Ec2ServiceTest {
when(docker.listNetworksCmd()).thenReturn(listNetworks);
AmiImageResolver images = mock(AmiImageResolver.class);
when(images.resolveImage(any())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest"));
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<RequestContext> contexts = mock(jakarta.enterprise.inject.Instance.class);
when(contexts.isResolvable()).thenReturn(true);
when(contexts.get()).thenReturn(context);
jakarta.enterprise.inject.Instance<RequestContext> 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);
}
/** Ec2Service in mock mode over {@code vpcNetworks}, called as the default account. */
private static Ec2Service mockedVpcNetworkService(VpcNetworkManager vpcNetworks) {
return mockedVpcNetworkService(Map.of(), vpcNetworks);
}
/** {@link #mockedVpcNetworkService(VpcNetworkManager)}, with {@code stores} in place of the stores they name. */
private static Ec2Service mockedVpcNetworkService(Map<String, AccountAwareStorageBackend<?>> stores,
VpcNetworkManager vpcNetworks) {
return mockedVpcNetworkService(new RequestContext(), stores, vpcNetworks);
}
/**
* Ec2Service in mock mode over {@code vpcNetworks}, with the caller's account taken from
* {@code context} and {@code stores} in place of the stores they name.
*/
private static Ec2Service mockedVpcNetworkService(RequestContext context,
Map<String, AccountAwareStorageBackend<?>> stores,
VpcNetworkManager vpcNetworks) {
jakarta.enterprise.inject.Instance<RequestContext> contexts = requestContexts(context);
return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(stores, contexts), contexts, vpcNetworks, null, null, null);
}
/** The request-scoped RequestContext as CDI hands it out, resolving to {@code context}. */
@SuppressWarnings("unchecked")
private static jakarta.enterprise.inject.Instance<RequestContext> requestContexts(RequestContext context) {
// jakarta.enterprise.inject.Instance is written out because this file imports the model's Instance.
jakarta.enterprise.inject.Instance<RequestContext> contexts = mock(jakarta.enterprise.inject.Instance.class);
when(contexts.isResolvable()).thenReturn(true);
when(contexts.get()).thenReturn(context);
return contexts;
}
private static Instance defaultSubnetInstance(String instanceId, String privateIp, InstanceState state) {
Instance instance = persistedInstance(instanceId, privateIp, state);
instance.setVpcId(Ec2Service.defaultVpcId("us-east-1"));
@@ -8280,11 +8389,8 @@ class Ec2ServiceTest {
}
};
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = mock(jakarta.enterprise.inject.Instance.class);
RequestContext reqCtx = new RequestContext();
when(reqCtxInstance.isResolvable()).thenReturn(true);
when(reqCtxInstance.get()).thenReturn(reqCtx);
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = requestContexts(reqCtx);
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(reqCtxInstance);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
@@ -8350,12 +8456,9 @@ class Ec2ServiceTest {
}
};
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = mock(jakarta.enterprise.inject.Instance.class);
RequestContext reqCtx = new RequestContext();
reqCtx.setAccountId(accountA);
when(reqCtxInstance.isResolvable()).thenReturn(true);
when(reqCtxInstance.get()).thenReturn(reqCtx);
jakarta.enterprise.inject.Instance<RequestContext> reqCtxInstance = requestContexts(reqCtx);
InMemoryStorageFactory storageFactory = new InMemoryStorageFactory(reqCtxInstance);
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),