mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(ec2): protect subnets and VPCs that load balancers use (#5663)
* fix(elbv2): protect subnets and VPCs that load balancers use DeleteSubnet and DeleteVpc returned success while an Application or Network Load Balancer still used the subnet, and DescribeLoadBalancers went on listing a subnet that no longer existed. EC2 now asks each VpcDependencyProvider, implemented by ELBv2, before deleting a subnet or VPC, under the lock CreateLoadBalancer and SetSubnets hold while they record their subnets, and refuses with DependencyViolation. Covered end to end through CloudFormation, including updates, rollbacks and stack deletes that move or delete load balancers, subnets and VPCs. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): record the subnets a load balancer is on A load balancer's attributes named none of its subnets, so once a template stopped naming it, the stack walks had nothing to order it by and deleted it after them, which EC2 now refuses. The provisioner keeps one hidden uses attribute per subnet, refreshed when an update moves the balancer and when a rollback moves it back. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): delete removed resources dependents first The update cleanup deleted removed and condition-disabled resources in reverse map order, before the replacement cleanup. A subnet an earlier update added sits after the load balancer it moved onto it, so removing both deleted the subnet first, and a renamed balancer's old entity still used a subnet the same update dropped. Both now end DELETE_FAILED, since EC2 refuses to delete a subnet a load balancer uses. The removed resources are now walked in dependency order, and a failed delete is tried once more after the replacement cleanup before it is reported. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): name every ELBv2 load balancer type as a subnet dependency The DeleteSubnet and DeleteVpc rows named only Application and Network Load Balancers, while the check counts every ELBv2 type. The SDK lifecycle test now deletes its subnets and VPC even when an assertion fails. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): pin the order of the removed-resource deletes The removal test passed through the retry alone, so it now checks that the load balancer is deleted before its subnet is tried, and that the replaced balancer's old entity goes before the dropped subnet. The provisioner attribute test reads only what Fn::GetAtt can see, with the balancer on subnets. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
0f4f59bbbb
commit
e520166170
13 files changed
+1337
-62
No files matched your search
+66
-33
@@ -2276,11 +2276,21 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// resources are deleted during post-update cleanup.
|
||||
persistStack(stack);
|
||||
}
|
||||
// Both cleanup paths feed the single final status/reason writer.
|
||||
List<UpdateCleanupFailure> cleanupFailures =
|
||||
new ArrayList<>(deleteRemovedOrConditionFalseResources(
|
||||
stack, resources, conditions, region));
|
||||
cleanupFailures.addAll(finishCommittedResourceCleanup(stack, region));
|
||||
// Both cleanup paths feed the single final status/reason writer. A removed resource
|
||||
// whose delete failed is tried once more after the replacement cleanup, as an entity
|
||||
// a replacement displaced can still use it: an old load balancer on a subnet the same
|
||||
// update removed.
|
||||
List<StackResource> retried = deleteRemovedOrConditionFalseResources(
|
||||
stack, resources, conditions, region);
|
||||
List<UpdateCleanupFailure> displacedFailures = finishCommittedResourceCleanup(stack, region);
|
||||
List<UpdateCleanupFailure> cleanupFailures = new ArrayList<>();
|
||||
for (StackResource resource : retried) {
|
||||
UpdateCleanupFailure failure = deleteRemovedResource(stack, resource, region, true);
|
||||
if (failure != null) {
|
||||
cleanupFailures.add(failure);
|
||||
}
|
||||
}
|
||||
cleanupFailures.addAll(displacedFailures);
|
||||
finishCommittedStackUpdate(stack, cleanupFailures);
|
||||
return;
|
||||
}
|
||||
@@ -2802,8 +2812,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
String region) {
|
||||
// Dependents first, in the template's order rather than the map's, as the update cleanup
|
||||
// walks it: a resource the update added sits after the resources that depend on it, so
|
||||
// reversing the map would delete a subnet the update added before an instance or NAT
|
||||
// gateway the update put on it, and EC2 refuses that delete.
|
||||
// reversing the map would delete a subnet the update moved a load balancer onto before the
|
||||
// load balancer is moved back, and EC2 refuses that delete.
|
||||
List<StackResource> resources = resourcesInCreationOrder(stack, region);
|
||||
Collections.reverse(resources);
|
||||
List<String> failures = new ArrayList<>();
|
||||
@@ -3066,16 +3076,21 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* as {@code DELETE_FAILED}, so a later {@code DeleteStack} or {@code UpdateStack} can retry the cleanup
|
||||
* instead of orphaning the backing resource.
|
||||
*
|
||||
* @return one {@link UpdateCleanupFailure} per resource whose physical deletion failed
|
||||
* <p>Dependents go first, in the order {@link #resourcesInCreationOrder} gives rather than the map's:
|
||||
* a subnet an earlier update added sits after the load balancer it moved onto it, and the template
|
||||
* that named what a removed resource uses is gone. A failed delete is not reported here, since the
|
||||
* caller tries it again after the replacement cleanup.
|
||||
*
|
||||
* @return the resources whose physical deletion failed, for {@link #deleteRemovedResource} to try again
|
||||
*/
|
||||
private List<UpdateCleanupFailure> deleteRemovedOrConditionFalseResources(Stack stack, JsonNode resources,
|
||||
private List<StackResource> deleteRemovedOrConditionFalseResources(Stack stack, JsonNode resources,
|
||||
Map<String, Boolean> conditions, String region) {
|
||||
if (!resources.isObject()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<UpdateCleanupFailure> failures = new ArrayList<>();
|
||||
List<StackResource> ordered = new ArrayList<>(stack.resourcesSnapshot().values());
|
||||
List<StackResource> failed = new ArrayList<>();
|
||||
List<StackResource> ordered = resourcesInCreationOrder(stack, region);
|
||||
Collections.reverse(ordered);
|
||||
for (StackResource resource : ordered) {
|
||||
JsonNode resDef = resources.get(resource.getLogicalId());
|
||||
@@ -3093,31 +3108,49 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
|
||||
try {
|
||||
deleteResourcePhysically(resource, region, ownerAccount(stack));
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_COMPLETE", null);
|
||||
stack.getResources().remove(resource.getLogicalId());
|
||||
} catch (Exception e) {
|
||||
String reason = e.getMessage() != null
|
||||
? e.getMessage()
|
||||
: "Resource deletion failed during update cleanup";
|
||||
failures.add(new UpdateCleanupFailure(
|
||||
resource.getLogicalId(), resource.getPhysicalId(), reason));
|
||||
// Keep the resource under stack management as DELETE_FAILED. Removing it here would
|
||||
// drop it from DescribeStackResources while the backing resource still exists,
|
||||
// orphaning it and preventing a later DeleteStack/UpdateStack from retrying cleanup.
|
||||
resource.setStatus("DELETE_FAILED");
|
||||
resource.setStatusReason(reason);
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_FAILED", reason);
|
||||
LOG.warnv("Failed to delete removed or condition-disabled {0} ({1}) in stack {2}: {3}",
|
||||
resource.getResourceType(), resource.getPhysicalId(),
|
||||
stack.getStackName(), reason);
|
||||
if (deleteRemovedResource(stack, resource, region, false) != null) {
|
||||
failed.add(resource);
|
||||
}
|
||||
}
|
||||
|
||||
return failures;
|
||||
return failed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes one removed or condition-disabled resource, and reports a failure only on the last
|
||||
* attempt.
|
||||
*
|
||||
* @return the failure, or null once the resource is deleted
|
||||
*/
|
||||
private UpdateCleanupFailure deleteRemovedResource(Stack stack, StackResource resource, String region,
|
||||
boolean lastAttempt) {
|
||||
try {
|
||||
deleteResourcePhysically(resource, region, ownerAccount(stack));
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_COMPLETE", null);
|
||||
stack.getResources().remove(resource.getLogicalId());
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
String reason = e.getMessage() != null
|
||||
? e.getMessage()
|
||||
: "Resource deletion failed during update cleanup";
|
||||
UpdateCleanupFailure failure = new UpdateCleanupFailure(
|
||||
resource.getLogicalId(), resource.getPhysicalId(), reason);
|
||||
if (!lastAttempt) {
|
||||
return failure;
|
||||
}
|
||||
// Keep the resource under stack management as DELETE_FAILED. Removing it here would
|
||||
// drop it from DescribeStackResources while the backing resource still exists,
|
||||
// orphaning it and preventing a later DeleteStack/UpdateStack from retrying cleanup.
|
||||
resource.setStatus("DELETE_FAILED");
|
||||
resource.setStatusReason(reason);
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_FAILED", reason);
|
||||
LOG.warnv("Failed to delete removed or condition-disabled {0} ({1}) in stack {2}: {3}",
|
||||
resource.getResourceType(), resource.getPhysicalId(),
|
||||
stack.getStackName(), reason);
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+37
-12
@@ -36,6 +36,8 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final String TARGET_GROUP = "AWS::ElasticLoadBalancingV2::TargetGroup";
|
||||
private static final String LISTENER = "AWS::ElasticLoadBalancingV2::Listener";
|
||||
private static final String LISTENER_RULE = "AWS::ElasticLoadBalancingV2::ListenerRule";
|
||||
/** Prefixes one uses attribute per subnet a load balancer is on, numbered from 1. */
|
||||
private static final String USED_SUBNET_ATTR_PREFIX = CfnRollback.USES_ATTR_PREFIX + "Subnet.";
|
||||
|
||||
private final ElbV2Service elbV2Service;
|
||||
|
||||
@@ -141,8 +143,9 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
return true;
|
||||
}
|
||||
String arn = resource.getPhysicalId();
|
||||
elbV2Service.setSubnets(AwsArnUtils.parse(arn).region(), arn,
|
||||
prior.isEmpty() ? List.of() : List.of(prior.split(",")));
|
||||
List<String> priorSubnets = prior.isEmpty() ? List.of() : List.of(prior.split(","));
|
||||
elbV2Service.setSubnets(AwsArnUtils.parse(arn).region(), arn, priorSubnets);
|
||||
recordUsedSubnets(resource, priorSubnets);
|
||||
resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);
|
||||
return true;
|
||||
}
|
||||
@@ -165,17 +168,19 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
|
||||
LoadBalancer lb;
|
||||
List<String> onSubnets;
|
||||
try {
|
||||
lb = elbV2Service.createLoadBalancer(ctx.region(), name, scheme, type, ipAddressType,
|
||||
subnets, securityGroups, tags);
|
||||
onSubnets = subnetIds(lb);
|
||||
} catch (AwsException e) {
|
||||
if (!"DuplicateLoadBalancerName".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
lb = elbV2Service.describeLoadBalancers(ctx.region(), null, List.of(name), null, null).get(0);
|
||||
if (ctx.reusesPriorEntity(lb.getLoadBalancerArn())) {
|
||||
moveToTemplateSubnets(r, lb, subnets, ctx);
|
||||
}
|
||||
onSubnets = ctx.reusesPriorEntity(lb.getLoadBalancerArn())
|
||||
? moveToTemplateSubnets(r, lb, subnets, ctx)
|
||||
: subnetIds(lb);
|
||||
}
|
||||
|
||||
r.setPhysicalId(lb.getLoadBalancerArn());
|
||||
@@ -184,6 +189,23 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
|
||||
r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
|
||||
r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
|
||||
recordUsedSubnets(r, onSubnets);
|
||||
}
|
||||
|
||||
private static List<String> subnetIds(LoadBalancer lb) {
|
||||
return lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the subnets the balancer is on as uses attributes. EC2 refuses to delete a subnet a
|
||||
* load balancer still uses, and once the template no longer names the balancer, as when an
|
||||
* update removes it together with a subnet it is on, these are what orders it before them.
|
||||
*/
|
||||
private static void recordUsedSubnets(StackResource r, List<String> subnetIds) {
|
||||
r.getAttributes().keySet().removeIf(key -> key.startsWith(USED_SUBNET_ATTR_PREFIX));
|
||||
for (int i = 0; i < subnetIds.size(); i++) {
|
||||
r.getAttributes().put(USED_SUBNET_ATTR_PREFIX + (i + 1), subnetIds.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,18 +244,21 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code Subnets} is not create-only, so an update that keeps the balancer moves it onto the
|
||||
* template's subnets in place, as SetSubnets does, rather than leaving it on a subnet the template
|
||||
* dropped or replaced and the update cleanup then deletes. The prior list is kept for a rollback.
|
||||
* {@code Subnets} and {@code SubnetMappings} are not create-only, so an update that keeps the
|
||||
* balancer moves it onto the template's subnets in place, as SetSubnets does. That also releases
|
||||
* the subnets it leaves, which EC2 refuses to delete while a load balancer still uses them, so the
|
||||
* update cleanup can delete a subnet the template dropped or replaced. The prior list is kept for
|
||||
* a rollback. Returns the subnets the balancer is on afterwards.
|
||||
*/
|
||||
private void moveToTemplateSubnets(StackResource r, LoadBalancer lb, List<String> subnets,
|
||||
ProvisionContext ctx) {
|
||||
List<String> current = lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList();
|
||||
private List<String> moveToTemplateSubnets(StackResource r, LoadBalancer lb, List<String> subnets,
|
||||
ProvisionContext ctx) {
|
||||
List<String> current = subnetIds(lb);
|
||||
if (subnets.isEmpty() || Set.copyOf(subnets).equals(Set.copyOf(current))) {
|
||||
return;
|
||||
return current;
|
||||
}
|
||||
elbV2Service.setSubnets(ctx.region(), lb.getLoadBalancerArn(), subnets);
|
||||
r.getAttributes().put(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR, String.join(",", current));
|
||||
return subnets;
|
||||
}
|
||||
|
||||
private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
|
||||
@@ -135,6 +135,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -313,6 +314,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
private final List<VpcRouteTableListener> routeTableListeners = new CopyOnWriteArrayList<>();
|
||||
private jakarta.enterprise.inject.Instance<Ec2InstanceLaunchListener> instanceLaunchListenersInstance;
|
||||
private final List<Ec2InstanceLaunchListener> instanceLaunchListeners = new CopyOnWriteArrayList<>();
|
||||
// Fully qualified to tell the CDI Instance from the EC2 model Instance. Only the CDI constructor
|
||||
// receives it; null on the hand-built constructors, which reads as "nothing else uses a subnet".
|
||||
private jakarta.enterprise.inject.Instance<VpcDependencyProvider> vpcDependencyProviders;
|
||||
|
||||
public void addRouteTableListener(VpcRouteTableListener listener) {
|
||||
if (listener != null && !this.routeTableListeners.contains(listener)) {
|
||||
@@ -444,7 +448,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
Ec2VolumeBlockDeviceManager volumeBlockDeviceManager,
|
||||
jakarta.enterprise.inject.Instance<VpcRouteTableListener> routeTableListenersInstance,
|
||||
jakarta.enterprise.inject.Instance<Ec2InstanceLaunchListener> instanceLaunchListenersInstance,
|
||||
Ec2EbsEncryptionService ebsEncryptionService) {
|
||||
Ec2EbsEncryptionService ebsEncryptionService,
|
||||
jakarta.enterprise.inject.Instance<VpcDependencyProvider> vpcDependencyProviders) {
|
||||
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
|
||||
instanceTypeCatalog, storageFactory, requestContextInstance, iamService, volumeBlockDeviceManager);
|
||||
this.vpcNetworkManager = vpcNetworkManager;
|
||||
@@ -452,6 +457,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
this.routeTableListenersInstance = routeTableListenersInstance;
|
||||
this.instanceLaunchListenersInstance = instanceLaunchListenersInstance;
|
||||
this.ebsEncryptionService = ebsEncryptionService;
|
||||
this.vpcDependencyProviders = vpcDependencyProviders;
|
||||
}
|
||||
|
||||
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
|
||||
@@ -2439,6 +2445,32 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return lockFor(key(region, "transit-gateway-attachments"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs an action that checks subnets and then records a reference to them, holding the lock
|
||||
* {@link #deleteSubnet} and {@link #deleteVpc} take while they ask each
|
||||
* {@link VpcDependencyProvider} whether anything still uses what they delete. Without it the
|
||||
* check and the write straddle the delete: the delete sees no reference because the referring
|
||||
* resource is not saved yet, removes the subnet, and the resource is then saved pointing at a
|
||||
* subnet that is gone.
|
||||
*
|
||||
* <p>Safe to call from inside a provider's own monitor, because the ordering only ever runs one
|
||||
* way. The deletes hold this lock while calling the providers, and their dependency checks are
|
||||
* plain reads over the provider's own store that take no provider monitor, so EC2 never waits on
|
||||
* a provider while a provider waits on EC2.
|
||||
*/
|
||||
public <T> T supplyWithSubnetReferencesHeld(String region, Supplier<T> action) {
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
return action.get();
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link #supplyWithSubnetReferencesHeld} for an action with no result. */
|
||||
public void runWithSubnetReferencesHeld(String region, Runnable action) {
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
action.run();
|
||||
}
|
||||
}
|
||||
|
||||
private TransitGatewayVpcAttachmentOptions resolveAttachmentOptions(
|
||||
TransitGatewayVpcAttachmentOptions requested) {
|
||||
TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();
|
||||
@@ -5346,6 +5378,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
requireNoTransitGatewayAttachment(region,
|
||||
attachment -> vpcId.equals(attachment.getVpcId()),
|
||||
"The vpc '" + vpcId + "' has dependencies and cannot be deleted.");
|
||||
requireNoProviderDependency(provider -> provider.hasVpcDependency(region, vpcId),
|
||||
"The vpc '" + vpcId + "' has dependencies and cannot be deleted.");
|
||||
requireNoVpcDependents(region, vpcId);
|
||||
deleteVpcDefaultResources(region, vpcId);
|
||||
vpcs.delete(key(region, vpcId));
|
||||
@@ -6566,6 +6600,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
|
||||
requireNoSubnetResidents(region, Set.of(subnetId),
|
||||
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
|
||||
requireNoProviderDependency(provider -> provider.hasSubnetDependency(region, subnetId),
|
||||
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
|
||||
subnets.delete(key(region, subnetId));
|
||||
}
|
||||
if (vpcNetworkManager != null) {
|
||||
@@ -6588,6 +6624,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to delete a subnet or VPC that another service still uses, such as a load balancer.
|
||||
* Called under {@link #attachmentTopologyLock}, which those services hold through
|
||||
* {@link #supplyWithSubnetReferencesHeld} while they record a reference, so no reference can
|
||||
* appear between this check and the delete.
|
||||
*/
|
||||
private void requireNoProviderDependency(Predicate<VpcDependencyProvider> dependsOnIt, String message) {
|
||||
if (vpcDependencyProviders != null && vpcDependencyProviders.stream().anyMatch(dependsOnIt)) {
|
||||
throw new AwsException("DependencyViolation", message, 400);
|
||||
}
|
||||
}
|
||||
|
||||
public void modifySubnetAttribute(String region, String subnetId, String attribute, String value) {
|
||||
ensureDefaultResources(region);
|
||||
Subnet subnet = requireSubnet(region, subnetId);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
/**
|
||||
* Implemented by services whose resources reference EC2 subnets or VPCs, so DeleteSubnet and
|
||||
* DeleteVpc refuse to remove one that is still in use. Answers come from the owning service's
|
||||
* current, account-scoped state, as plain reads that take no lock of that service.
|
||||
*
|
||||
* <p>A service records a reference inside {@link Ec2Service#supplyWithSubnetReferencesHeld}, which
|
||||
* holds the lock EC2 holds while it asks these questions and deletes, so a delete cannot pass its
|
||||
* check while a reference is being published.
|
||||
*/
|
||||
public interface VpcDependencyProvider {
|
||||
boolean hasSubnetDependency(String region, String subnetId);
|
||||
|
||||
boolean hasVpcDependency(String region, String vpcId);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.VpcDependencyProvider;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.*;
|
||||
import io.github.hectorvent.floci.services.iam.ServerCertificateReferenceProvider;
|
||||
@@ -34,7 +35,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider {
|
||||
public class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider, VpcDependencyProvider {
|
||||
|
||||
@Inject
|
||||
ElbV2DataPlane dataPlane;
|
||||
@@ -195,10 +196,23 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
|
||||
// ── Load Balancers ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Resolving the subnets and publishing the balancer happen under EC2's subnet lock, so a
|
||||
* DeleteSubnet cannot pass its dependency check in between and leave the balancer on a subnet
|
||||
* that is gone.
|
||||
*/
|
||||
public LoadBalancer createLoadBalancer(String region, String name, String scheme,
|
||||
String type, String ipAddressType,
|
||||
List<String> subnets, List<String> securityGroups,
|
||||
Map<String, String> initialTags) {
|
||||
return ec2Service.supplyWithSubnetReferencesHeld(region, () -> createLoadBalancerWithSubnetsHeld(
|
||||
region, name, scheme, type, ipAddressType, subnets, securityGroups, initialTags));
|
||||
}
|
||||
|
||||
private LoadBalancer createLoadBalancerWithSubnetsHeld(String region, String name, String scheme,
|
||||
String type, String ipAddressType,
|
||||
List<String> subnets, List<String> securityGroups,
|
||||
Map<String, String> initialTags) {
|
||||
validateName(name, "load balancer");
|
||||
Map<String, LoadBalancer> regionLbs = loadBalancers.computeIfAbsent(region, k -> new ConcurrentHashMap<>());
|
||||
boolean duplicate = regionLbs.values().stream()
|
||||
@@ -241,6 +255,23 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
return lb;
|
||||
}
|
||||
|
||||
/**
|
||||
* A subnet is in use while a load balancer is configured with it. Account-scoped through the
|
||||
* request-scoped storage, and a target group does not count: it pins nothing in AWS either.
|
||||
*/
|
||||
@Override
|
||||
public boolean hasSubnetDependency(String region, String subnetId) {
|
||||
return loadBalancers.getOrDefault(region, Map.of()).values().stream()
|
||||
.anyMatch(lb -> lb.getAvailabilityZones().stream()
|
||||
.anyMatch(zone -> subnetId.equals(zone.getSubnetId())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasVpcDependency(String region, String vpcId) {
|
||||
return loadBalancers.getOrDefault(region, Map.of()).values().stream()
|
||||
.anyMatch(lb -> vpcId.equals(lb.getVpcId()));
|
||||
}
|
||||
|
||||
private String loadBalancerDnsSuffix() {
|
||||
if (config == null) {
|
||||
return EmbeddedDnsServer.DEFAULT_SUFFIX;
|
||||
@@ -336,18 +367,21 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
persistRegion(loadBalancers, region);
|
||||
}
|
||||
|
||||
/** Under EC2's subnet lock for the same reason as {@link #createLoadBalancer}. */
|
||||
public void setSubnets(String region, String arn, List<String> subnets) {
|
||||
LoadBalancer lb = requireLoadBalancer(region, arn);
|
||||
String vpcId = resolveSubnetVpcId(region, lb.getType(), subnets);
|
||||
if (vpcId != null && lb.getVpcId() != null && !lb.getVpcId().equals(vpcId)) {
|
||||
throw new AwsException("InvalidConfigurationRequest",
|
||||
"All subnets must belong to the load balancer VPC.", 400);
|
||||
}
|
||||
lb.setAvailabilityZones(resolveAvailabilityZones(region, subnets));
|
||||
if (vpcId != null) {
|
||||
lb.setVpcId(vpcId);
|
||||
}
|
||||
persistRegion(loadBalancers, region);
|
||||
ec2Service.runWithSubnetReferencesHeld(region, () -> {
|
||||
LoadBalancer lb = requireLoadBalancer(region, arn);
|
||||
String vpcId = resolveSubnetVpcId(region, lb.getType(), subnets);
|
||||
if (vpcId != null && lb.getVpcId() != null && !lb.getVpcId().equals(vpcId)) {
|
||||
throw new AwsException("InvalidConfigurationRequest",
|
||||
"All subnets must belong to the load balancer VPC.", 400);
|
||||
}
|
||||
lb.setAvailabilityZones(resolveAvailabilityZones(region, subnets));
|
||||
if (vpcId != null) {
|
||||
lb.setVpcId(vpcId);
|
||||
}
|
||||
persistRegion(loadBalancers, region);
|
||||
});
|
||||
}
|
||||
|
||||
public void setIpAddressType(String region, String arn, String ipAddressType) {
|
||||
|
||||
Reference in new issue
Block a user