feat(autoscaling): support EnterStandby and ExitStandby (#6955)

* feat(autoscaling): support EnterStandby and ExitStandby

Both actions were routed to Auto Scaling but answered
UnsupportedOperation, so a client taking a node out of service could
lower MinSize and then fail to put the instance in standby.

EnterStandby moves InService instances to EnteringStandby, optionally
lowering desired capacity (refused below MinSize), and returns one
InProgress activity per instance. The reconciler then deregisters them
from the group's target groups and Classic load balancers and sets
Standby. ExitStandby moves Standby instances to Pending, raises desired
capacity (refused above MaxSize) and returns one PreInService activity
per instance; the reconciler registers them again and sets InService.
Descriptions, causes, status codes and progress follow the EC2 Auto
Scaling API reference, user guide and botocore examples. Error texts
follow real AWS responses quoted in public issue reports where one was
found; the others (an instance outside the group, ExitStandby above
MaxSize) are modelled on AWS's texts for similar errors.

Standby members do not count toward desired capacity, including when
AttachInstances raises it, are never scaled in or refreshed, and stay
in the group when their EC2 instance stops. Each member records the
activity of its move in a new optional standbyActivityId field, so a
move interrupted by a restart finishes after it; groups stored without
the field load unchanged. A move whose instance is terminated,
detached, deleted with its group or not running when it leaves standby
is cancelled.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(autoscaling): check EnterStandby and ExitStandby through the Java SDK

The AWS SDK for Java parses both responses into InProgress and
PreInService activities with AWS's descriptions, causes and progress,
the instance reaches Standby and then InService again, desired capacity
follows it, and ExitStandby on an instance in service is a
ValidationError.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(autoscaling): health-check standby returns and lock capacity changes

Review fixes for EnterStandby and ExitStandby:

- An instance whose EC2 instance stopped or terminated while in standby
  now fails the health check AWS runs when it exits standby: Floci
  terminates it if EC2 still has it, records AWS's "Terminating EC2
  instance" activity with the EC2 health check cause, and the group
  launches a replacement. Before, it was dropped from the group as a
  stale reference, and a stopped instance was left behind in EC2, still
  tagged with the group name.
- An instance returning from standby keeps its health status instead
  of being reset to Healthy, so a SetInstanceHealth mark made while it
  waited survives its return.
- SetDesiredCapacity and UpdateAutoScalingGroup now change the group
  under its lock, so they no longer race the capacity changes
  EnterStandby, ExitStandby and the reconciler make under it.
- DetachInstances refuses an instance still in EnteringStandby with
  AWS's "is not in InService or Standby" error. Other states Floci
  still detaches, as before.
- The docs say that instance refresh leaves standby members alone
  whatever its StandbyInstances preference says.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(autoscaling): refuse detaching an instance mid standby move

DetachInstances now refuses any instance whose standby move is still in
progress, with AWS's "The instance <id> is not in InService or
Standby." error: one in EnteringStandby, one on its way back from
standby (Pending), and one marked for termination before the
reconciler ended its move. The detach path therefore no longer cancels
a move. Pending launches and Terminating members without a move are
still detached, as before.

Tests now also cover a refused termination of an instance that failed
its health check on return (retried on the next pass, nothing launched
meanwhile), that return across a restart in every storage mode, and an
instance refresh cancelling the move of an instance on its way back.
The docs list that refresh among the reasons a move is cancelled.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(autoscaling): treat an instance EC2 has no record of as missing

The reconciler's stale check asked DescribeInstances for the one
instance and kept the member on any error. EC2 answers an id it has no
record of with InvalidInstanceID.NotFound rather than an empty list, so
a member whose EC2 record was gone was kept forever:

- an instance leaving standby stayed Pending with its PreInService
  activity and kept counting toward desired capacity, so no
  replacement was launched;
- a Pending launch was never pruned either;
- a Terminating member was never pruned and was reported as a failed
  termination.

That error now reads as a missing instance, both when deciding whether
a member is stale and whether it still needs terminating. Other errors
keep the member, as before. The standby tests' EC2 mock now answers a
missing id the way Ec2Service does.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(autoscaling): keep a missing instance out of a termination batch

EC2 terminates the ids of a TerminateInstances batch in order and
stops at the first one it has no record of. The reconciler sent every
Terminating member in one batch, so a member whose EC2 record was gone
kept the members after it from being terminated that pass and had a
failed termination recorded for them.

A member EC2 has no record of now stays out of the batch, since it is
pruned as a stale reference in the same pass. The standby tests' EC2
mock terminates in order as Ec2Service does, and a reconciler test
covers a batch with one missing and one live member.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(autoscaling): say which EC2 errors still count as an instance record

hasNoEc2Record treats only InvalidInstanceID.NotFound (or an empty
answer) as a missing record; any other EC2 error keeps the instance in
the termination batch. The Javadoc now says so.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(autoscaling): use StorageFactories in the standby storage test

storedService built its StorageFactory from hand-stubbed EmulatorConfig
and ServiceConfigAccess mocks, which is what StorageFactories.open in
io.github.hectorvent.floci.testing already provides. Its flush and
compaction intervals are an hour instead of a minute; neither timer
fires during the test either way.

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:
Jackson Price authored and GitHub committed 2026-10-29 22:28:16 -04:00
1 parent 4d3f3b664d
commit ead5d4a3fe
11 files changed
+1776 -88

No files matched your search

@@ -68,6 +68,8 @@ public class AutoScalingQueryHandler {
case "AttachInstances" -> handleAttachInstances(p, region);
case "DetachInstances" -> handleDetachInstances(p, region);
case "TerminateInstanceInAutoScalingGroup" -> handleTerminateInstance(p, region);
case "EnterStandby" -> handleEnterStandby(p, region);
case "ExitStandby" -> handleExitStandby(p, region);
// Load balancer attachment
case "AttachLoadBalancerTargetGroups" -> handleAttachLoadBalancerTargetGroups(p, region);
case "DetachLoadBalancerTargetGroups" -> handleDetachLoadBalancerTargetGroups(p, region);
@@ -923,6 +925,49 @@ public class AutoScalingQueryHandler {
.end("TerminateInstanceInAutoScalingGroupResponse").build());
}
private Response handleEnterStandby(MultivaluedMap<String, String> p, String region) {
String groupName = p.getFirst("AutoScalingGroupName");
String decrement = p.getFirst("ShouldDecrementDesiredCapacity");
List<String> missing = new ArrayList<>();
if (groupName == null) {
missing.add(SmithyValidationErrors.notNull("autoScalingGroupName"));
}
if (decrement == null || decrement.isBlank()) {
missing.add(SmithyValidationErrors.notNull("shouldDecrementDesiredCapacity"));
}
if (!missing.isEmpty()) {
throw SmithyValidationErrors.validationError(missing);
}
boolean shouldDecrement = requiredBoolParam(p, "ShouldDecrementDesiredCapacity",
"shouldDecrementDesiredCapacity");
return ok(activitiesResponse("EnterStandby",
service.enterStandby(region, groupName, memberList(p, "InstanceIds"), shouldDecrement)));
}
private Response handleExitStandby(MultivaluedMap<String, String> p, String region) {
String groupName = p.getFirst("AutoScalingGroupName");
if (groupName == null) {
throw SmithyValidationErrors.validationError(SmithyValidationErrors.notNull("autoScalingGroupName"));
}
return ok(activitiesResponse("ExitStandby",
service.exitStandby(region, groupName, memberList(p, "InstanceIds"))));
}
private static String activitiesResponse(String action, List<ScalingActivity> activities) {
XmlBuilder xml = new XmlBuilder()
.start(action + "Response", NS)
.start(action + "Result")
.start("Activities");
for (ScalingActivity activity : activities) {
appendActivityXml(xml, activity);
}
xml.end("Activities")
.end(action + "Result")
.raw(AwsQueryResponse.responseMetadata())
.end(action + "Response");
return xml.build();
}
// ── Load balancer attachment ───────────────────────────────────────────────
private Response handleAttachLoadBalancerTargetGroups(MultivaluedMap<String, String> p, String region) {
@@ -1372,17 +1417,7 @@ public class AutoScalingQueryHandler {
.start("DescribeScalingActivitiesResult")
.start("Activities");
for (ScalingActivity a : activities) {
xml.start("member")
.elem("ActivityId", a.getActivityId())
.elem("AutoScalingGroupName", a.getAutoScalingGroupName())
.elem("StatusCode", a.getStatusCode())
.elem("Progress", String.valueOf(a.getProgress()))
.elem("StartTime", ISO_FMT.format(a.getStartTime()));
if (a.getDescription() != null) { xml.elem("Description", a.getDescription()); }
if (a.getCause() != null) { xml.elem("Cause", a.getCause()); }
if (a.getEndTime() != null) { xml.elem("EndTime", ISO_FMT.format(a.getEndTime())); }
if (a.getStatusMessage() != null) { xml.elem("StatusMessage", a.getStatusMessage()); }
xml.end("member");
appendActivityXml(xml, a);
}
xml.end("Activities")
.end("DescribeScalingActivitiesResult")
@@ -1391,6 +1426,20 @@ public class AutoScalingQueryHandler {
return ok(xml.build());
}
private static void appendActivityXml(XmlBuilder xml, ScalingActivity a) {
xml.start("member")
.elem("ActivityId", a.getActivityId())
.elem("AutoScalingGroupName", a.getAutoScalingGroupName())
.elem("StatusCode", a.getStatusCode())
.elem("Progress", String.valueOf(a.getProgress()))
.elem("StartTime", ISO_FMT.format(a.getStartTime()));
if (a.getDescription() != null) { xml.elem("Description", a.getDescription()); }
if (a.getCause() != null) { xml.elem("Cause", a.getCause()); }
if (a.getEndTime() != null) { xml.elem("EndTime", ISO_FMT.format(a.getEndTime())); }
if (a.getStatusMessage() != null) { xml.elem("StatusMessage", a.getStatusMessage()); }
xml.end("member");
}
// ── Metadata responses ────────────────────────────────────────────────────
private Response handleDescribeNotificationTypes() {
@@ -2081,14 +2130,19 @@ public class AutoScalingQueryHandler {
/** A required boolean member must be present and exactly "true"/"false" — never silently coerced to false. */
private boolean requiredBoolParam(MultivaluedMap<String, String> p, String key) {
return requiredBoolParam(p, key, key);
}
/** As {@link #requiredBoolParam(MultivaluedMap, String)}, naming the member {@code path} in the error. */
private boolean requiredBoolParam(MultivaluedMap<String, String> p, String key, String path) {
String val = p.getFirst(key);
if (val == null || val.isBlank()) {
throw SmithyValidationErrors.validationError(
SmithyValidationErrors.notNull(key));
SmithyValidationErrors.notNull(path));
}
if (!"true".equalsIgnoreCase(val) && !"false".equalsIgnoreCase(val)) {
throw SmithyValidationErrors.validationError(
"Value '" + val + "' at '" + key
"Value '" + val + "' at '" + path
+ "' failed to satisfy constraint: Member must be a valid boolean");
}
return parseOptionalBoolean(val, key);
@@ -33,6 +33,8 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
@@ -65,6 +67,9 @@ public class AutoScalingReconciler {
*/
private static final Set<String> TERMINATED_STATES = Set.of("shutting-down", "terminated");
/** The error EC2 answers, rather than an empty list, for an instance id it has no record of. */
private static final String INSTANCE_NOT_FOUND = "InvalidInstanceID.NotFound";
/** The Activity StatusMessage limit (XmlStringMaxLen255). */
private static final int STATUS_MESSAGE_MAX_LENGTH = 255;
@@ -136,6 +141,7 @@ public class AutoScalingReconciler {
public void reconcile(AutoScalingGroup asg) {
asgService.reconcileIfPresent(asg, () -> {
settleStandbyMoves(asg);
removeTerminatingInstances(asg);
removeStaleInstances(asg);
removeOrphanedTargetRegistrations(asg);
@@ -228,6 +234,42 @@ public class AutoScalingReconciler {
}
}
/**
* Finishes each move into standby: the instance leaves the group's target groups and Classic load
* balancers, then becomes Standby. A move whose instance left its transient state some other way, such
* as being terminated or refreshed, is cancelled. A move out of standby is finished by
* {@link #promoteReadyInstances} once the instance is running.
*/
private void settleStandbyMoves(AutoScalingGroup asg) {
List<AsgInstance> entering = new ArrayList<>();
List<AsgInstance> interrupted = new ArrayList<>();
for (AsgInstance instance : asg.getInstances()) {
if ("EnteringStandby".equals(instance.getLifecycleState())) {
entering.add(instance);
} else if (instance.getStandbyActivityId() != null && !"Pending".equals(instance.getLifecycleState())) {
interrupted.add(instance);
}
}
if (entering.isEmpty() && interrupted.isEmpty()) {
return;
}
if (!entering.isEmpty()) {
List<String> instanceIds = entering.stream().map(AsgInstance::getInstanceId).toList();
deregisterFromTargetGroups(asg, instanceIds);
deregisterFromClassicLoadBalancers(asg, instanceIds);
for (AsgInstance instance : entering) {
instance.setLifecycleState("Standby");
if (instance.getStandbyActivityId() != null) {
asgService.completeActivity(instance.getStandbyActivityId(), "Successful", null);
instance.setStandbyActivityId(null);
}
}
LOG.infov("ASG {0}: instance(s) {1} are now in Standby", asg.getAutoScalingGroupName(), instanceIds);
}
asgService.cancelStandbyMoves(interrupted);
asgService.saveAutoScalingGroupIfPresent(asg);
}
static long activeCapacity(AutoScalingGroup asg) {
return asg.getInstances().stream()
.filter(i -> {
@@ -253,14 +295,22 @@ public class AutoScalingReconciler {
String ec2State = ec2Instances.get(0).getState().getName();
if ("running".equals(ec2State)) {
asgInst.setLifecycleState("InService");
asgInst.setHealthStatus("Healthy");
registerWithTargetGroups(asg, asgInst);
registerWithClassicLoadBalancers(asg, asgInst);
changed = true;
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
"Launching a new EC2 instance: " + asgInst.getInstanceId(),
SCALE_OUT_CAUSE,
"Successful");
String standbyActivityId = asgInst.getStandbyActivityId();
if (standbyActivityId != null) {
// An instance back from standby keeps the health it had there and completes its
// ExitStandby activity; nothing was launched.
asgInst.setStandbyActivityId(null);
asgService.completeActivity(standbyActivityId, "Successful", null);
} else {
asgInst.setHealthStatus("Healthy");
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
"Launching a new EC2 instance: " + asgInst.getInstanceId(),
SCALE_OUT_CAUSE,
"Successful");
}
LOG.infov("ASG {0}: instance {1} is now InService",
asg.getAutoScalingGroupName(), asgInst.getInstanceId());
}
@@ -278,6 +328,13 @@ public class AutoScalingReconciler {
List<AsgInstance> staleInstances = asg.getInstances().stream()
.filter(instance -> isStaleInstance(asg, instance))
.collect(Collectors.toList());
List<AsgInstance> backFromStandby = staleInstances.stream()
.filter(instance -> instance.getStandbyActivityId() != null)
.toList();
if (!backFromStandby.isEmpty()) {
replaceUnhealthyReturns(asg, backFromStandby);
staleInstances.removeAll(backFromStandby);
}
if (staleInstances.isEmpty()) {
return;
}
@@ -298,6 +355,44 @@ public class AutoScalingReconciler {
asg.getAutoScalingGroupName(), instanceIds);
}
/**
* Instances back from standby whose EC2 instance stopped or went away fail the health check AWS runs on their
* return: each is terminated, if EC2 still has it, and leaves the group with AWS's termination activity, and the
* group launches a replacement for the capacity ExitStandby restored. A termination EC2 refuses is retried on
* the next pass.
*/
private void replaceUnhealthyReturns(AutoScalingGroup asg, List<AsgInstance> returning) {
List<String> instanceIds = returning.stream().map(AsgInstance::getInstanceId).toList();
List<String> stillThere = instanceIds.stream()
.filter(id -> !isMissingOrTerminalEc2Instance(asg, id, TERMINATED_STATES))
.toList();
if (!stillThere.isEmpty()) {
try {
ec2Service.terminateInstances(asg.getRegion(), stillThere);
} catch (Exception e) {
LOG.warnv("ASG {0}: could not terminate instance(s) {1} back from standby: {2}",
asg.getAutoScalingGroupName(), stillThere, e.getMessage());
return;
}
}
failActiveSsmInvocations(asg, instanceIds);
deregisterFromTargetGroups(asg, instanceIds);
deregisterFromClassicLoadBalancers(asg, instanceIds);
asgService.cancelStandbyMoves(returning);
asg.getInstances().removeIf(instance -> instanceIds.contains(instance.getInstanceId()));
asgService.saveAutoScalingGroupIfPresent(asg);
String now = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString();
for (String instanceId : instanceIds) {
asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(),
"Terminating EC2 instance: " + instanceId,
"At " + now + " an instance was taken out of service in response to an EC2 health check"
+ " indicating it has been terminated or stopped.",
"Successful");
}
LOG.infov("ASG {0}: instance(s) {1} back from standby were not running and were replaced",
asg.getAutoScalingGroupName(), instanceIds);
}
private void failActiveSsmInvocations(AutoScalingGroup asg, List<String> instanceIds) {
if (ssmCommandService == null) {
return;
@@ -326,6 +421,14 @@ public class AutoScalingReconciler {
return false;
}
/**
* Whether EC2 has no record of the instance at all, whatever state a record would be in. Any EC2 error other than
* {@code InvalidInstanceID.NotFound} counts as a record, so the instance is not given up on.
*/
private boolean hasNoEc2Record(AutoScalingGroup asg, String instanceId) {
return isMissingOrTerminalEc2Instance(asg, instanceId, Set.of());
}
private boolean isMissingOrTerminalEc2Instance(AutoScalingGroup asg, String instanceId,
Set<String> terminalStates) {
try {
@@ -343,6 +446,9 @@ public class AutoScalingReconciler {
return state != null && terminalStates.contains(state);
}
catch (Exception e) {
if (e instanceof AwsException aws && INSTANCE_NOT_FOUND.equals(aws.getErrorCode())) {
return true;
}
LOG.debugv("ASG {0}: keeping instance {1} during stale check: {2}",
asg.getAutoScalingGroupName(), instanceId, e.getMessage());
return false;
@@ -391,16 +497,21 @@ public class AutoScalingReconciler {
return;
}
// A terminating instance whose EC2 record is already gone is not a failure: it is pruned as stale by
// removeStaleInstances in this same pass. It stays out of the batch, which EC2 would stop at its id.
List<String> instanceIds = terminatingInstances.stream()
.map(AsgInstance::getInstanceId)
.filter(id -> !hasNoEc2Record(asg, id))
.collect(Collectors.toList());
if (instanceIds.isEmpty()) {
return;
}
try {
ec2Service.terminateInstances(asg.getRegion(), instanceIds);
} catch (Exception e) {
LOG.warnv("ASG {0}: failed to terminate refreshing instances {1}: {2}",
asg.getAutoScalingGroupName(), instanceIds, e.getMessage());
// A terminating instance whose EC2 record is already gone is not a failure: it is pruned
// as stale by removeStaleInstances in this same pass. Only real failures are recorded.
// Only real failures are recorded, not an instance that is going away or has gone in the meantime.
List<String> stillPresent = instanceIds.stream()
.filter(id -> !isMissingOrTerminalEc2Instance(asg, id, TERMINATED_STATES))
.toList();
@@ -432,60 +432,65 @@ public class AutoScalingService implements PassedRoleLookup {
String healthCheckType, Integer healthCheckGracePeriod,
List<String> terminationPolicies,
AsgOptionalFields optionalFields) {
AutoScalingGroup asg = requireGroup(region, name);
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchTemplateVersion != null && launchTemplateId == null && launchTemplateName == null) {
throw new AwsException("ValidationError",
"LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", 400);
// Under the group's lock, which EnterStandby, ExitStandby and the reconciler hold while they read and
// change the group's capacity.
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchTemplateVersion != null && launchTemplateId == null && launchTemplateName == null) {
throw new AwsException("ValidationError",
"LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", 400);
}
validateOptionalFields(optionalFields);
rejectDesiredConfigurationUpdateDuringActiveRefresh(region, name,
launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName,
launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
validateEffectiveLaunchImage(region,
effectiveIdentity.launchConfigurationName(),
effectiveIdentity.launchTemplateId(),
effectiveIdentity.launchTemplateName(),
effectiveIdentity.launchTemplateVersion(),
effectiveIdentity.mixedInstancesPolicy());
validateDesiredCapacityType(
effectiveDesiredCapacityType(asg, optionalFields),
effectiveIdentity.mixedInstancesPolicy());
if (launchConfigName != null) {
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(null);
}
if (launchTemplateId != null || launchTemplateName != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(null);
}
if (mixedInstancesPolicy != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
}
if (minSize != null) { asg.setMinSize(minSize); }
if (maxSize != null) { asg.setMaxSize(maxSize); }
if (desiredCapacity != null) { asg.setDesiredCapacity(desiredCapacity); }
if (defaultCooldown != null) { asg.setDefaultCooldown(defaultCooldown); }
if (availabilityZones != null) { asg.setAvailabilityZones(new ArrayList<>(availabilityZones)); }
if (subnetIds != null) { asg.setSubnetIds(new ArrayList<>(subnetIds)); }
if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); }
if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); }
if (terminationPolicies != null) { asg.setTerminationPolicies(new ArrayList<>(terminationPolicies)); }
if (optionalFields != null) {
optionalFields.applyToExistingGroup(asg);
}
groups.put(key, asg);
}
validateOptionalFields(optionalFields);
rejectDesiredConfigurationUpdateDuringActiveRefresh(region, name,
launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName,
launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
validateEffectiveLaunchImage(region,
effectiveIdentity.launchConfigurationName(),
effectiveIdentity.launchTemplateId(),
effectiveIdentity.launchTemplateName(),
effectiveIdentity.launchTemplateVersion(),
effectiveIdentity.mixedInstancesPolicy());
validateDesiredCapacityType(
effectiveDesiredCapacityType(asg, optionalFields),
effectiveIdentity.mixedInstancesPolicy());
if (launchConfigName != null) {
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(null);
}
if (launchTemplateId != null || launchTemplateName != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(null);
}
if (mixedInstancesPolicy != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
}
if (minSize != null) { asg.setMinSize(minSize); }
if (maxSize != null) { asg.setMaxSize(maxSize); }
if (desiredCapacity != null) { asg.setDesiredCapacity(desiredCapacity); }
if (defaultCooldown != null) { asg.setDefaultCooldown(defaultCooldown); }
if (availabilityZones != null) { asg.setAvailabilityZones(new ArrayList<>(availabilityZones)); }
if (subnetIds != null) { asg.setSubnetIds(new ArrayList<>(subnetIds)); }
if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); }
if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); }
if (terminationPolicies != null) { asg.setTerminationPolicies(new ArrayList<>(terminationPolicies)); }
if (optionalFields != null) {
optionalFields.applyToExistingGroup(asg);
}
groups.put(asgKey(region, name), asg);
}
/**
@@ -565,6 +570,7 @@ public class AutoScalingService implements PassedRoleLookup {
}
});
}
cancelStandbyMoves(asg.getInstances());
groups.remove(key);
instanceRefreshes.entrySet().removeIf(e -> region.equals(e.getValue().getRegion())
&& name.equals(e.getValue().getAutoScalingGroupName()));
@@ -626,14 +632,17 @@ public class AutoScalingService implements PassedRoleLookup {
}
public void setDesiredCapacity(String region, String name, int desiredCapacity) {
AutoScalingGroup asg = requireGroup(region, name);
if (desiredCapacity < asg.getMinSize() || desiredCapacity > asg.getMaxSize()) {
throw new AwsException("ValidationError",
"New DesiredCapacity=" + desiredCapacity + " must be between MinSize="
+ asg.getMinSize() + " and MaxSize=" + asg.getMaxSize() + ".", 400);
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
if (desiredCapacity < asg.getMinSize() || desiredCapacity > asg.getMaxSize()) {
throw new AwsException("ValidationError",
"New DesiredCapacity=" + desiredCapacity + " must be between MinSize="
+ asg.getMinSize() + " and MaxSize=" + asg.getMaxSize() + ".", 400);
}
asg.setDesiredCapacity(desiredCapacity);
groups.put(key, asg);
}
asg.setDesiredCapacity(desiredCapacity);
groups.put(asgKey(region, name), asg);
}
public void createOrUpdateTags(
@@ -919,8 +928,12 @@ public class AutoScalingService implements PassedRoleLookup {
inst.setLaunchTemplateVersion(asg.getLaunchTemplateVersion());
asg.getInstances().add(inst);
}
if (asg.getInstances().size() > asg.getDesiredCapacity()) {
asg.setDesiredCapacity(asg.getInstances().size());
// Members in standby do not count toward desired capacity.
int counted = (int) asg.getInstances().stream()
.filter(member -> !isStandbyState(member.getLifecycleState()))
.count();
if (counted > asg.getDesiredCapacity()) {
asg.setDesiredCapacity(counted);
}
groups.put(asgKey(region, name), asg);
}
@@ -932,6 +945,17 @@ public class AutoScalingService implements PassedRoleLookup {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
for (AsgInstance member : asg.getInstances()) {
// AWS detaches only InService and Standby instances. Floci does not refuse the other states yet,
// except for an instance whose standby move is still in progress, whatever its state: it keeps the
// move's activity until the reconciler completes or cancels the move.
boolean moving = "EnteringStandby".equals(member.getLifecycleState())
|| member.getStandbyActivityId() != null;
if (moving && instanceIds.contains(member.getInstanceId())) {
throw new AwsException("ValidationError",
"The instance " + member.getInstanceId() + " is not in InService or Standby.", 400);
}
}
List<String> detached = asg.getInstances().stream().map(AsgInstance::getInstanceId)
.filter(instanceIds::contains).toList();
if (!detached.isEmpty()) {
@@ -963,6 +987,139 @@ public class AutoScalingService implements PassedRoleLookup {
});
}
/**
* EnterStandby. Each instance, which must be InService, moves to EnteringStandby with an InProgress
* activity, and the reconciler finishes the move to Standby once it has taken the instance out of the
* group's load balancers. Decrementing desired capacity keeps the group from launching replacements and
* is refused when it would go below MinSize. The activities returned are copies taken as the moves
* start, so the response shows them InProgress even if the reconciler completes them at once.
*/
public List<ScalingActivity> enterStandby(String region, String name, List<String> instanceIds,
boolean shouldDecrementDesiredCapacity) {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
List<AsgInstance> moving = membersInState(asg, instanceIds, "InService");
int desired = asg.getDesiredCapacity();
int newDesired = shouldDecrementDesiredCapacity ? desired - moving.size() : desired;
if (newDesired != desired) {
requireDesiredCapacityWithinBounds(asg, newDesired,
"To place into standby " + moving.size() + " instances");
}
Instant now = Instant.now();
List<ScalingActivity> started = new ArrayList<>();
for (AsgInstance instance : moving) {
String cause = "At " + now.truncatedTo(ChronoUnit.SECONDS) + " instance " + instance.getInstanceId()
+ " was moved to standby in response to a user request"
+ (newDesired != desired ? ", shrinking the capacity from " + desired + " to " + newDesired : "")
+ ".";
started.add(newActivity(region, name, "Moving EC2 instance to Standby: " + instance.getInstanceId(),
cause, "InProgress", 50, now));
instance.setLifecycleState("EnteringStandby");
}
return startStandbyMoves(key, asg, moving, started, newDesired);
}
}
/**
* ExitStandby. Each instance, which must be in Standby, moves to Pending with a PreInService activity
* and desired capacity grows by one for it, refused above MaxSize. The reconciler puts the instance
* back in service, registering it with the group's load balancers, once its EC2 instance is running.
*/
public List<ScalingActivity> exitStandby(String region, String name, List<String> instanceIds) {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
List<AsgInstance> moving = membersInState(asg, instanceIds, "Standby");
int desired = asg.getDesiredCapacity();
int newDesired = desired + moving.size();
if (newDesired != desired) {
requireDesiredCapacityWithinBounds(asg, newDesired,
"To exit standby " + moving.size() + " instances");
}
Instant now = Instant.now();
List<ScalingActivity> started = new ArrayList<>();
for (AsgInstance instance : moving) {
String cause = "At " + now.truncatedTo(ChronoUnit.SECONDS) + " instance " + instance.getInstanceId()
+ " was moved out of standby in response to a user request, increasing the capacity from "
+ desired + " to " + newDesired + ".";
started.add(newActivity(region, name, "Moving EC2 instance out of Standby: " + instance.getInstanceId(),
cause, "PreInService", 30, now));
instance.setLifecycleState("Pending");
}
return startStandbyMoves(key, asg, moving, started, newDesired);
}
}
/** Links each moving member to its activity, saves the group, then stores the activities. */
private List<ScalingActivity> startStandbyMoves(String key, AutoScalingGroup asg, List<AsgInstance> moving,
List<ScalingActivity> started, int newDesired) {
for (int index = 0; index < moving.size(); index++) {
moving.get(index).setStandbyActivityId(started.get(index).getActivityId());
}
asg.setDesiredCapacity(newDesired);
groups.put(key, asg);
List<ScalingActivity> response = new ArrayList<>();
for (ScalingActivity activity : started) {
activities.put(activity.getActivityId(), activity);
response.add(copyOf(activity));
}
return response;
}
/**
* The members an EnterStandby or ExitStandby request names, each once, refused unless every one belongs
* to the group and is in {@code requiredState}.
*/
private static List<AsgInstance> membersInState(AutoScalingGroup asg, List<String> instanceIds,
String requiredState) {
List<String> requested = instanceIds == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(instanceIds));
Map<String, AsgInstance> members = new LinkedHashMap<>();
for (AsgInstance member : asg.getInstances()) {
members.put(member.getInstanceId(), member);
}
List<String> strangers = requested.stream().filter(id -> !members.containsKey(id)).toList();
if (strangers.size() == 1) {
throw new AwsException("ValidationError", "The instance " + strangers.getFirst()
+ " is not part of Auto Scaling group " + asg.getAutoScalingGroupName() + ".", 400);
}
if (!strangers.isEmpty()) {
throw new AwsException("ValidationError", "The instances " + String.join(", ", strangers)
+ " are not part of Auto Scaling group " + asg.getAutoScalingGroupName() + ".", 400);
}
List<AsgInstance> named = requested.stream().map(members::get).toList();
for (AsgInstance member : named) {
if (!requiredState.equals(member.getLifecycleState())) {
throw new AwsException("ValidationError",
"The instance " + member.getInstanceId() + " is not in " + requiredState + ".", 400);
}
}
return named;
}
static boolean isStandbyState(String lifecycleState) {
return "EnteringStandby".equals(lifecycleState) || "Standby".equals(lifecycleState);
}
private static void requireDesiredCapacityWithinBounds(AutoScalingGroup asg, int newDesired, String change) {
if (newDesired < asg.getMinSize() || newDesired > asg.getMaxSize()) {
throw new AwsException("ValidationError", "AutoScalingGroup " + asg.getAutoScalingGroupName()
+ " has min-size=" + asg.getMinSize() + ", max-size=" + asg.getMaxSize()
+ ", and desired-size=" + asg.getDesiredCapacity() + ". " + change
+ ", please update the AutoScalingGroup sizes appropriately.", 400);
}
}
/** Cancels the standby activity of each member that leaves the group, or its move, while the move is in progress. */
void cancelStandbyMoves(List<AsgInstance> leaving) {
for (AsgInstance member : leaving) {
if (member.getStandbyActivityId() != null) {
completeActivity(member.getStandbyActivityId(), "Cancelled", null);
member.setStandbyActivityId(null);
}
}
}
private void releaseRefreshOwnership(AutoScalingGroup asg, List<String> instanceIds) {
InstanceRefresh refresh = activeInstanceRefresh(asg);
if (refresh != null && refresh.getReplacements() != null) {
@@ -1446,19 +1603,41 @@ public class AutoScalingService implements PassedRoleLookup {
public ScalingActivity recordActivity(String region, String asgName, String description,
String cause, String statusCode) {
ScalingActivity activity = newActivity(region, asgName, description, cause, statusCode,
"Successful".equals(statusCode) ? 100 : 0, Instant.now());
activities.put(activity.getActivityId(), activity);
return activity;
}
private static ScalingActivity newActivity(String region, String asgName, String description, String cause,
String statusCode, int progress, Instant startTime) {
ScalingActivity activity = new ScalingActivity();
activity.setActivityId(UUID.randomUUID().toString());
activity.setAutoScalingGroupName(asgName);
activity.setRegion(region);
activity.setDescription(description);
activity.setCause(cause);
activity.setStartTime(Instant.now());
activity.setStartTime(startTime);
activity.setStatusCode(statusCode);
activity.setProgress("Successful".equals(statusCode) ? 100 : 0);
activities.put(activity.getActivityId(), activity);
activity.setProgress(progress);
return activity;
}
private static ScalingActivity copyOf(ScalingActivity activity) {
ScalingActivity copy = new ScalingActivity();
copy.setActivityId(activity.getActivityId());
copy.setAutoScalingGroupName(activity.getAutoScalingGroupName());
copy.setRegion(activity.getRegion());
copy.setDescription(activity.getDescription());
copy.setCause(activity.getCause());
copy.setStartTime(activity.getStartTime());
copy.setEndTime(activity.getEndTime());
copy.setStatusCode(activity.getStatusCode());
copy.setStatusMessage(activity.getStatusMessage());
copy.setProgress(activity.getProgress());
return copy;
}
public void completeActivity(String activityId, String statusCode, String statusMessage) {
ScalingActivity activity = activities.get(activityId);
if (activity != null) {
@@ -9,7 +9,8 @@ public class AsgInstance {
private String instanceId;
private String availabilityZone;
private String lifecycleState; // Pending | InService | Terminating | Terminated | Detached
// Pending | InService | EnteringStandby | Standby | Terminating | Terminated | Detached
private String lifecycleState;
private String healthStatus; // Healthy | Unhealthy
private String launchConfigurationName;
private String launchTemplateId;
@@ -17,6 +18,9 @@ public class AsgInstance {
private String launchTemplateVersion;
private String instanceType;
private boolean protectedFromScaleIn;
// The EnterStandby or ExitStandby activity the reconciler completes when this instance finishes moving
// into or out of standby; null otherwise, and for members stored before standby was supported.
private String standbyActivityId;
public AsgInstance() {}
@@ -49,4 +53,7 @@ public class AsgInstance {
public boolean isProtectedFromScaleIn() { return protectedFromScaleIn; }
public void setProtectedFromScaleIn(boolean v) { this.protectedFromScaleIn = v; }
public String getStandbyActivityId() { return standbyActivityId; }
public void setStandbyActivityId(String v) { this.standbyActivityId = v; }
}