mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(autoscaling): balance scale-out across zones and subnets (#5525)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
60d4d6b7a5
commit
6442d75115
9 files changed
+774
-78
No files matched your search
@@ -0,0 +1,63 @@
|
||||
"""Synchronous placement inputs, checked against live AWS on 2026-10-12."""
|
||||
|
||||
import uuid
|
||||
from contextlib import ExitStack, closing
|
||||
|
||||
import boto3
|
||||
|
||||
|
||||
def test_subnet_counts_track_address_allocation(ec2_client):
|
||||
with ExitStack() as cleanup:
|
||||
vpc = ec2_client.create_vpc(CidrBlock="10.98.0.0/16")["Vpc"]["VpcId"]
|
||||
cleanup.callback(ec2_client.delete_vpc, VpcId=vpc)
|
||||
for cidr, capacity in [("10.98.0.0/28", 11), ("10.98.1.0/24", 251)]:
|
||||
subnet = ec2_client.create_subnet(VpcId=vpc, CidrBlock=cidr)["Subnet"]
|
||||
subnet_id = subnet["SubnetId"]
|
||||
cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet_id)
|
||||
assert subnet["AvailableIpAddressCount"] == capacity
|
||||
interface = ec2_client.create_network_interface(SubnetId=subnet_id)["NetworkInterface"]
|
||||
try:
|
||||
described = ec2_client.describe_subnets(SubnetIds=[subnet_id])["Subnets"][0]
|
||||
assert described["AvailableIpAddressCount"] == capacity - 1
|
||||
finally:
|
||||
ec2_client.delete_network_interface(NetworkInterfaceId=interface["NetworkInterfaceId"])
|
||||
described = ec2_client.describe_subnets(SubnetIds=[subnet_id])["Subnets"][0]
|
||||
assert described["AvailableIpAddressCount"] == capacity
|
||||
|
||||
|
||||
def test_zone_only_groups_accept_real_zones_outside_local_subnet_catalog(
|
||||
aws_config, client_config
|
||||
):
|
||||
name = "zone-placement-" + uuid.uuid4().hex[:12]
|
||||
aws_config = {**aws_config, "region_name": "us-east-1"}
|
||||
with (
|
||||
closing(boto3.client("ec2", config=client_config, **aws_config)) as ec2_client,
|
||||
closing(boto3.client("autoscaling", config=client_config, **aws_config)) as autoscaling,
|
||||
):
|
||||
with ExitStack() as cleanup:
|
||||
image = ec2_client.register_image(
|
||||
Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1"
|
||||
)["ImageId"]
|
||||
cleanup.callback(ec2_client.deregister_image, ImageId=image)
|
||||
template = ec2_client.create_launch_template(
|
||||
LaunchTemplateName=name,
|
||||
LaunchTemplateData={"ImageId": image, "InstanceType": "t3.nano"},
|
||||
)["LaunchTemplate"]["LaunchTemplateId"]
|
||||
cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template)
|
||||
autoscaling.create_auto_scaling_group(
|
||||
AutoScalingGroupName=name,
|
||||
MinSize=0, MaxSize=0, DesiredCapacity=0,
|
||||
LaunchTemplate={"LaunchTemplateId": template},
|
||||
AvailabilityZones=["us-east-1d"],
|
||||
)
|
||||
cleanup.callback(autoscaling.delete_auto_scaling_group,
|
||||
AutoScalingGroupName=name, ForceDelete=True)
|
||||
group = autoscaling.describe_auto_scaling_groups(
|
||||
AutoScalingGroupNames=[name])["AutoScalingGroups"][0]
|
||||
assert group["AvailabilityZones"] == ["us-east-1d"]
|
||||
autoscaling.update_auto_scaling_group(
|
||||
AutoScalingGroupName=name, AvailabilityZones=["us-east-1d", "us-east-1f"])
|
||||
group = autoscaling.describe_auto_scaling_groups(
|
||||
AutoScalingGroupNames=[name])["AutoScalingGroups"][0]
|
||||
assert group["AvailabilityZones"] == ["us-east-1d", "us-east-1f"]
|
||||
assert group["Instances"] == []
|
||||
@@ -39,6 +39,24 @@ and zero capacity. Both groups had identical configuration except for name, ARN
|
||||
and creation time. The SDK regression is
|
||||
`compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_whitespace.py`.
|
||||
|
||||
Scale-out follows the [AWS placement rules](https://docs.aws.amazon.com/autoscaling/ec2/userguide/auto-scaling-benefits.html):
|
||||
choose the zone with the fewest active instances, then its subnet with the most
|
||||
free IPv4 addresses. Declared subnets and actual EC2 placement take precedence
|
||||
over stale group zone metadata. Exhausted IPv4 subnets are skipped when another
|
||||
subnet has capacity. If all are full, EC2 reports the selected subnet's allocation
|
||||
error. IPv6-only subnets do not require free IPv4 addresses. Retrying another zone
|
||||
after a launch error and rebalancing without a capacity increase are not implemented.
|
||||
|
||||
AWS launch errors appear as failed scaling activities after preserving partial
|
||||
launches. Repeated identical failures reuse the recorded activity, following the
|
||||
scale-in behavior, and do not complete an instance refresh. Unexpected runtime,
|
||||
save and cleanup failures still propagate.
|
||||
|
||||
For groups configured only with Availability Zones, Floci preserves its unpinned
|
||||
EC2 launch behavior and counts each member under the requested zone. This permits
|
||||
real zones outside the local subnet catalog, such as `us-east-1d`; the underlying
|
||||
EC2 instance can use a default subnet in a different zone.
|
||||
|
||||
### Instance Management
|
||||
|
||||
| Operation | Notes |
|
||||
|
||||
@@ -960,6 +960,11 @@ and the last one as AWS reserves them, and skipping every address a persisted in
|
||||
interface or NAT gateway in the subnet still holds, so a restart does not hand one out twice. A
|
||||
subnet with no free address left fails the request with `InsufficientFreeAddressesInSubnet`.
|
||||
|
||||
`CreateSubnet` derives `AvailableIpAddressCount` from the IPv4 CIDR, excluding the
|
||||
five AWS-reserved addresses. `DescribeSubnets` subtracts addresses currently held
|
||||
by instances, network interfaces, NAT gateways and interface endpoints. ASG
|
||||
scale-out uses this count when selecting among subnets in the same zone.
|
||||
|
||||
## Requirements
|
||||
|
||||
EC2 requires the Docker socket to be accessible (same as Lambda, ECS, and other container services):
|
||||
|
||||
+170
-64
@@ -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) {
|
||||
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Placement;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.any;
|
||||
import static org.mockito.Mockito.anyInt;
|
||||
import static org.mockito.Mockito.anyList;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AutoScalingPlacementTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void changedSubnetsTakePrecedenceOverOlderZoneMetadata() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-b", REGION + "b"), List.of("subnet-b"));
|
||||
fixture.group.setAvailabilityZones(List.of(REGION + "a"));
|
||||
fixture.grow(2);
|
||||
assertEquals(Map.of(REGION + "b", 2L), fixture.counts());
|
||||
fixture.assertReportedZones();
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedSubnetsDoNotBlockOtherConfiguredZones() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.availableIps.put("subnet-a", 0);
|
||||
fixture.grow(2);
|
||||
assertEquals(Map.of(REGION + "b", 2L), fixture.counts());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneRemainingAddressIsNotSelectedAgainWithinTheSameScaleOut() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.availableIps.put("subnet-a", 1);
|
||||
fixture.availableIps.put("subnet-b", 10);
|
||||
fixture.grow(4);
|
||||
assertEquals(Map.of(REGION + "a", 1L, REGION + "b", 3L), fixture.counts());
|
||||
assertEquals(0, fixture.availableIps.get("subnet-a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSaveStillCleansUpSuccessfulAllocationsAndRethrows() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.saveFailure = new IllegalStateException("fixture save failure");
|
||||
assertEquals(fixture.saveFailure, assertThrows(IllegalStateException.class, () -> fixture.grow(2)));
|
||||
verify(fixture.ec2).terminateInstances(REGION, List.of("i-1", "i-2"));
|
||||
assertTrue(fixture.group.getInstances().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedGrowthBalancesActualZonesAndReportsEachInstancePlacement() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.grow(2);
|
||||
assertEquals(Map.of(REGION + "a", 1L, REGION + "b", 1L), fixture.counts());
|
||||
fixture.grow(3);
|
||||
assertEquals(Map.of(REGION + "a", 2L, REGION + "b", 1L), fixture.counts());
|
||||
fixture.grow(4);
|
||||
assertEquals(Map.of(REGION + "a", 2L, REGION + "b", 2L), fixture.counts());
|
||||
fixture.assertReportedZones();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unequalSubnetCountsDoNotWeightOneAvailabilityZoneMoreHeavily() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a1", REGION + "a", "subnet-a2", REGION + "a",
|
||||
"subnet-b", REGION + "b"), List.of("subnet-a1", "subnet-a2", "subnet-b"));
|
||||
fixture.grow(4);
|
||||
assertEquals(Map.of(REGION + "a", 2L, REGION + "b", 2L), fixture.counts());
|
||||
fixture.assertReportedZones();
|
||||
}
|
||||
|
||||
@Test
|
||||
void chosenZoneUsesTheSubnetWithTheMostAvailableAddresses() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-small", REGION + "a", "subnet-large", REGION + "a"),
|
||||
List.of("subnet-small", "subnet-large"));
|
||||
fixture.availableIps.put("subnet-small", 11);
|
||||
fixture.availableIps.put("subnet-large", 251);
|
||||
fixture.grow(2);
|
||||
assertEquals(List.of("subnet-large", "subnet-large"), fixture.instances.values().stream()
|
||||
.map(Instance::getSubnetId).toList());
|
||||
fixture.availableIps.put("subnet-small", 250);
|
||||
fixture.grow(3);
|
||||
assertEquals("subnet-small", fixture.instances.get("i-3").getSubnetId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleZoneSubnetsUseTheirActualZoneWithoutAnExplicitZoneList() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-b1", REGION + "b", "subnet-b2", REGION + "b"),
|
||||
List.of("subnet-b1", "subnet-b2"));
|
||||
fixture.grow(3);
|
||||
assertEquals(Map.of(REGION + "b", 3L), fixture.counts());
|
||||
fixture.assertReportedZones();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unmodelledZonesLaunchUnpinnedAndBalanceUnderTheirRequestedZones() {
|
||||
Fixture fixture = new Fixture(Map.of(), List.of());
|
||||
fixture.group.setAvailabilityZones(List.of(REGION + "d", REGION + "f"));
|
||||
fixture.grow(2);
|
||||
fixture.grow(3);
|
||||
fixture.grow(4);
|
||||
assertEquals(Map.of(REGION + "a", 4L), fixture.counts());
|
||||
assertEquals(Map.of(REGION + "d", 2L, REGION + "f", 2L), fixture.group.getInstances().stream()
|
||||
.collect(Collectors.groupingBy(instance -> instance.getAvailabilityZone(), Collectors.counting())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingEc2PlacementWinsOverStaleGroupZoneMetadata() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.grow(2);
|
||||
fixture.group.getInstances().forEach(instance -> instance.setAvailabilityZone(REGION + "a"));
|
||||
fixture.grow(3);
|
||||
assertEquals(REGION + "a", fixture.instances.get("i-3").getPlacement().getAvailabilityZone());
|
||||
assertEquals(Map.of(REGION + "a", 2L, REGION + "b", 1L), fixture.counts());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingDeclaredSubnetRefusesBeforeAnyAllocation() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a"),
|
||||
List.of("subnet-a", "subnet-missing"));
|
||||
fixture.grow(2);
|
||||
assertTrue(fixture.activities().getFirst().getStatusMessage().contains("subnet-missing"));
|
||||
assertEquals(Map.of(), fixture.instances);
|
||||
assertEquals(0, fixture.group.getInstances().size());
|
||||
verify(fixture.groups, never()).saveAutoScalingGroupIfPresent(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void laterAllocationFailureRetainsAlreadyLaunchedGroupMembers() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.failAfter = 1;
|
||||
fixture.grow(2);
|
||||
assertEquals(1, fixture.instances.size());
|
||||
assertEquals(List.of("i-1"), fixture.group.getInstances().stream()
|
||||
.map(instance -> instance.getInstanceId()).toList());
|
||||
assertTrue(fixture.savedMembers.contains(List.of("i-1")));
|
||||
ScalingActivity activity = fixture.activities().getFirst();
|
||||
assertEquals("Failed", activity.getStatusCode());
|
||||
assertEquals("fixture allocation failure Launching EC2 instance failed.", activity.getStatusMessage());
|
||||
assertEquals("Launching a new EC2 instance. Status Reason: " + activity.getStatusMessage(),
|
||||
activity.getDescription());
|
||||
assertEquals(100, activity.getProgress());
|
||||
assertNotNull(activity.getEndTime());
|
||||
fixture.grow(2);
|
||||
assertEquals(1, fixture.activities().size());
|
||||
fixture.launchFailure = new AwsException("RequestLimitExceeded", "request limit exceeded", 503);
|
||||
fixture.grow(2);
|
||||
assertEquals(2, fixture.activities().size());
|
||||
assertEquals("request limit exceeded Launching EC2 instance failed.",
|
||||
fixture.activities().getFirst().getStatusMessage());
|
||||
fixture.launchFailure = new AwsException("InsufficientInstanceCapacity", "fixture allocation failure", 400);
|
||||
fixture.grow(2);
|
||||
assertEquals(3, fixture.activities().size());
|
||||
verify(fixture.groups, never()).completeInstanceRefreshIfSettled(any(), any());
|
||||
fixture.failAfter = Integer.MAX_VALUE;
|
||||
fixture.grow(2);
|
||||
assertEquals(2, fixture.allocations);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedGroupAfterPartialFailureTerminatesOnlyItsSuccessfulAllocations() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.instances.put("i-unrelated", new Instance());
|
||||
fixture.failAfter = 1;
|
||||
fixture.deleteOnFailure = true;
|
||||
fixture.grow(2);
|
||||
assertTrue(fixture.savedMembers.contains(List.of("i-1")));
|
||||
verify(fixture.ec2).terminateInstances(REGION, List.of("i-1"));
|
||||
verify(fixture.ec2, times(1)).terminateInstances(eq(REGION), anyList());
|
||||
assertTrue(fixture.instances.containsKey("i-unrelated"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedPlacementsLetEc2ReportTheLeastPopulatedSubnetsFailure() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-b", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-b"));
|
||||
fixture.grow(1);
|
||||
fixture.availableIps.put("subnet-a", 0);
|
||||
fixture.availableIps.put("subnet-b", 0);
|
||||
fixture.grow(2);
|
||||
assertEquals("There are not enough free addresses in subnet 'subnet-b' to satisfy the requested "
|
||||
+ "number of instances. Launching EC2 instance failed.",
|
||||
fixture.activities().getFirst().getStatusMessage());
|
||||
assertEquals("An instance was started in response to a desired capacity change.",
|
||||
fixture.activities().getFirst().getCause());
|
||||
assertEquals(1, fixture.allocations);
|
||||
verify(fixture.groups, times(1)).completeInstanceRefreshIfSettled(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ipv6OnlySubnetsDoNotRequireFreeIpv4Addresses() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a", "subnet-v6", REGION + "b"),
|
||||
List.of("subnet-a", "subnet-v6"));
|
||||
fixture.ipv6Only.add("subnet-v6");
|
||||
fixture.availableIps.put("subnet-v6", 0);
|
||||
fixture.grow(4);
|
||||
assertEquals(Map.of(REGION + "a", 2L, REGION + "b", 2L), fixture.counts());
|
||||
assertTrue(fixture.activities().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedLaunchFailurePropagatesAfterSavingPartialAllocations() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a"), List.of("subnet-a"));
|
||||
fixture.failAfter = 1;
|
||||
fixture.launchFailure = new IllegalStateException("unexpected launch failure");
|
||||
assertSame(fixture.launchFailure, assertThrows(IllegalStateException.class, () -> fixture.grow(2)));
|
||||
assertEquals(List.of(List.of("i-1")), fixture.savedMembers);
|
||||
verify(fixture.ec2, never()).terminateInstances(any(), any());
|
||||
verify(fixture.groups, never()).completeInstanceRefreshIfSettled(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFailureRetainsSaveAndCleanupFailuresAsSuppressedExceptions() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a"), List.of("subnet-a"));
|
||||
fixture.failAfter = 1;
|
||||
fixture.saveFailure = new IllegalStateException("save failed");
|
||||
RuntimeException cleanupFailure = new IllegalStateException("cleanup failed");
|
||||
when(fixture.ec2.terminateInstances(REGION, List.of("i-1"))).thenThrow(cleanupFailure);
|
||||
assertSame(fixture.launchFailure, assertThrows(AwsException.class, () -> fixture.grow(2)));
|
||||
assertEquals(List.of(fixture.saveFailure), List.of(fixture.launchFailure.getSuppressed()));
|
||||
assertEquals(List.of(cleanupFailure), List.of(fixture.saveFailure.getSuppressed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedGroupCleanupFailurePropagates() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a"), List.of("subnet-a"));
|
||||
fixture.groupPresent = false;
|
||||
RuntimeException cleanupFailure = new IllegalStateException("cleanup failed");
|
||||
when(fixture.ec2.terminateInstances(REGION, List.of("i-1"))).thenThrow(cleanupFailure);
|
||||
assertSame(cleanupFailure, assertThrows(IllegalStateException.class, () -> fixture.grow(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduledReconciliationContinuesAfterOneGroupFails() {
|
||||
Fixture fixture = new Fixture(Map.of("subnet-a", REGION + "a"), List.of("subnet-a"));
|
||||
fixture.group.setDesiredCapacity(1);
|
||||
fixture.failAfter = 0;
|
||||
AutoScalingGroup healthyGroup = new AutoScalingGroup();
|
||||
healthyGroup.setRegion(REGION);
|
||||
healthyGroup.setAutoScalingGroupName("healthy-group");
|
||||
when(fixture.groups.autoScalingGroupAccountIds()).thenReturn(Set.of("000000000000"));
|
||||
when(fixture.groups.describeAutoScalingGroups(null, null)).thenReturn(List.of(fixture.group, healthyGroup));
|
||||
when(fixture.groups.saveAutoScalingGroupIfPresent(healthyGroup)).thenReturn(true);
|
||||
assertDoesNotThrow(fixture.reconciler::reconcileAll);
|
||||
verify(fixture.groups).completeInstanceRefreshIfSettled(REGION, "healthy-group");
|
||||
verify(fixture.groups, never()).completeInstanceRefreshIfSettled(REGION, "placement-group");
|
||||
}
|
||||
|
||||
private static class Fixture {
|
||||
final AutoScalingGroup group = new AutoScalingGroup();
|
||||
final Map<String, Instance> instances = new LinkedHashMap<>();
|
||||
final Map<String, Integer> availableIps = new LinkedHashMap<>();
|
||||
final List<String> ipv6Only = new ArrayList<>();
|
||||
final AutoScalingReconciler reconciler;
|
||||
final AutoScalingService groups = mock(AutoScalingService.class);
|
||||
final AutoScalingService activityStore = new AutoScalingService();
|
||||
final Ec2Service ec2 = mock(Ec2Service.class);
|
||||
final List<List<String>> savedMembers = new ArrayList<>();
|
||||
boolean groupPresent = true;
|
||||
boolean deleteOnFailure;
|
||||
int allocations;
|
||||
int failAfter = Integer.MAX_VALUE;
|
||||
RuntimeException saveFailure;
|
||||
RuntimeException launchFailure =
|
||||
new AwsException("InsufficientInstanceCapacity", "fixture allocation failure", 400);
|
||||
|
||||
Fixture(Map<String, String> zones, List<String> declaredSubnets) {
|
||||
reconciler = new AutoScalingReconciler(groups, ec2, mock(ElbV2Service.class));
|
||||
doAnswer(call -> {
|
||||
call.<Runnable>getArgument(1).run();
|
||||
return null;
|
||||
}).when(groups).adjustCapacityIfPresent(any(), any());
|
||||
when(groups.describeScalingActivities(anyString(), anyString())).thenAnswer(call ->
|
||||
activityStore.describeScalingActivities(call.getArgument(0), call.getArgument(1)));
|
||||
when(groups.recordActivity(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenAnswer(call -> activityStore.recordActivity(call.getArgument(0), call.getArgument(1),
|
||||
call.getArgument(2), call.getArgument(3), call.getArgument(4)));
|
||||
doAnswer(call -> {
|
||||
activityStore.completeActivity(call.getArgument(0), call.getArgument(1), call.getArgument(2));
|
||||
return null;
|
||||
}).when(groups).completeActivity(anyString(), anyString(), anyString());
|
||||
group.setRegion(REGION);
|
||||
group.setAutoScalingGroupName("placement-group");
|
||||
group.setLaunchConfigurationName("launch");
|
||||
group.setSubnetIds(declaredSubnets);
|
||||
LaunchConfiguration launch = new LaunchConfiguration();
|
||||
launch.setImageId("ami-test");
|
||||
launch.setInstanceType("m5.large");
|
||||
when(groups.describeLaunchConfigurations(REGION, List.of("launch"))).thenReturn(List.of(launch));
|
||||
when(groups.saveAutoScalingGroupIfPresent(group)).thenAnswer(call -> {
|
||||
savedMembers.add(group.getInstances().stream().map(instance -> instance.getInstanceId()).toList());
|
||||
if (saveFailure != null) {
|
||||
throw saveFailure;
|
||||
}
|
||||
return groupPresent;
|
||||
});
|
||||
List<Subnet> subnets = zones.entrySet().stream().map(entry -> {
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId(entry.getKey());
|
||||
subnet.setAvailabilityZone(entry.getValue());
|
||||
return subnet;
|
||||
}).toList();
|
||||
when(ec2.describeSubnets(eq(REGION), anyList(), any())).thenAnswer(call -> {
|
||||
subnets.forEach(subnet -> {
|
||||
subnet.setAvailableIpAddressCount(availableIps.getOrDefault(subnet.getSubnetId(), 251));
|
||||
subnet.setCidrBlock(ipv6Only.contains(subnet.getSubnetId()) ? null : "10.0.0.0/24");
|
||||
});
|
||||
return subnets;
|
||||
});
|
||||
when(ec2.getInstance(eq(REGION), anyString()))
|
||||
.thenAnswer(call -> Optional.ofNullable(instances.get(call.<String>getArgument(1))));
|
||||
when(ec2.isInstanceContainerRunning(anyString())).thenReturn(true);
|
||||
when(ec2.describeInstances(eq(REGION), anyList(), any())).thenAnswer(call -> {
|
||||
List<String> ids = call.getArgument(1);
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(ids.stream().map(instances::get).toList());
|
||||
return List.of(reservation);
|
||||
});
|
||||
when(ec2.runInstances(any(), any(), any(), anyInt(), anyInt(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), anyInt(), any(), any(), any(), any())).thenAnswer(call -> {
|
||||
if (allocations >= failAfter) {
|
||||
if (deleteOnFailure) {
|
||||
groupPresent = false;
|
||||
}
|
||||
throw launchFailure;
|
||||
}
|
||||
String subnet = call.getArgument(7);
|
||||
String zone = null;
|
||||
if (subnet != null) {
|
||||
if (!ipv6Only.contains(subnet) && availableIps.getOrDefault(subnet, 251) == 0) {
|
||||
throw new AwsException("InsufficientFreeAddressesInSubnet",
|
||||
"There are not enough free addresses in subnet '" + subnet
|
||||
+ "' to satisfy the requested number of instances.", 400);
|
||||
}
|
||||
zone = zones.get(subnet);
|
||||
}
|
||||
if (zone == null) {
|
||||
zone = REGION + "a";
|
||||
}
|
||||
List<Instance> launched = new ArrayList<>();
|
||||
int count = call.getArgument(3);
|
||||
for (int index = 0; index < count; index++) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId("i-" + (++allocations));
|
||||
instance.setSubnetId(subnet);
|
||||
instance.setPlacement(new Placement(zone));
|
||||
instance.setState(new InstanceState(0, "pending"));
|
||||
instances.put(instance.getInstanceId(), instance);
|
||||
if (subnet != null) {
|
||||
availableIps.compute(subnet, (key, free) -> (free == null ? 251 : free) - 1);
|
||||
}
|
||||
launched.add(instance);
|
||||
}
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(launched);
|
||||
return reservation;
|
||||
});
|
||||
}
|
||||
|
||||
void grow(int desired) {
|
||||
group.setDesiredCapacity(desired);
|
||||
reconciler.reconcile(group);
|
||||
}
|
||||
|
||||
List<ScalingActivity> activities() {
|
||||
return groups.describeScalingActivities(REGION, group.getAutoScalingGroupName());
|
||||
}
|
||||
|
||||
Map<String, Long> counts() {
|
||||
return instances.values().stream().collect(Collectors.groupingBy(
|
||||
instance -> instance.getPlacement().getAvailabilityZone(), Collectors.counting()));
|
||||
}
|
||||
|
||||
void assertReportedZones() {
|
||||
group.getInstances().forEach(instance -> assertEquals(
|
||||
instances.get(instance.getInstanceId()).getPlacement().getAvailabilityZone(),
|
||||
instance.getAvailabilityZone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -153,6 +153,7 @@ class AutoScalingReconcilerTest {
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("app-asg");
|
||||
when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
|
||||
asg.setDesiredCapacity(1);
|
||||
asg.setLaunchTemplateId("lt-123");
|
||||
asg.setLaunchTemplateVersion("1");
|
||||
@@ -318,6 +319,7 @@ class AutoScalingReconcilerTest {
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("app-asg");
|
||||
when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
|
||||
asg.setDesiredCapacity(1);
|
||||
asg.setLaunchTemplateId("lt-123");
|
||||
asg.setLaunchTemplateVersion("$Latest");
|
||||
@@ -356,6 +358,7 @@ class AutoScalingReconcilerTest {
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("app-asg");
|
||||
when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
|
||||
asg.setDesiredCapacity(1);
|
||||
MixedInstancesPolicy policy = new MixedInstancesPolicy();
|
||||
MixedInstancesPolicy.LaunchTemplate launchTemplatePolicy =
|
||||
|
||||
+18
@@ -68,6 +68,24 @@ class AutoScalingServiceTest {
|
||||
java.util.Map.of(), java.util.Map.of(), AsgOptionalFields.none());
|
||||
}
|
||||
|
||||
@Test
|
||||
void zoneOnlyGroupAcceptsRealZonesOutsideTheLocalSubnetCatalog() {
|
||||
service.ec2Service = mock(Ec2Service.class);
|
||||
service.createLaunchConfiguration(REGION, "zone-lc", null, "ami-test", "t3.nano",
|
||||
null, List.of(), null, null, null);
|
||||
service.createAutoScalingGroup(REGION, "zone-only", "zone-lc", null, null, null, null,
|
||||
0, 0, 0, 300, List.of("us-east-1d"), List.of(), List.of(), List.of(),
|
||||
"EC2", 0, List.of(), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
assertEquals(List.of("us-east-1d"), service.describeAutoScalingGroups(
|
||||
REGION, List.of("zone-only")).getFirst().getAvailabilityZones());
|
||||
service.updateAutoScalingGroup(REGION, "zone-only", null, null, null, null, null,
|
||||
null, 10, null, null, List.of("us-east-1d", "us-east-1f"), null,
|
||||
null, null, null, AsgOptionalFields.none());
|
||||
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("zone-only")).getFirst();
|
||||
assertEquals(List.of("us-east-1d", "us-east-1f"), group.getAvailabilityZones());
|
||||
assertEquals(10, group.getMaxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startInstanceRefreshStoresCompletedRefreshAndAppliesDesiredLaunchTemplate() {
|
||||
InstanceRefresh request = new InstanceRefresh();
|
||||
|
||||
@@ -160,6 +160,40 @@ class Ec2ServiceTest {
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void subnetAvailableAddressesTrackAllocationsAndRelease() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.97.0.0/16", false).getVpcId();
|
||||
Subnet small = service.createSubnet(region, vpcId, "10.97.0.0/28", region + "a");
|
||||
Subnet large = service.createSubnet(region, vpcId, "10.97.1.0/24", region + "a");
|
||||
assertEquals(11, small.getAvailableIpAddressCount());
|
||||
assertEquals(251, large.getAvailableIpAddressCount());
|
||||
|
||||
NetworkInterface eni = service.createNetworkInterface(region, small.getSubnetId(), "count-probe",
|
||||
"10.97.0.4", List.of("10.97.0.4", "10.97.0.5"), List.of(), List.of());
|
||||
assertEquals(9, service.describeSubnets(region, List.of(small.getSubnetId()), Map.of())
|
||||
.getFirst().getAvailableIpAddressCount());
|
||||
Reservation reservation = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), small.getSubnetId(), null, List.of(), null, null);
|
||||
assertEquals(8, service.describeSubnets(region, List.of(small.getSubnetId()), Map.of())
|
||||
.getFirst().getAvailableIpAddressCount());
|
||||
|
||||
service.terminateInstances(region, List.of(reservation.getInstances().getFirst().getInstanceId()));
|
||||
service.deleteNetworkInterface(region, eni.getNetworkInterfaceId());
|
||||
assertEquals(11, service.describeSubnets(region, List.of(small.getSubnetId()), Map.of())
|
||||
.getFirst().getAvailableIpAddressCount());
|
||||
assertEquals(251, service.describeSubnets(region, List.of(large.getSubnetId()), Map.of())
|
||||
.getFirst().getAvailableIpAddressCount());
|
||||
// Legacy records can contain invalid addresses; they do not consume usable subnet space.
|
||||
service.createNetworkInterface(region, small.getSubnetId(), "legacy-addresses",
|
||||
"10.98.0.4", List.of("10.97.0.0", "10.97.0.15"), List.of(), List.of());
|
||||
assertEquals(11, service.describeSubnets(region, List.of(small.getSubnetId()), Map.of())
|
||||
.getFirst().getAvailableIpAddressCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndDescribeVpcsDoNotContactDockerEvenOnFirstUse() {
|
||||
EmulatorConfig config = mockConfig(false);
|
||||
|
||||
Reference in new issue
Block a user