mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): give each account's VPC its own Docker network (#8598)
VpcNetworkManager keyed its VPC bindings, subnets and Docker networks by Region and id alone, and every account's default VPC and subnets share one id (vpc-default-<region>), so two accounts' default VPCs shared one binding, one Docker network and one lease table: EC2 instances, Lambda functions, ECS tasks, EKS nodes and the MWAA, CodeBuild and Batch containers of two accounts landed on the same bridge. Ec2Service worked around the shared lease table by counting every account's resources as holding the subnet's addresses. - VpcNetworkManager takes the account on every call and keys bindings and subnets by account, Region and id. A network carries the account in its labels and, for any account but the default one, in its name; the default account's keeps the name it always had, so its live networks outlive the upgrade. A surviving network of another account's VPC of the same id is a collision, as another Region's is. - Startup reconciliation asks which accounts declare a VPC of an id in a Region (DeclaredVpcs). A labelled network is kept while its account declares the VPC; one an older version labelled with no account belongs to the account declaring its VPC, the default account first, and a non-default account's VPC keeps using that account-less network, so its live containers stay attached across the upgrade. - Ec2Service passes the caller's account, and the restore each stored VPC's, subnet's and instance's own. The helpers other services call (allocate, reserve, release, attach, detach) take the owning account and run as it, as a caller may run outside the owner's request: a provisioned or cross-account Lambda launch, a container removed in the background. Lambda, ECS, EKS and VpcContainerLeases (MWAA, CodeBuild, Batch) pass the account they already hold; Lambda's and EKS's leases carry it to their release. - An address is held by the caller's account's resources alone, as its network and lease table are its own: the every-account holding check goes, and the container lease map is keyed by account. VpcNetworkManagerTest covers two accounts' default VPCs getting a network each (the second's identical CIDR substituted), another account's surviving network as a collision, a labelled network kept only while its account declares the VPC, and an older version's unlabelled network kept and adopted for the account declaring it. Ec2ServiceTest's cross-account tests now pin the per-account holding. ec2.md says so.
This commit is contained in:
1 parent
06a5ce4219
commit
bb6b308fdb
20 files changed
+776
-649
No files matched your search
@@ -502,7 +502,7 @@ public class Ec2ContainerManager {
|
||||
// Nothing holds the address, and moments from now this instance will be
|
||||
// reporting its bridge address instead, so the lease would no longer be
|
||||
// findable from the instance at terminate time. Give it back here.
|
||||
vpcNetworkManager.releasePrivateIp(region, instance.getSubnetId(), leasedPrivateIp);
|
||||
vpcNetworkManager.releasePrivateIp(instance.getOwnerId(), region, instance.getSubnetId(), leasedPrivateIp);
|
||||
}
|
||||
|
||||
if (isLaunchCancelled(instance)) {
|
||||
@@ -701,7 +701,7 @@ public class Ec2ContainerManager {
|
||||
// default bridge attachment stays: it is what carries the published SSH host
|
||||
// port, which a network mode set at creation time would suppress.
|
||||
String vpcAddress = namespace == null
|
||||
? vpcNetworkManager.attach(region, instance.getVpcId(), instance.getSubnetId(),
|
||||
? vpcNetworkManager.attach(instance.getOwnerId(), region, instance.getVpcId(), instance.getSubnetId(),
|
||||
containerId, leasedPrivateIp).map(network -> leasedPrivateIp).orElse(null)
|
||||
: null;
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
@@ -858,8 +858,8 @@ public class Ec2ContainerManager {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
vpcNetworkManager.detach(instance.getRegion(), instance.getVpcId(), containerId);
|
||||
vpcNetworkManager.releasePrivateIp(instance.getRegion(), instance.getSubnetId(), leasedPrivateIp);
|
||||
vpcNetworkManager.detach(instance.getOwnerId(), instance.getRegion(), instance.getVpcId(), containerId);
|
||||
vpcNetworkManager.releasePrivateIp(instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(), leasedPrivateIp);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error releasing the VPC address of failed EC2 launch {0}: {1}",
|
||||
instance.getInstanceId(), e.getMessage());
|
||||
@@ -1674,7 +1674,7 @@ public class Ec2ContainerManager {
|
||||
// Give the address back only now that the container is gone: releasing it while
|
||||
// Docker still holds the endpoint would hand the same IP to the next launch and
|
||||
// have Docker refuse it.
|
||||
vpcNetworkManager.releasePrivateIp(instance.getRegion(), instance.getSubnetId(),
|
||||
vpcNetworkManager.releasePrivateIp(instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(),
|
||||
instance.getPrivateIpAddress());
|
||||
instance.setState(InstanceState.terminated());
|
||||
instance.setTerminatedAt(System.currentTimeMillis());
|
||||
|
||||
@@ -350,7 +350,7 @@ 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<String, Long> subnetIpCursors = new HashMap<>();
|
||||
// region::subnetId → addresses allocateVpcPrivateIp leased to containers no stored resource
|
||||
// account::region::subnetId → addresses allocateVpcPrivateIp leased to containers no stored resource
|
||||
// stands behind; guarded by privateIpAllocationLock.
|
||||
private final Map<String, Set<String>> containerPrivateIps = new HashMap<>();
|
||||
// Held from a synthesised address being chosen until the resource holding it is persisted, so
|
||||
@@ -417,71 +417,96 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
public boolean attachContainerToVpc(String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager != null) {
|
||||
return vpcNetworkManager.attachContainer(region, vpcId, containerId);
|
||||
/*
|
||||
* The VPC helpers other services call take the account owning the VPC and run as it: an account's VPC network
|
||||
* is its own, two accounts' default VPCs sharing one id, and a caller may run outside the owner's request
|
||||
* (a provisioned or cross-account Lambda launch, a container removed in the background).
|
||||
*/
|
||||
|
||||
public boolean attachContainerToVpc(String accountId, String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager == null) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
return RequestScopes.callAs(accountId, region,
|
||||
() -> vpcNetworkManager.attachContainer(callerAccountId(), region, vpcId, containerId));
|
||||
}
|
||||
|
||||
/** Attaches a container to the VPC's Docker network at {@code address}; empty when it stays off it. */
|
||||
public Optional<String> attachContainerToVpc(String region, String vpcId, String subnetId,
|
||||
public Optional<String> attachContainerToVpc(String accountId, String region, String vpcId, String subnetId,
|
||||
String containerId, String address) {
|
||||
if (vpcNetworkManager == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return vpcNetworkManager.attach(region, vpcId, subnetId, containerId, address);
|
||||
return RequestScopes.callAs(accountId, region, () -> vpcNetworkManager.attach(callerAccountId(), 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<String> allocateVpcPrivateIp(String region, String subnetId) {
|
||||
public Optional<String> allocateVpcPrivateIp(String accountId, String region, String subnetId) {
|
||||
if (vpcNetworkManager == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
Optional<String> 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;
|
||||
}
|
||||
return RequestScopes.callAs(accountId, region, () -> {
|
||||
synchronized (privateIpAllocationLock) {
|
||||
Optional<String> allocated = vpcNetworkManager.allocatePrivateIp(callerAccountId(), region, subnetId)
|
||||
.flatMap(first -> leaseNotHeld(region, subnetId, first,
|
||||
privateIpsHeldOnVpcNetwork(region, subnetId)));
|
||||
allocated.ifPresent(address -> containerPrivateIps
|
||||
.computeIfAbsent(containerKey(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 void releaseVpcPrivateIp(String accountId, String region, String subnetId, String address) {
|
||||
RequestScopes.runAs(accountId, region, () -> {
|
||||
synchronized (privateIpAllocationLock) {
|
||||
containerPrivateIps.computeIfPresent(containerKey(region, subnetId), (ignored, addresses) -> {
|
||||
addresses.remove(address);
|
||||
return addresses.isEmpty() ? null : addresses;
|
||||
});
|
||||
releasePrivateIps(region, subnetId, List.of(address));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-claims a Docker-backed subnet address a persisted container (such as an EKS cluster node)
|
||||
* already holds across a restart.
|
||||
*/
|
||||
public boolean reserveVpcPrivateIp(String region, String subnetId, String address) {
|
||||
public boolean reserveVpcPrivateIp(String accountId, String region, String subnetId, String address) {
|
||||
if (vpcNetworkManager == null || subnetId == null || address == null) {
|
||||
return false;
|
||||
}
|
||||
synchronized (privateIpAllocationLock) {
|
||||
if (!vpcNetworkManager.reservePrivateIp(region, subnetId, address)) {
|
||||
return false;
|
||||
return RequestScopes.callAs(accountId, region, () -> {
|
||||
synchronized (privateIpAllocationLock) {
|
||||
if (!vpcNetworkManager.reservePrivateIp(callerAccountId(), region, subnetId, address)) {
|
||||
return false;
|
||||
}
|
||||
containerPrivateIps.computeIfAbsent(containerKey(region, subnetId), ignored -> new HashSet<>())
|
||||
.add(address);
|
||||
return true;
|
||||
}
|
||||
containerPrivateIps.computeIfAbsent(key(region, subnetId), ignored -> new HashSet<>()).add(address);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public void detachContainerFromVpc(String accountId, String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager != null) {
|
||||
RequestScopes.runAs(accountId, region,
|
||||
() -> vpcNetworkManager.detach(callerAccountId(), region, vpcId, containerId));
|
||||
}
|
||||
}
|
||||
|
||||
public void detachContainerFromVpc(String region, String vpcId, String containerId) {
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.detach(region, vpcId, containerId);
|
||||
}
|
||||
/** The key of a subnet's container addresses: the caller's account, then the subnet's key. */
|
||||
private String containerKey(String region, String subnetId) {
|
||||
return callerAccountId() + "::" + key(region, subnetId);
|
||||
}
|
||||
|
||||
private String accountOrDefault(String accountId) {
|
||||
return accountId == null ? defaultAccountId : accountId;
|
||||
}
|
||||
|
||||
public boolean isVpcNetworkEnabled() {
|
||||
@@ -1215,7 +1240,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (vpcNetworkManager == null || !vpcNetworkManager.enabled()) {
|
||||
return;
|
||||
}
|
||||
vpcNetworkManager.reconcileOrphans((region, vpcId) -> findAnyVpcEntry(region, vpcId).isPresent());
|
||||
Map<String, Set<String>> declaringAccounts = new HashMap<>();
|
||||
for (AccountAwareStorageBackend.AccountEntry<Vpc> entry : entriesOfEveryAccount(vpcs)) {
|
||||
declaringAccounts.computeIfAbsent(key(entry.value().getRegion(), entry.value().getVpcId()),
|
||||
ignored -> new HashSet<>()).add(accountOrDefault(entry.accountId()));
|
||||
}
|
||||
vpcNetworkManager.reconcileOrphans((region, vpcId) ->
|
||||
declaringAccounts.getOrDefault(key(region, vpcId), Set.of()));
|
||||
// declareVpc is first-wins on overlapping CIDRs, so declare in a stable order, default account first.
|
||||
List<AccountAwareStorageBackend.AccountEntry<Vpc>> restoredVpcs = new ArrayList<>(entriesOfEveryAccount(vpcs));
|
||||
restoredVpcs.sort(Comparator
|
||||
@@ -1224,11 +1255,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
.thenComparing(AccountAwareStorageBackend.AccountEntry::key));
|
||||
for (AccountAwareStorageBackend.AccountEntry<Vpc> entry : restoredVpcs) {
|
||||
Vpc vpc = entry.value();
|
||||
vpcNetworkManager.declareVpc(vpc.getRegion(), vpc.getVpcId(), vpc.getCidrBlock());
|
||||
vpcNetworkManager.declareVpc(accountOrDefault(entry.accountId()), vpc.getRegion(), vpc.getVpcId(),
|
||||
vpc.getCidrBlock());
|
||||
}
|
||||
for (AccountAwareStorageBackend.AccountEntry<Subnet> entry : entriesOfEveryAccount(subnets)) {
|
||||
Subnet subnet = entry.value();
|
||||
vpcNetworkManager.declareSubnet(
|
||||
vpcNetworkManager.declareSubnet(accountOrDefault(entry.accountId()),
|
||||
subnet.getRegion(), subnet.getVpcId(), subnet.getSubnetId(), subnet.getCidrBlock());
|
||||
}
|
||||
reserveRestoredPrivateIps();
|
||||
@@ -1257,7 +1289,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|| "terminated".equals(instance.getState().getName())) {
|
||||
continue;
|
||||
}
|
||||
if (vpcNetworkManager.reservePrivateIp(instance.getRegion(), instance.getSubnetId(),
|
||||
if (vpcNetworkManager.reservePrivateIp(accountOrDefault(entry.accountId()), instance.getRegion(),
|
||||
instance.getSubnetId(),
|
||||
instance.getPrivateIpAddress())) {
|
||||
reserved++;
|
||||
}
|
||||
@@ -1467,13 +1500,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
private void declareVpcNetwork(String region, String vpcId, String cidrBlock) {
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.declareVpc(region, vpcId, cidrBlock);
|
||||
vpcNetworkManager.declareVpc(callerAccountId(), region, vpcId, cidrBlock);
|
||||
}
|
||||
}
|
||||
|
||||
private void declareSubnetNetwork(String region, String vpcId, String subnetId, String cidrBlock) {
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.declareSubnet(region, vpcId, subnetId, cidrBlock);
|
||||
vpcNetworkManager.declareSubnet(callerAccountId(), region, vpcId, subnetId, cidrBlock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4700,7 +4733,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
List<String> skipped = new ArrayList<>();
|
||||
while (allocated.isPresent() && held.contains(allocated.get())) {
|
||||
skipped.add(allocated.get());
|
||||
allocated = vpcNetworkManager.allocatePrivateIp(region, subnetId);
|
||||
allocated = vpcNetworkManager.allocatePrivateIp(callerAccountId(), 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.
|
||||
@@ -4717,7 +4750,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return;
|
||||
}
|
||||
for (String address : addresses) {
|
||||
vpcNetworkManager.releasePrivateIp(region, subnetId, address);
|
||||
vpcNetworkManager.releasePrivateIp(callerAccountId(), region, subnetId, address);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4734,7 +4767,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// 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);
|
||||
Optional<String> allocated = vpcNetworkManager.allocatePrivateIp(callerAccountId(), 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.
|
||||
@@ -4835,7 +4868,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
*/
|
||||
private void claimRequestedPrivateIp(String region, String subnetId, String address) {
|
||||
if (requireRequestedPrivateIpFree(region, subnetId, address)) {
|
||||
vpcNetworkManager.claimPrivateIp(region, subnetId, address);
|
||||
vpcNetworkManager.claimPrivateIp(callerAccountId(), region, subnetId, address);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4855,45 +4888,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (vpcNetworkManager == null || subnetId == null) {
|
||||
return false;
|
||||
}
|
||||
boolean leasable = vpcNetworkManager.effectiveSubnetCidr(region, subnetId)
|
||||
return vpcNetworkManager.effectiveSubnetCidr(callerAccountId(), region, subnetId)
|
||||
.filter(cidr -> Ipv4Cidrs.contains(cidr, address + "/32"))
|
||||
.isPresent();
|
||||
if (!leasable) {
|
||||
return false;
|
||||
}
|
||||
if (privateIpsInUseInEveryAccount(region, subnetId).contains(address)) {
|
||||
throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** {@link #privateIpsInUse}, across every account rather than only the caller's. */
|
||||
private Set<String> privateIpsInUseInEveryAccount(String region, String subnetId) {
|
||||
String regionPrefix = region + "::";
|
||||
return privateIpsBySubnet(valuesOfEveryAccount(networkInterfaces, regionPrefix),
|
||||
valuesOfEveryAccount(instances, regionPrefix),
|
||||
valuesOfEveryAccount(natGateways, regionPrefix),
|
||||
valuesOfEveryAccount(instanceConnectEndpoints, regionPrefix))
|
||||
.getOrDefault(subnetId, Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Every address a stored resource holds in the subnet: {@link #privateIpsTaken}, plus what the
|
||||
* instances, network interfaces, NAT gateways and EC2 Instance Connect Endpoints of every
|
||||
* account hold there. Default subnet ids are the same in every account, so their Docker
|
||||
* network, and its lease table, is shared.
|
||||
* Every address a stored resource of the caller's account holds in the subnet,
|
||||
* {@link #privateIpsTaken}: its VPC network, and that network's lease table, are the account's
|
||||
* own, even for the default subnets whose ids every account shares.
|
||||
*/
|
||||
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))
|
||||
.map(AccountAwareStorageBackend.AccountEntry::value)
|
||||
.toList();
|
||||
return privateIpsTaken(region, subnetId);
|
||||
}
|
||||
|
||||
private static AwsException insufficientFreeAddresses(String subnetId) {
|
||||
@@ -4929,10 +4935,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
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.
|
||||
String containerPrefix = callerAccountId() + "::" + regionPrefix;
|
||||
synchronized (privateIpAllocationLock) {
|
||||
containerPrivateIps.forEach((subnetKey, addresses) -> {
|
||||
if (subnetKey.startsWith(regionPrefix)) {
|
||||
bySubnet.computeIfAbsent(subnetKey.substring(regionPrefix.length()), ignored -> new HashSet<>())
|
||||
if (subnetKey.startsWith(containerPrefix)) {
|
||||
bySubnet.computeIfAbsent(subnetKey.substring(containerPrefix.length()), ignored -> new HashSet<>())
|
||||
.addAll(addresses);
|
||||
}
|
||||
});
|
||||
@@ -6797,7 +6804,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
removeTags(region, vpcId);
|
||||
}
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.deleteVpcNetwork(region, vpcId);
|
||||
vpcNetworkManager.deleteVpcNetwork(callerAccountId(), region, vpcId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8072,7 +8079,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
subnets.delete(key(region, subnetId));
|
||||
}
|
||||
if (vpcNetworkManager != null) {
|
||||
vpcNetworkManager.forgetSubnet(region, subnetId);
|
||||
vpcNetworkManager.forgetSubnet(callerAccountId(), region, subnetId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -82,15 +82,15 @@ public final class VpcContainerLeases {
|
||||
expectedVpcId, subnetId, vpcId);
|
||||
return;
|
||||
}
|
||||
Optional<String> address = ec2.allocateVpcPrivateIp(region, subnetId);
|
||||
Optional<String> address = ec2.allocateVpcPrivateIp(accountId, region, subnetId);
|
||||
if (address.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Optional<String> attached;
|
||||
try {
|
||||
attached = ec2.attachContainerToVpc(region, vpcId, subnetId, containerId, address.get());
|
||||
attached = ec2.attachContainerToVpc(accountId, region, vpcId, subnetId, containerId, address.get());
|
||||
} catch (RuntimeException e) {
|
||||
ec2.releaseVpcPrivateIp(region, subnetId, address.get());
|
||||
ec2.releaseVpcPrivateIp(accountId, region, subnetId, address.get());
|
||||
throw e;
|
||||
}
|
||||
if (attached.isPresent()) {
|
||||
@@ -99,7 +99,7 @@ public final class VpcContainerLeases {
|
||||
joined.set(lease);
|
||||
LOG.infov("{0} {1} joined VPC {2} at {3}", owner, name, vpcId, address.get());
|
||||
} else {
|
||||
ec2.releaseVpcPrivateIp(region, subnetId, address.get());
|
||||
ec2.releaseVpcPrivateIp(accountId, region, subnetId, address.get());
|
||||
}
|
||||
}));
|
||||
return Optional.ofNullable(joined.get());
|
||||
@@ -128,7 +128,7 @@ public final class VpcContainerLeases {
|
||||
for (String address : addresses) {
|
||||
Optional<Cidr4> host = address == null ? Optional.empty() : Cidr4.parse(address + "/32");
|
||||
if (host.isPresent() && cidr.get().containsAddress(host.get().network())
|
||||
&& ec2.reserveVpcPrivateIp(region, subnetId, address)) {
|
||||
&& ec2.reserveVpcPrivateIp(accountId, region, subnetId, address)) {
|
||||
Lease lease = new Lease(accountId, region, subnets.getFirst().getVpcId(), subnetId, address);
|
||||
leases.put(containerId, lease);
|
||||
LOG.infov("{0} {1} re-claimed its VPC address {2}", owner, name, address);
|
||||
@@ -161,7 +161,7 @@ public final class VpcContainerLeases {
|
||||
// Gone, so its address is free.
|
||||
unconfirmed.remove(containerId);
|
||||
if (leases.remove(containerId, lease)) {
|
||||
ec2.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address());
|
||||
ec2.releaseVpcPrivateIp(lease.accountId(), lease.region(), lease.subnetId(), lease.address());
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
unconfirmed.add(containerId);
|
||||
|
||||
@@ -27,7 +27,6 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.BiPredicate;
|
||||
|
||||
/**
|
||||
* Gives every VPC a real Docker network, so an EC2 instance's private address is an address
|
||||
@@ -176,20 +175,28 @@ public class VpcNetworkManager {
|
||||
* a consumer first needs an effective CIDR or private address; the network itself is only
|
||||
* created on attachment. Management requests must not wait for the Docker daemon.
|
||||
*/
|
||||
public void declareVpc(String region, String vpcId, String declaredCidr) {
|
||||
public void declareVpc(String accountId, String region, String vpcId, String declaredCidr) {
|
||||
if (!enabled() || region == null || vpcId == null) {
|
||||
return;
|
||||
}
|
||||
bindings.putIfAbsent(key(region, vpcId),
|
||||
new VpcBinding(region, vpcId, declaredCidr, networkName(region, vpcId)));
|
||||
String account = accountId == null ? config.defaultAccountId() : accountId;
|
||||
String key = key(account, region, vpcId);
|
||||
String networkName = networkName(account, region, vpcId);
|
||||
String accountLess = networkName(config.defaultAccountId(), region, vpcId);
|
||||
if (!isDefaultAccount(account) && previousRunNames(account, region, vpcId).contains(accountLess)) {
|
||||
// The network an older version created for another account's VPC under the account-less name: keep
|
||||
// using it, so what a previous run attached to it stays reachable across the upgrade.
|
||||
networkName = accountLess;
|
||||
}
|
||||
bindings.putIfAbsent(key, new VpcBinding(account, region, vpcId, declaredCidr, networkName));
|
||||
}
|
||||
|
||||
/** Records a subnet declaration inside an already-declared VPC. */
|
||||
public void declareSubnet(String region, String vpcId, String subnetId, String declaredCidr) {
|
||||
public void declareSubnet(String accountId, String region, String vpcId, String subnetId, String declaredCidr) {
|
||||
if (!enabled() || region == null || vpcId == null || subnetId == null) {
|
||||
return;
|
||||
}
|
||||
VpcBinding vpc = bindings.get(key(region, vpcId));
|
||||
VpcBinding vpc = bindings.get(key(accountId, region, vpcId));
|
||||
if (vpc == null) {
|
||||
return;
|
||||
}
|
||||
@@ -200,12 +207,12 @@ public class VpcNetworkManager {
|
||||
if (vpc.planned && !vpc.subnets.containsKey(subnetId)) {
|
||||
vpc.subnets.put(subnetId, planSubnet(vpc, subnetId, declaredCidr));
|
||||
}
|
||||
subnetOwner.put(key(region, subnetId), key(region, vpcId));
|
||||
subnetOwner.put(key(accountId, region, subnetId), key(accountId, region, vpcId));
|
||||
}
|
||||
}
|
||||
|
||||
private VpcBinding plannedVpc(String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.get(key(region, vpcId));
|
||||
private VpcBinding plannedVpc(String accountId, String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.get(key(accountId, region, vpcId));
|
||||
if (vpc == null || vpc.planned) {
|
||||
return vpc;
|
||||
}
|
||||
@@ -223,17 +230,18 @@ public class VpcNetworkManager {
|
||||
}
|
||||
|
||||
private void planVpc(VpcBinding vpc) {
|
||||
String accountId = vpc.accountId;
|
||||
String region = vpc.region;
|
||||
String vpcId = vpc.vpcId;
|
||||
String declaredCidr = vpc.declaredCidr;
|
||||
Optional<Cidr4> declared = Cidr4.parse(declaredCidr);
|
||||
String rejection = rejectionReason(region, vpcId, declared, declaredCidr, List.of());
|
||||
String rejection = rejectionReason(accountId, region, vpcId, declared, declaredCidr, List.of());
|
||||
Cidr4 effective;
|
||||
if (rejection == null) {
|
||||
effective = declared.orElseThrow();
|
||||
}
|
||||
else {
|
||||
effective = allocateFromFallbackPool(region, vpcId, declared.map(Cidr4::prefix).orElse(null));
|
||||
effective = allocateFromFallbackPool(accountId, region, vpcId, declared.map(Cidr4::prefix).orElse(null));
|
||||
if (effective == null) {
|
||||
LOG.warnv("VPC {0} in {1}: declared CIDR {2} is unusable ({3}) and the fallback pool {4} "
|
||||
+ "is exhausted. This VPC gets no Docker network; its instances keep "
|
||||
@@ -256,7 +264,7 @@ public class VpcNetworkManager {
|
||||
* @return null when the block can be used as declared, otherwise a human-readable reason
|
||||
* it cannot, which goes verbatim into the substitution WARN.
|
||||
*/
|
||||
private String rejectionReason(String region, String vpcId, Optional<Cidr4> declared, String declaredText,
|
||||
private String rejectionReason(String accountId, String region, String vpcId, Optional<Cidr4> declared, String declaredText,
|
||||
Collection<Cidr4> extraTaken) {
|
||||
if (declared.isEmpty()) {
|
||||
return declaredText == null || declaredText.isBlank()
|
||||
@@ -266,11 +274,11 @@ public class VpcNetworkManager {
|
||||
if (!cidr.isRfc1918()) {
|
||||
return "outside RFC 1918 private space (10/8, 172.16/12, 192.168/16)";
|
||||
}
|
||||
Optional<String> clash = firstClash(region, vpcId, cidr, extraTaken);
|
||||
Optional<String> clash = firstClash(accountId, region, vpcId, cidr, extraTaken);
|
||||
return clash.orElse(null);
|
||||
}
|
||||
|
||||
private Optional<String> firstClash(String region, String vpcId, Cidr4 candidate, Collection<Cidr4> extraTaken) {
|
||||
private Optional<String> firstClash(String accountId, String region, String vpcId, Cidr4 candidate, Collection<Cidr4> extraTaken) {
|
||||
for (Cidr4 taken : extraTaken) {
|
||||
if (candidate.overlaps(taken)) {
|
||||
return Optional.of("overlaps an address range already in use (" + taken + ")");
|
||||
@@ -283,7 +291,7 @@ public class VpcNetworkManager {
|
||||
+ "cannot route two identical ranges");
|
||||
}
|
||||
}
|
||||
for (Cidr4 taken : dockerNetworkSubnets(region, vpcId)) {
|
||||
for (Cidr4 taken : dockerNetworkSubnets(accountId, region, vpcId)) {
|
||||
if (candidate.overlaps(taken)) {
|
||||
return Optional.of("overlaps an existing Docker network (" + taken + ")");
|
||||
}
|
||||
@@ -371,7 +379,7 @@ public class VpcNetworkManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Cidr4 allocateFromFallbackPool(String region, String vpcId, Integer declaredPrefix) {
|
||||
private Cidr4 allocateFromFallbackPool(String accountId, String region, String vpcId, Integer declaredPrefix) {
|
||||
EmulatorConfig.VpcNetworksConfig cfg = config.services().ec2().vpcNetworks();
|
||||
Optional<Cidr4> pool = Cidr4.parse(cfg.fallbackPool());
|
||||
if (pool.isEmpty() || !pool.get().isRfc1918()) {
|
||||
@@ -385,7 +393,7 @@ public class VpcNetworkManager {
|
||||
// asked for, not a /16 that wastes fifteen sixteenths of the pool per VPC.
|
||||
prefix = Math.min(declaredPrefix, MAX_ALLOCATABLE_PREFIX);
|
||||
}
|
||||
List<Cidr4> taken = new ArrayList<>(dockerNetworkSubnets(region, vpcId));
|
||||
List<Cidr4> taken = new ArrayList<>(dockerNetworkSubnets(accountId, region, vpcId));
|
||||
bindings.values().stream().map(b -> b.effective).filter(c -> c != null).forEach(taken::add);
|
||||
return allocateSubBlock(pool.get(), prefix, taken);
|
||||
}
|
||||
@@ -420,11 +428,11 @@ public class VpcNetworkManager {
|
||||
* @return the address, or empty when the subnet has no Docker-backed range, in which case
|
||||
* the caller keeps its existing synthesised address rather than reporting nothing.
|
||||
*/
|
||||
public Optional<String> allocatePrivateIp(String region, String subnetId) {
|
||||
public Optional<String> allocatePrivateIp(String accountId, String region, String subnetId) {
|
||||
if (!enabled() || subnetId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
SubnetBinding subnet = subnetBinding(region, subnetId);
|
||||
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
|
||||
if (subnet == null || subnet.effective == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -468,8 +476,8 @@ public class VpcNetworkManager {
|
||||
* @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
|
||||
*/
|
||||
public boolean reservePrivateIp(String region, String subnetId, String address) {
|
||||
return lease(region, subnetId, address, true);
|
||||
public boolean reservePrivateIp(String accountId, String region, String subnetId, String address) {
|
||||
return lease(accountId, region, subnetId, address, true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -484,19 +492,19 @@ public class VpcNetworkManager {
|
||||
* @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
|
||||
*/
|
||||
public boolean claimPrivateIp(String region, String subnetId, String address) {
|
||||
return lease(region, subnetId, address, false);
|
||||
public boolean claimPrivateIp(String accountId, String region, String subnetId, String address) {
|
||||
return lease(accountId, region, subnetId, address, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param restoring whether a restart is re-reserving an address a persisted instance holds,
|
||||
* which warns on refusal and moves the cursor past the address
|
||||
*/
|
||||
private boolean lease(String region, String subnetId, String address, boolean restoring) {
|
||||
private boolean lease(String accountId, String region, String subnetId, String address, boolean restoring) {
|
||||
if (!enabled() || subnetId == null || address == null) {
|
||||
return false;
|
||||
}
|
||||
SubnetBinding subnet = subnetBinding(region, subnetId);
|
||||
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
|
||||
if (subnet == null || subnet.effective == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -526,8 +534,8 @@ public class VpcNetworkManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void releasePrivateIp(String region, String subnetId, String address) {
|
||||
String vpcKey = subnetOwner.get(key(region, subnetId));
|
||||
public void releasePrivateIp(String accountId, String region, String subnetId, String address) {
|
||||
String vpcKey = subnetOwner.get(key(accountId, region, subnetId));
|
||||
VpcBinding vpc = vpcKey == null ? null : bindings.get(vpcKey);
|
||||
SubnetBinding subnet = vpc == null ? null : vpc.subnets.get(subnetId);
|
||||
if (subnet != null && address != null) {
|
||||
@@ -549,19 +557,19 @@ public class VpcNetworkManager {
|
||||
*
|
||||
* @return the network name on success, empty when the instance stays on the bridge only
|
||||
*/
|
||||
public Optional<String> attach(String region, String vpcId, String subnetId,
|
||||
public Optional<String> attach(String accountId, String region, String vpcId, String subnetId,
|
||||
String containerId, String address) {
|
||||
if (!enabled() || containerId == null || address == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
VpcBinding vpc = plannedVpc(region, vpcId);
|
||||
VpcBinding vpc = plannedVpc(accountId, region, vpcId);
|
||||
if (vpc == null || vpc.effective == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// Only attach an address this manager actually planned. A synthesised address from
|
||||
// Ec2Service's fallback would be outside the network's IPAM pool, and Docker would
|
||||
// reject it, noisily, and after the container is already up.
|
||||
SubnetBinding subnet = subnetBinding(region, subnetId);
|
||||
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
|
||||
Optional<Cidr4> parsed = Cidr4.parse(address + "/32");
|
||||
if (subnet == null || subnet.effective == null || parsed.isEmpty()
|
||||
|| !subnet.effective.containsAddress(parsed.get().network())) {
|
||||
@@ -594,11 +602,11 @@ public class VpcNetworkManager {
|
||||
*
|
||||
* @return true if the container is attached to the VPC network, false otherwise
|
||||
*/
|
||||
public boolean attachContainer(String region, String vpcId, String containerId) {
|
||||
public boolean attachContainer(String accountId, String region, String vpcId, String containerId) {
|
||||
if (!enabled() || containerId == null || vpcId == null) {
|
||||
return false;
|
||||
}
|
||||
VpcBinding vpc = plannedVpc(region, vpcId);
|
||||
VpcBinding vpc = plannedVpc(accountId, region, vpcId);
|
||||
if (vpc == null || vpc.effective == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -635,11 +643,11 @@ public class VpcNetworkManager {
|
||||
* <p>A container that was never attached, or whose network is already gone, is not an error
|
||||
* here; both are the ordinary shape of a launch that failed early.
|
||||
*/
|
||||
public void detach(String region, String vpcId, String containerId) {
|
||||
public void detach(String accountId, String region, String vpcId, String containerId) {
|
||||
if (!enabled() || containerId == null) {
|
||||
return;
|
||||
}
|
||||
VpcBinding vpc = bindings.get(key(region, vpcId));
|
||||
VpcBinding vpc = bindings.get(key(accountId, region, vpcId));
|
||||
if (vpc == null || !vpc.created) {
|
||||
return;
|
||||
}
|
||||
@@ -662,7 +670,7 @@ public class VpcNetworkManager {
|
||||
/** @return the network name, or null when creation failed */
|
||||
private String materialise(VpcBinding vpc) {
|
||||
synchronized (vpc) {
|
||||
if (bindings.get(key(vpc.region, vpc.vpcId)) != vpc) {
|
||||
if (bindings.get(key(vpc.accountId, vpc.region, vpc.vpcId)) != vpc) {
|
||||
return null;
|
||||
}
|
||||
if (vpc.created) {
|
||||
@@ -814,7 +822,8 @@ public class VpcNetworkManager {
|
||||
|
||||
private Map<String, String> networkLabels(VpcBinding vpc) {
|
||||
Map<String, String> labels = new LinkedHashMap<>(ContainerStorageHelper.defaultLabels(config));
|
||||
labels.putAll(ContainerStorageHelper.resourceIdentityLabels(SERVICE_VALUE, vpc.vpcId, null, vpc.region));
|
||||
labels.putAll(ContainerStorageHelper.resourceIdentityLabels(SERVICE_VALUE, vpc.vpcId, vpc.accountId,
|
||||
vpc.region));
|
||||
labels.put(ContainerStorageHelper.COMPONENT_LABEL, COMPONENT_VALUE);
|
||||
labels.put(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config));
|
||||
return ALIASES.withLegacyAliases(labels);
|
||||
@@ -822,8 +831,8 @@ public class VpcNetworkManager {
|
||||
|
||||
// ─── Teardown ────────────────────────────────────────────────────────────
|
||||
|
||||
public void forgetSubnet(String region, String subnetId) {
|
||||
String vpcKey = subnetOwner.remove(key(region, subnetId));
|
||||
public void forgetSubnet(String accountId, String region, String subnetId) {
|
||||
String vpcKey = subnetOwner.remove(key(accountId, region, subnetId));
|
||||
if (vpcKey == null) {
|
||||
return;
|
||||
}
|
||||
@@ -837,19 +846,19 @@ public class VpcNetworkManager {
|
||||
}
|
||||
|
||||
/** Drops the VPC's plan and removes its Docker network, retrying while endpoints drain. */
|
||||
public void deleteVpcNetwork(String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.remove(key(region, vpcId));
|
||||
public void deleteVpcNetwork(String accountId, String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.remove(key(accountId, region, vpcId));
|
||||
if (vpc == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (vpc.declarationLock) {
|
||||
vpc.subnetDeclarations.keySet().forEach(subnetId -> subnetOwner.remove(key(region, subnetId)));
|
||||
vpc.subnetDeclarations.keySet().forEach(subnetId -> subnetOwner.remove(key(accountId, region, subnetId)));
|
||||
}
|
||||
// A network this process never materialised can still exist: one a previous run created
|
||||
// for a VPC none of whose instances has started since. Startup reconciliation noted it,
|
||||
// under its own name, which an older version spelled differently from vpc.networkName.
|
||||
// An upgrade can leave both spellings behind, so every one noted is removed.
|
||||
Set<String> previousRunNetworks = networksFromPreviousRun.remove(key(region, vpcId));
|
||||
Set<String> previousRunNetworks = networksFromPreviousRun.remove(key(accountId, region, vpcId));
|
||||
Set<String> networkNames = new LinkedHashSet<>();
|
||||
synchronized (vpc) {
|
||||
// An in-flight Docker create must finish before its network is collected for removal.
|
||||
@@ -899,6 +908,33 @@ public class VpcNetworkManager {
|
||||
/** Network names by VPC, for VPCs still declared at startup whose networks a previous run created. */
|
||||
private final Map<String, Set<String>> networksFromPreviousRun = new ConcurrentHashMap<>();
|
||||
|
||||
/** The accounts that still declare a VPC of an id in a Region, as startup reconciliation asks. */
|
||||
@FunctionalInterface
|
||||
public interface DeclaredVpcs {
|
||||
Set<String> accountsDeclaring(String region, String vpcId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The account a surviving network belongs to: the account it is labelled with, when that account still declares
|
||||
* the VPC; for a network an older version labelled with none, as it keyed networks by Region and id alone, the
|
||||
* account declaring the VPC, the default account first. Null when no account declares it.
|
||||
*/
|
||||
private String declaringAccount(Map<String, String> labels, Set<String> declaring) {
|
||||
String labelled = ALIASES.labelValue(labels, ContainerStorageHelper.ACCOUNT_LABEL);
|
||||
if (labelled != null && !labelled.isBlank()) {
|
||||
return declaring.contains(labelled) ? labelled : null;
|
||||
}
|
||||
if (declaring.contains(config.defaultAccountId())) {
|
||||
return config.defaultAccountId();
|
||||
}
|
||||
return declaring.stream().sorted().findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/** The names of the networks a previous run left for an account's VPC, noted by startup reconciliation. */
|
||||
private Set<String> previousRunNames(String accountId, String region, String vpcId) {
|
||||
return networksFromPreviousRun.getOrDefault(key(accountId, region, vpcId), Set.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes VPC networks this Floci left behind on a previous run.
|
||||
*
|
||||
@@ -915,9 +951,10 @@ public class VpcNetworkManager {
|
||||
* VPC later removes its network even though this run never materialised it. That listing runs
|
||||
* with {@code reconcile-on-startup} off too; only the removal of orphans is behind the flag.
|
||||
*
|
||||
* @param stillDeclared answers whether (region, vpcId) exists in the restored state
|
||||
* @param stillDeclared answers which accounts declare a VPC of an id in a Region in the restored state; a network
|
||||
* an older version labelled with no account belongs to one of them, the default account first
|
||||
*/
|
||||
public void reconcileOrphans(BiPredicate<String, String> stillDeclared) {
|
||||
public void reconcileOrphans(DeclaredVpcs stillDeclared) {
|
||||
if (!enabled()) {
|
||||
return;
|
||||
}
|
||||
@@ -940,8 +977,10 @@ public class VpcNetworkManager {
|
||||
}
|
||||
String vpcId = ALIASES.labelValue(labels, ContainerStorageHelper.RESOURCE_ID_LABEL);
|
||||
String region = ALIASES.labelValue(labels, ContainerStorageHelper.REGION_LABEL);
|
||||
if (vpcId != null && region != null && stillDeclared.test(region, vpcId)) {
|
||||
networksFromPreviousRun.computeIfAbsent(key(region, vpcId), k -> ConcurrentHashMap.newKeySet())
|
||||
String accountId = vpcId == null || region == null ? null
|
||||
: declaringAccount(labels, stillDeclared.accountsDeclaring(region, vpcId));
|
||||
if (accountId != null) {
|
||||
networksFromPreviousRun.computeIfAbsent(key(accountId, region, vpcId), k -> ConcurrentHashMap.newKeySet())
|
||||
.add(network.getName());
|
||||
continue;
|
||||
}
|
||||
@@ -992,40 +1031,55 @@ public class VpcNetworkManager {
|
||||
|
||||
// ─── Introspection, for tests and reporting ──────────────────────────────
|
||||
|
||||
public Optional<String> effectiveVpcCidr(String region, String vpcId) {
|
||||
VpcBinding vpc = plannedVpc(region, vpcId);
|
||||
public Optional<String> effectiveVpcCidr(String accountId, String region, String vpcId) {
|
||||
VpcBinding vpc = plannedVpc(accountId, region, vpcId);
|
||||
return vpc == null || vpc.effective == null ? Optional.empty() : Optional.of(vpc.effective.toString());
|
||||
}
|
||||
|
||||
public Optional<String> effectiveSubnetCidr(String region, String subnetId) {
|
||||
SubnetBinding subnet = subnetBinding(region, subnetId);
|
||||
public Optional<String> effectiveSubnetCidr(String accountId, String region, String subnetId) {
|
||||
SubnetBinding subnet = subnetBinding(accountId, region, subnetId);
|
||||
return subnet == null || subnet.effective == null
|
||||
? Optional.empty() : Optional.of(subnet.effective.toString());
|
||||
}
|
||||
|
||||
public Optional<String> networkNameFor(String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.get(key(region, vpcId));
|
||||
public Optional<String> networkNameFor(String accountId, String region, String vpcId) {
|
||||
VpcBinding vpc = bindings.get(key(accountId, region, vpcId));
|
||||
return vpc == null ? Optional.empty() : Optional.of(vpc.networkName);
|
||||
}
|
||||
|
||||
public boolean isSubstituted(String region, String vpcId) {
|
||||
VpcBinding vpc = plannedVpc(region, vpcId);
|
||||
public boolean isSubstituted(String accountId, String region, String vpcId) {
|
||||
VpcBinding vpc = plannedVpc(accountId, region, vpcId);
|
||||
return vpc != null && vpc.substituted;
|
||||
}
|
||||
|
||||
String networkName(String region, String vpcId) {
|
||||
/**
|
||||
* The Docker network of an account's VPC. The default account's keeps the name it always had, so its networks
|
||||
* outlive an upgrade; any other account's carries the account, as two accounts' default VPCs share one id.
|
||||
*/
|
||||
String networkName(String accountId, String region, String vpcId) {
|
||||
String account = isDefaultAccount(accountId) ? "" : accountId + "-";
|
||||
return ContainerStorageHelper.dockerName(config,
|
||||
"vpc-" + config.port() + "-" + region + "-" + vpcId);
|
||||
"vpc-" + config.port() + "-" + account + region + "-" + vpcId);
|
||||
}
|
||||
|
||||
private SubnetBinding subnetBinding(String region, String subnetId) {
|
||||
String vpcKey = subnetOwner.get(key(region, subnetId));
|
||||
private boolean isDefaultAccount(String accountId) {
|
||||
return accountId == null || accountId.equals(config.defaultAccountId());
|
||||
}
|
||||
|
||||
/** The account a VPC network was created for; the default account for one an older version labelled with none. */
|
||||
private String accountOf(Map<String, String> labels) {
|
||||
String account = ALIASES.labelValue(labels, ContainerStorageHelper.ACCOUNT_LABEL);
|
||||
return account == null || account.isBlank() ? config.defaultAccountId() : account;
|
||||
}
|
||||
|
||||
private SubnetBinding subnetBinding(String accountId, String region, String subnetId) {
|
||||
String vpcKey = subnetOwner.get(key(accountId, region, subnetId));
|
||||
if (vpcKey == null) {
|
||||
return null;
|
||||
}
|
||||
VpcBinding vpc = bindings.get(vpcKey);
|
||||
if (vpc != null) {
|
||||
vpc = plannedVpc(vpc.region, vpc.vpcId);
|
||||
vpc = plannedVpc(vpc.accountId, vpc.region, vpc.vpcId);
|
||||
}
|
||||
return vpc == null ? null : vpc.subnets.get(subnetId);
|
||||
}
|
||||
@@ -1033,20 +1087,23 @@ public class VpcNetworkManager {
|
||||
/**
|
||||
* Every IPv4 range the daemon has already reserved, so a declared CIDR can be checked before use.
|
||||
*
|
||||
* @param ownAccount the account of the VPC being planned
|
||||
* @param ownRegion the Region of the VPC being planned
|
||||
* @param ownVpcId the VPC being planned; this instance's surviving network for that same VPC is
|
||||
* excluded, so a Floci restart re-planning a VPC whose bridge is still up does
|
||||
* not read its own network as a collision and substitute a CIDR it already has.
|
||||
* Two Regions can hold a VPC with the same id (the legacy {@code vpc-default}),
|
||||
* so the network must be for that VPC in the same Region
|
||||
* Two Regions, and two accounts, can hold a VPC with the same id (the default
|
||||
* VPC's), so the network must be for that VPC of the same account in the same Region
|
||||
*/
|
||||
private Set<Cidr4> dockerNetworkSubnets(String ownRegion, String ownVpcId) {
|
||||
private Set<Cidr4> dockerNetworkSubnets(String ownAccount, String ownRegion, String ownVpcId) {
|
||||
Set<Cidr4> taken = new LinkedHashSet<>();
|
||||
try {
|
||||
for (Network network : dockerClient.listNetworksCmd().exec()) {
|
||||
Map<String, String> labels = network.getLabels() == null ? Map.of() : network.getLabels();
|
||||
if (ownVpcId != null && ALIASES.matches(labels, ContainerStorageHelper.RESOURCE_ID_LABEL, ownVpcId)
|
||||
&& ALIASES.matches(labels, ContainerStorageHelper.REGION_LABEL, ownRegion)
|
||||
&& (accountOf(labels).equals(ownAccount) || previousRunNames(ownAccount, ownRegion, ownVpcId)
|
||||
.contains(network.getName()))
|
||||
&& ownedByThisDeployment(labels)) {
|
||||
continue;
|
||||
}
|
||||
@@ -1065,11 +1122,17 @@ public class VpcNetworkManager {
|
||||
return taken;
|
||||
}
|
||||
|
||||
private static String key(String region, String id) {
|
||||
return region + "::" + id;
|
||||
/**
|
||||
* The key of a VPC or subnet of an account in a Region. Two accounts' default VPCs share one id
|
||||
* ({@code vpc-default-<region>}), so the account is part of it: without it they shared one binding and one
|
||||
* Docker network.
|
||||
*/
|
||||
private String key(String accountId, String region, String id) {
|
||||
return (accountId == null ? config.defaultAccountId() : accountId) + "::" + region + "::" + id;
|
||||
}
|
||||
|
||||
private static final class VpcBinding {
|
||||
final String accountId;
|
||||
final String region;
|
||||
final String vpcId;
|
||||
final String declaredCidr;
|
||||
@@ -1084,7 +1147,8 @@ public class VpcNetworkManager {
|
||||
volatile boolean created;
|
||||
volatile String flociContainerId;
|
||||
|
||||
VpcBinding(String region, String vpcId, String declaredCidr, String networkName) {
|
||||
VpcBinding(String accountId, String region, String vpcId, String declaredCidr, String networkName) {
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.vpcId = vpcId;
|
||||
this.declaredCidr = declaredCidr;
|
||||
|
||||
@@ -1174,8 +1174,8 @@ public class EcsContainerManager {
|
||||
.filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty())
|
||||
.findFirst()
|
||||
.orElse(definitions.getFirst());
|
||||
ec2Service.attachContainerToVpc(region, vpcId,
|
||||
task.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst(),
|
||||
ec2Service.attachContainerToVpc(AwsArnUtils.accountOrDefault(task.getTaskArn(), regionResolver.getAccountId()),
|
||||
region, vpcId, task.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst(),
|
||||
containerIds.get(holder.getName()), task.getPrivateIpAddress());
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.dns.DnsAnswer;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource;
|
||||
import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc;
|
||||
@@ -197,7 +196,7 @@ public class EksClusterManager
|
||||
private final StorageBackend<String, Nodegroup> nodeGroupStorage;
|
||||
private final Map<String, Set<String>> programmedClusterRoutes = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> clusterRouteLocks = new ConcurrentHashMap<>();
|
||||
private record VpcLease(String region, String vpcId, String subnetId, String address) {}
|
||||
private record VpcLease(String accountId, String region, String vpcId, String subnetId, String address) {}
|
||||
private record ClusterVpcSubnet(String vpcId, String subnetId) {}
|
||||
private final Map<String, VpcLease> clusterVpcLeases = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -246,7 +245,8 @@ public class EksClusterManager
|
||||
if (persistedIp == null || persistedIp.isBlank() || subnet == null) {
|
||||
return null;
|
||||
}
|
||||
return new VpcLease(clusterRegion(cluster), subnet.vpcId(), subnet.subnetId(), persistedIp);
|
||||
return new VpcLease(resolveClusterAccountId(cluster), clusterRegion(cluster), subnet.vpcId(), subnet.subnetId(),
|
||||
persistedIp);
|
||||
}
|
||||
|
||||
// Issue #5501: Lease or re-reserve a stable VPC subnet IP for the k3s node container across restarts.
|
||||
@@ -276,10 +276,9 @@ public class EksClusterManager
|
||||
}
|
||||
String persistedIp = cluster.getNodePrivateIp();
|
||||
if (persistedIp != null && !persistedIp.isBlank()) {
|
||||
boolean reserved = Boolean.TRUE.equals(RequestScopes.callAs(accountId, region,
|
||||
() -> ec2.reserveVpcPrivateIp(region, subnetId, persistedIp)));
|
||||
boolean reserved = ec2.reserveVpcPrivateIp(accountId, region, subnetId, persistedIp);
|
||||
if (reserved) {
|
||||
VpcLease lease = new VpcLease(region, vpcId, subnetId, persistedIp);
|
||||
VpcLease lease = new VpcLease(accountId, region, vpcId, subnetId, persistedIp);
|
||||
clusterVpcLeases.put(resourceName, lease);
|
||||
return lease;
|
||||
}
|
||||
@@ -291,14 +290,13 @@ public class EksClusterManager
|
||||
if (!allocateWhenUnreserved) {
|
||||
return null;
|
||||
}
|
||||
Optional<String> allocated = RequestScopes.callAs(accountId, region,
|
||||
() -> ec2.allocateVpcPrivateIp(region, subnetId));
|
||||
Optional<String> allocated = ec2.allocateVpcPrivateIp(accountId, region, subnetId);
|
||||
if (allocated == null || allocated.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String address = allocated.get();
|
||||
cluster.setNodePrivateIp(address);
|
||||
VpcLease lease = new VpcLease(region, vpcId, subnetId, address);
|
||||
VpcLease lease = new VpcLease(accountId, region, vpcId, subnetId, address);
|
||||
clusterVpcLeases.put(resourceName, lease);
|
||||
return lease;
|
||||
}
|
||||
@@ -307,7 +305,7 @@ public class EksClusterManager
|
||||
VpcLease lease = clusterVpcLeases.remove(resourceName);
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (lease != null && ec2 != null) {
|
||||
ec2.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address());
|
||||
ec2.releaseVpcPrivateIp(lease.accountId(), lease.region(), lease.subnetId(), lease.address());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -940,7 +938,7 @@ public class EksClusterManager
|
||||
if (vpcLease != null) {
|
||||
Ec2Service ec2 = ec2Service();
|
||||
Optional<String> attachedNetwork = ec2 != null
|
||||
? ec2.attachContainerToVpc(
|
||||
? ec2.attachContainerToVpc(vpcLease.accountId(),
|
||||
vpcLease.region(), vpcLease.vpcId(), vpcLease.subnetId(),
|
||||
containerId, vpcLease.address())
|
||||
: Optional.empty();
|
||||
@@ -991,7 +989,8 @@ public class EksClusterManager
|
||||
if (vpcLease != null) {
|
||||
Ec2Service ec2 = ec2Service();
|
||||
if (ec2 != null) {
|
||||
ec2.detachContainerFromVpc(vpcLease.region(), vpcLease.vpcId(), containerId);
|
||||
ec2.detachContainerFromVpc(vpcLease.accountId(), vpcLease.region(), vpcLease.vpcId(),
|
||||
containerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1151,7 +1150,7 @@ public class EksClusterManager
|
||||
renamed = true;
|
||||
docker.stopContainerCmd(oldId).exec();
|
||||
if (lease != null && ec2 != null) {
|
||||
ec2.detachContainerFromVpc(lease.region(), lease.vpcId(), oldId);
|
||||
ec2.detachContainerFromVpc(lease.accountId(), lease.region(), lease.vpcId(), oldId);
|
||||
}
|
||||
unregisterMetadataEndpoint(cluster);
|
||||
closeQuietly(clusterLogHandles.remove(clusterResourceName(cluster)));
|
||||
@@ -1169,7 +1168,7 @@ public class EksClusterManager
|
||||
lifecycleManager.removeIfExistsStrict(containerName, true);
|
||||
docker.renameContainerCmd(oldId).withName(containerName).exec();
|
||||
if (lease != null && ec2 != null) {
|
||||
Optional<String> reattached = ec2.attachContainerToVpc(
|
||||
Optional<String> reattached = ec2.attachContainerToVpc(lease.accountId(),
|
||||
lease.region(), lease.vpcId(), lease.subnetId(), oldId, lease.address());
|
||||
if (reattached == null || reattached.isEmpty()) {
|
||||
throw new IllegalStateException("Could not reattach previous EKS container " + oldId);
|
||||
@@ -2855,9 +2854,9 @@ public class EksClusterManager
|
||||
return;
|
||||
}
|
||||
String region = clusterRegion(cluster);
|
||||
ec2.attachContainerToVpc(region, vpcId, containerId);
|
||||
|
||||
String accountId = resolveClusterAccountId(cluster);
|
||||
ec2.attachContainerToVpc(accountId, region, vpcId, containerId);
|
||||
|
||||
List<RouteTable> vpcRouteTables = ec2.describeRouteTables(accountId, region, List.of(), Map.of("vpc-id", List.of(vpcId)));
|
||||
List<RouteTable> applicable = EksVpcRouteProgramming.findApplicableRouteTables(
|
||||
vpcId, vpcConfig.getSubnetIds(), vpcRouteTables);
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -719,16 +718,16 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
|| subnets.isEmpty() || !(subnets.getFirst() instanceof String subnetId)) {
|
||||
return;
|
||||
}
|
||||
// Provisioned and cross-account launches run outside the owner's request scope.
|
||||
Optional<String> address = RequestScopes.callAs(accountId, region,
|
||||
() -> ec2Service.allocateVpcPrivateIp(region, subnetId));
|
||||
// Provisioned and cross-account launches run outside the owner's request scope, so the owner is named.
|
||||
Optional<String> address = ec2Service.allocateVpcPrivateIp(accountId, 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()));
|
||||
if (ec2Service.attachContainerToVpc(accountId, region, fn.getVpcId(), subnetId, containerId, address.get())
|
||||
.isPresent()) {
|
||||
vpcLeases.put(containerId, new VpcLease(accountId, region, subnetId, address.get()));
|
||||
} else {
|
||||
ec2Service.releaseVpcPrivateIp(region, subnetId, address.get());
|
||||
ec2Service.releaseVpcPrivateIp(accountId, region, subnetId, address.get());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -736,7 +735,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
private void releaseVpcLease(String containerId) {
|
||||
VpcLease lease = vpcLeases.remove(containerId);
|
||||
if (lease != null) {
|
||||
ec2Service.releaseVpcPrivateIp(lease.region(), lease.subnetId(), lease.address());
|
||||
ec2Service.releaseVpcPrivateIp(lease.accountId(), lease.region(), lease.subnetId(), lease.address());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1456,7 +1455,7 @@ 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) { }
|
||||
private record VpcLease(String accountId, String region, String subnetId, String address) { }
|
||||
|
||||
/**
|
||||
* Arms an async watch (via Docker's own wait-for-exit API, not polling) that notices when
|
||||
|
||||
Reference in new issue
Block a user