fix(autoscaling): balance scale-out across zones and subnets (#5525)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-14 13:48:06 -04:00
1 parent 60d4d6b7a5
commit 6442d75115
9 files changed
+774 -78

No files matched your search

@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.elb.ElbClassicService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
@@ -28,6 +29,7 @@ import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -41,6 +43,7 @@ import java.util.stream.Collectors;
public class AutoScalingReconciler {
private static final Logger LOG = Logger.getLogger(AutoScalingReconciler.class);
private static final String SCALE_OUT_CAUSE = "An instance was started in response to a desired capacity change.";
/** The codes DescribeLaunchTemplates raises for an explicit name or id that does not exist. */
private static final Set<String> LAUNCH_TEMPLATE_NOT_FOUND_CODES =
@@ -116,8 +119,8 @@ public class AutoScalingReconciler {
try {
reconcile(asg);
} catch (Exception e) {
LOG.warnv("Reconcile failed for ASG {0} in account {1}: {2}",
asg.getAutoScalingGroupName(), accountId, e.getMessage());
LOG.warnv(e, "Reconcile failed for ASG {0} in account {1}",
asg.getAutoScalingGroupName(), accountId);
}
}
} catch (Exception e) {
@@ -136,14 +139,16 @@ public class AutoScalingReconciler {
int desired = asg.getDesiredCapacity();
if (activeCapacity < desired && !asg.getSuspendedProcesses().contains("Launch")) {
scaleOut(asg, (int) (desired - activeCapacity));
if (!scaleOut(asg, (int) (desired - activeCapacity))) {
return;
}
} else if (activeCapacity > desired && !asg.getSuspendedProcesses().contains("Terminate")) {
scaleIn(asg, (int) (activeCapacity - desired));
}
if (asgService.saveAutoScalingGroupIfPresent(asg)) {
asgService.completeInstanceRefreshIfSettled(asg.getRegion(), asg.getAutoScalingGroupName());
}
});
if (asgService.saveAutoScalingGroupIfPresent(asg)) {
asgService.completeInstanceRefreshIfSettled(asg.getRegion(), asg.getAutoScalingGroupName());
}
}
static long activeCapacity(AutoScalingGroup asg) {
@@ -177,7 +182,7 @@ public class AutoScalingReconciler {
changed = true;
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
"Launching a new EC2 instance: " + asgInst.getInstanceId(),
"An instance was started in response to a desired capacity change.",
SCALE_OUT_CAUSE,
"Successful");
LOG.infov("ASG {0}: instance {1} is now InService",
asg.getAutoScalingGroupName(), asgInst.getInstanceId());
@@ -343,65 +348,162 @@ public class AutoScalingReconciler {
return "Pending".equals(state) || "InService".equals(state);
}
private void scaleOut(AutoScalingGroup asg, int count) {
private boolean scaleOut(AutoScalingGroup asg, int count) {
LaunchSource launchSource = resolveLaunchSource(asg);
if (launchSource == null) {
LOG.warnv("ASG {0}: no launch source found, cannot scale out", asg.getAutoScalingGroupName());
return;
return true;
}
LOG.infov("ASG {0}: scaling out by {1}", asg.getAutoScalingGroupName(), count);
String az = asg.getAvailabilityZones().isEmpty()
? asg.getRegion() + "a"
: asg.getAvailabilityZones().get(0);
String subnetId = asg.getSubnetIds().isEmpty() ? null : asg.getSubnetIds().get(0);
List<String> launchedInstanceIds = new ArrayList<>();
RuntimeException launchFailure = null;
try {
Reservation reservation = ec2Service.runInstances(
asg.getRegion(),
launchSource.imageId(),
launchSource.instanceType(),
count, count,
launchSource.keyName(),
launchSource.securityGroupIds(),
subnetId,
null,
propagatedInstanceTags(asg, launchSource),
launchSource.userData(),
launchSource.iamInstanceProfile(),
launchSource.associatePublicIpAddress(), null, 0, null, null, null,
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
: encodeLegacyUserData(launchSource.userData()));
List<LaunchPlacement> placements = new ArrayList<>(launchPlacements(asg));
for (int index = 0; index < count; index++) {
LaunchPlacement placement = leastPopulatedPlacement(asg, placements);
Reservation reservation = ec2Service.runInstances(
asg.getRegion(),
launchSource.imageId(),
launchSource.instanceType(),
1, 1,
launchSource.keyName(),
launchSource.securityGroupIds(),
placement.subnetId(),
null,
propagatedInstanceTags(asg, launchSource),
launchSource.userData(),
launchSource.iamInstanceProfile(),
launchSource.associatePublicIpAddress(), null, 0, null, null, null,
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
: encodeLegacyUserData(launchSource.userData()));
List<String> launchedInstanceIds = new ArrayList<>();
for (Instance ec2Inst : reservation.getInstances()) {
AsgInstance asgInst = new AsgInstance();
asgInst.setInstanceId(ec2Inst.getInstanceId());
asgInst.setAvailabilityZone(az);
asgInst.setLifecycleState("Pending");
asgInst.setHealthStatus("Healthy");
asgInst.setLaunchConfigurationName(launchSource.launchConfigurationName());
asgInst.setLaunchTemplateId(launchSource.launchTemplateId());
asgInst.setLaunchTemplateName(launchSource.launchTemplateName());
asgInst.setLaunchTemplateVersion(launchSource.launchTemplateVersion());
asgInst.setInstanceType(launchSource.instanceType());
asg.getInstances().add(asgInst);
launchedInstanceIds.add(ec2Inst.getInstanceId());
LOG.infov("ASG {0}: launched instance {1} (Pending)",
asg.getAutoScalingGroupName(), ec2Inst.getInstanceId());
}
if (!asgService.saveAutoScalingGroupIfPresent(asg) && !launchedInstanceIds.isEmpty()) {
try {
ec2Service.terminateInstances(asg.getRegion(), launchedInstanceIds);
} catch (Exception e) {
LOG.warnv("ASG {0}: failed to clean up instances {1} after group deletion: {2}",
asg.getAutoScalingGroupName(), launchedInstanceIds, e.getMessage());
for (Instance ec2Inst : reservation.getInstances()) {
AsgInstance asgInst = new AsgInstance();
asgInst.setInstanceId(ec2Inst.getInstanceId());
asgInst.setAvailabilityZone(placement.subnetId() == null && placement.availabilityZone() != null
? placement.availabilityZone() : ec2Inst.getPlacement() != null
? ec2Inst.getPlacement().getAvailabilityZone() : placement.availabilityZone());
asgInst.setLifecycleState("Pending");
asgInst.setHealthStatus("Healthy");
asgInst.setLaunchConfigurationName(launchSource.launchConfigurationName());
asgInst.setLaunchTemplateId(launchSource.launchTemplateId());
asgInst.setLaunchTemplateName(launchSource.launchTemplateName());
asgInst.setLaunchTemplateVersion(launchSource.launchTemplateVersion());
asgInst.setInstanceType(launchSource.instanceType());
asg.getInstances().add(asgInst);
launchedInstanceIds.add(ec2Inst.getInstanceId());
LOG.infov("ASG {0}: launched instance {1} (Pending)",
asg.getAutoScalingGroupName(), ec2Inst.getInstanceId());
}
if (placement.subnetId() != null) {
placements.set(placements.indexOf(placement), new LaunchPlacement(placement.subnetId(),
placement.availabilityZone(), Math.max(0,
placement.availableIpAddresses() - reservation.getInstances().size()),
placement.requiresIpv4Address()));
}
}
} catch (Exception e) {
LOG.warnv("ASG {0}: failed to launch instances: {1}",
asg.getAutoScalingGroupName(), e.getMessage());
} catch (RuntimeException e) {
launchFailure = e;
}
// Preserve successful allocations even if a later single-instance launch fails.
if (!launchedInstanceIds.isEmpty()) {
try {
preserveScaleOutAllocations(asg, launchedInstanceIds);
} catch (RuntimeException persistenceFailure) {
if (launchFailure != null) {
launchFailure.addSuppressed(persistenceFailure);
throw launchFailure;
}
throw persistenceFailure;
}
}
if (launchFailure instanceof AwsException) {
String description = "Launching a new EC2 instance.";
String message = statusMessage(launchFailure, " Launching EC2 instance failed.");
recordFailedActivity(asg, description + " Status Reason: " + message,
SCALE_OUT_CAUSE, message, description);
return false;
}
if (launchFailure != null) {
throw launchFailure;
}
return true;
}
private void preserveScaleOutAllocations(AutoScalingGroup asg, List<String> launchedInstanceIds) {
RuntimeException saveFailure = null;
try {
if (asgService.saveAutoScalingGroupIfPresent(asg)) {
return;
}
} catch (RuntimeException e) {
saveFailure = e;
}
try {
ec2Service.terminateInstances(asg.getRegion(), launchedInstanceIds);
asg.getInstances().removeIf(instance -> launchedInstanceIds.contains(instance.getInstanceId()));
} catch (RuntimeException cleanupFailure) {
if (saveFailure == null) {
throw cleanupFailure;
}
saveFailure.addSuppressed(cleanupFailure);
}
if (saveFailure != null) {
throw saveFailure;
}
}
private List<LaunchPlacement> launchPlacements(AutoScalingGroup asg) {
if (!asg.getSubnetIds().isEmpty()) {
Map<String, Subnet> subnets = ec2Service.describeSubnets(asg.getRegion(), asg.getSubnetIds(), Map.of())
.stream().collect(Collectors.toMap(Subnet::getSubnetId, subnet -> subnet));
List<LaunchPlacement> placements = new ArrayList<>();
for (String id : asg.getSubnetIds()) {
Subnet subnet = subnets.get(id);
if (subnet == null) {
throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + id + "' does not exist", 400);
}
// Subnets remain authoritative when an update leaves older zone metadata behind.
placements.add(new LaunchPlacement(id, subnet.getAvailabilityZone(), subnet.getAvailableIpAddressCount(),
subnet.getCidrBlock() != null && !subnet.getCidrBlock().isBlank()));
}
return placements;
}
if (!asg.getAvailabilityZones().isEmpty()) {
return asg.getAvailabilityZones().stream().map(zone -> new LaunchPlacement(null, zone, 0, false)).toList();
}
return List.of(new LaunchPlacement(null, null, 0, false));
}
private LaunchPlacement leastPopulatedPlacement(AutoScalingGroup asg, List<LaunchPlacement> placements) {
Map<String, Long> zoneCounts = new LinkedHashMap<>();
for (LaunchPlacement placement : placements) {
zoneCounts.putIfAbsent(placement.availabilityZone(), 0L);
}
for (AsgInstance instance : asg.getInstances()) {
if (!isActiveLifecycleState(instance.getLifecycleState())) {
continue;
}
Instance actual = asg.getSubnetIds().isEmpty() ? null
: ec2Service.getInstance(asg.getRegion(), instance.getInstanceId()).orElse(null);
String zone = actual != null && actual.getPlacement() != null
? actual.getPlacement().getAvailabilityZone() : instance.getAvailabilityZone();
if (zoneCounts.containsKey(zone)) {
zoneCounts.compute(zone, (ignored, count) -> count + 1);
}
}
Comparator<LaunchPlacement> preference = Comparator
.comparingLong((LaunchPlacement placement) -> zoneCounts.get(placement.availabilityZone()))
.thenComparing(Comparator.comparingInt(LaunchPlacement::availableIpAddresses).reversed());
return placements.stream()
.filter(placement -> !placement.requiresIpv4Address() || placement.availableIpAddresses() > 0)
.min(preference)
.orElseGet(() -> placements.stream().min(preference).orElseThrow());
}
private record LaunchPlacement(String subnetId, String availabilityZone, int availableIpAddresses,
boolean requiresIpv4Address) {}
private static List<io.github.hectorvent.floci.services.ec2.model.Tag> propagatedInstanceTags(
AutoScalingGroup asg,
LaunchSource launchSource) {
@@ -459,15 +561,20 @@ public class AutoScalingReconciler {
/**
* Records a failed scaling activity with the error text, matching AWS (100% progress and a
* {@code StatusMessage}). A failure that repeats on a later pass with the same error, because
* termination keeps failing, is not recorded again: the latest activity with the same
* scaling keeps failing, is not recorded again: the latest activity with the same
* description already records it, whatever other activities were recorded after it. A
* different error is recorded, so the history carries the current reason.
*/
private void recordFailedActivity(AutoScalingGroup asg, String description, String cause, Exception failure) {
String statusMessage = statusMessage(failure);
recordFailedActivity(asg, description, cause, statusMessage(failure, ""), description);
}
private void recordFailedActivity(AutoScalingGroup asg, String description, String cause,
String statusMessage, String descriptionPrefix) {
ScalingActivity previous = asgService.describeScalingActivities(asg.getRegion(), asg.getAutoScalingGroupName())
.stream()
.filter(activity -> description.equals(activity.getDescription()))
.filter(activity -> activity.getDescription() != null
&& activity.getDescription().startsWith(descriptionPrefix))
.findFirst()
.orElse(null);
if (previous != null && "Failed".equals(previous.getStatusCode())
@@ -479,17 +586,16 @@ public class AutoScalingReconciler {
asgService.completeActivity(activity.getActivityId(), "Failed", statusMessage);
}
private static String statusMessage(Exception failure) {
private static String statusMessage(Exception failure, String suffix) {
String message = failure.getMessage() != null && !failure.getMessage().isBlank()
? failure.getMessage()
: failure.getClass().getSimpleName();
if (message.length() <= STATUS_MESSAGE_MAX_LENGTH) {
return message;
int maxLength = STATUS_MESSAGE_MAX_LENGTH - suffix.length();
if (message.length() <= maxLength) {
return message + suffix;
}
int end = Character.isHighSurrogate(message.charAt(STATUS_MESSAGE_MAX_LENGTH - 1))
? STATUS_MESSAGE_MAX_LENGTH - 1
: STATUS_MESSAGE_MAX_LENGTH;
return message.substring(0, end);
int end = Character.isHighSurrogate(message.charAt(maxLength - 1)) ? maxLength - 1 : maxLength;
return message.substring(0, end) + suffix;
}
private void deregisterFromTargetGroups(AutoScalingGroup asg, List<String> instanceIds) {
@@ -3833,12 +3833,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/** Every private address a live instance, network interface or NAT gateway holds in the subnet. */
private Set<String> privateIpsInUse(String region, String subnetId) {
return new HashSet<>(privateIpsBySubnet(region).getOrDefault(subnetId, Set.of()));
}
private Map<String, Set<String>> privateIpsBySubnet(String region) {
String regionPrefix = region + "::";
Set<String> inUse = new HashSet<>();
Map<String, Set<String>> bySubnet = new HashMap<>();
for (NetworkInterface ni : networkInterfaces.scan(k -> k.startsWith(regionPrefix))) {
if (!Objects.equals(subnetId, ni.getSubnetId())) {
continue;
}
Set<String> inUse = bySubnet.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>());
addIfSet(inUse, ni.getPrivateIpAddress());
for (NetworkInterfacePrivateIpAddress ip : nullToEmpty(ni.getPrivateIpAddresses())) {
addIfSet(inUse, ip.getPrivateIpAddress());
@@ -3849,24 +3851,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if ("terminated".equals(state)) {
continue;
}
if (Objects.equals(subnetId, instance.getSubnetId())) {
addIfSet(inUse, instance.getPrivateIpAddress());
}
addIfSet(bySubnet.computeIfAbsent(instance.getSubnetId(), ignored -> new HashSet<>()),
instance.getPrivateIpAddress());
for (InstanceNetworkInterface ni : nullToEmpty(instance.getNetworkInterfaces())) {
if (Objects.equals(subnetId, ni.getSubnetId())) {
addIfSet(inUse, ni.getPrivateIpAddress());
}
addIfSet(bySubnet.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>()),
ni.getPrivateIpAddress());
}
}
for (NatGateway natGateway : natGateways.scan(k -> k.startsWith(regionPrefix))) {
if (!Objects.equals(subnetId, natGateway.getSubnetId()) || "deleted".equals(natGateway.getState())) {
if ("deleted".equals(natGateway.getState())) {
continue;
}
Set<String> inUse = bySubnet.computeIfAbsent(natGateway.getSubnetId(), ignored -> new HashSet<>());
for (NatGatewayAddress address : nullToEmpty(natGateway.getNatGatewayAddresses())) {
addIfSet(inUse, address.getPrivateIp());
}
}
return inUse;
return bySubnet;
}
private static <T> List<T> nullToEmpty(List<T> list) {
@@ -5751,7 +5752,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
subnet.setState("available");
subnet.setAvailabilityZone(zoneName);
subnet.setAvailabilityZoneId(AvailabilityZoneIds.forZoneName(region, zoneName));
subnet.setAvailableIpAddressCount(251);
subnet.setAvailableIpAddressCount(availableSubnetAddresses(subnet, Set.of()));
String ownerAccountId = callerAccountId();
subnet.setOwnerId(ownerAccountId);
subnet.setRegion(region);
@@ -5862,11 +5863,42 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<Subnet> describeSubnets(String region, List<String> subnetIds, Map<String, List<String>> filters) {
ensureDefaultResources(region);
return subnets.scan(k -> true).stream()
List<Subnet> result = subnets.scan(k -> true).stream()
.filter(s -> s.getRegion().equals(region))
.filter(s -> subnetIds.isEmpty() || subnetIds.contains(s.getSubnetId()))
.filter(s -> matchesFilters(s, filters, region))
.collect(Collectors.toList());
if (result.isEmpty()) {
return result;
}
Map<String, Set<String>> inUse = privateIpsBySubnet(region);
Map<String, Set<Long>> occupiedBySubnet = new HashMap<>();
inUse.forEach((id, addresses) -> occupiedBySubnet.put(id, addressValues(addresses)));
// Seed empty subnets too, so endpoint derivation never needs another resource-store scan.
result.forEach(subnet -> occupiedBySubnet.putIfAbsent(subnet.getSubnetId(), Set.of()));
for (VpcEndpoint endpoint : vpcEndpoints.scan(k -> true)) {
if (!region.equals(endpoint.getRegion()) || !"Interface".equalsIgnoreCase(endpoint.getVpcEndpointType())) {
continue;
}
endpoint.getSubnetIds().forEach(id -> occupiedBySubnet.putIfAbsent(id, Set.of()));
for (NetworkInterface ni : endpointNetworkInterfacesOf(endpoint, occupiedBySubnet)) {
addIfSet(inUse.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>()),
ni.getPrivateIpAddress());
}
}
for (Subnet subnet : result) {
subnet.setAvailableIpAddressCount(availableSubnetAddresses(subnet,
inUse.getOrDefault(subnet.getSubnetId(), Set.of())));
}
return result;
}
private static int availableSubnetAddresses(Subnet subnet, Set<String> inUse) {
return Cidr4.parse(subnet.getCidrBlock()).map(cidr -> {
long occupied = addressValues(inUse).stream()
.filter(address -> address >= cidr.network() + 4 && address < cidr.broadcast()).count();
return (int) Math.max(0, cidr.size() - 5 - occupied);
}).orElse(0);
}
public void deleteSubnet(String region, String subnetId) {