mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(autoscaling): preserve paused refresh ownership (#5668)
* fix(autoscaling): retain paused refresh replacements across reloads * fix(autoscaling): preserve paused and detached refresh instances * fix(autoscaling): retain recovered refresh launch identity * test(autoscaling): cover refresh recovery across groups * test(autoscaling): cover paused refresh SDK responses * fix(autoscaling): publish refresh ownership before reconciliation * fix(autoscaling): release refresh ownership during group changes * test(autoscaling): retain launch settings during refreshes * fix(autoscaling): report accepted refresh placement * fix(autoscaling): retain refresh settings and report launch failures
This commit is contained in:
1 parent
ff32bae98c
commit
b395560fe2
13 files changed
+1794
-114
No files matched your search
+196
-45
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefreshLaunch;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefreshReplacement;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity;
|
||||
@@ -130,17 +133,18 @@ public class AutoScalingReconciler {
|
||||
}
|
||||
|
||||
public void reconcile(AutoScalingGroup asg) {
|
||||
removeTerminatingInstances(asg);
|
||||
removeStaleInstances(asg);
|
||||
removeOrphanedTargetRegistrations(asg);
|
||||
promoteReadyInstances(asg);
|
||||
asgService.reconcileIfPresent(asg, () -> {
|
||||
removeTerminatingInstances(asg);
|
||||
removeStaleInstances(asg);
|
||||
removeOrphanedTargetRegistrations(asg);
|
||||
promoteReadyInstances(asg);
|
||||
reconcileRefreshReplacements(asg);
|
||||
|
||||
asgService.adjustCapacityIfPresent(asg, () -> {
|
||||
long activeCapacity = activeCapacity(asg);
|
||||
long reservedCapacity = reservedRefreshCapacity(asg);
|
||||
int desired = asg.getDesiredCapacity();
|
||||
|
||||
if (activeCapacity < desired && !asg.getSuspendedProcesses().contains("Launch")) {
|
||||
if (!scaleOut(asg, (int) (desired - activeCapacity))) {
|
||||
if (activeCapacity + reservedCapacity < desired && !asg.getSuspendedProcesses().contains("Launch")) {
|
||||
if (!scaleOut(asg, (int) (desired - activeCapacity - reservedCapacity))) {
|
||||
return;
|
||||
}
|
||||
} else if (activeCapacity > desired && !asg.getSuspendedProcesses().contains("Terminate")) {
|
||||
@@ -152,6 +156,76 @@ public class AutoScalingReconciler {
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean refreshPaused(AutoScalingGroup asg) {
|
||||
return asg.getSuspendedProcesses().contains("InstanceRefresh")
|
||||
|| asg.getSuspendedProcesses().contains("Launch")
|
||||
|| asg.getSuspendedProcesses().contains("Terminate");
|
||||
}
|
||||
|
||||
private boolean pausedRefreshOwns(AutoScalingGroup asg, String instanceId) {
|
||||
InstanceRefresh refresh = asgService.activeInstanceRefresh(asg);
|
||||
return refreshPaused(asg) && refresh != null && refresh.getReplacements() != null
|
||||
&& refresh.getReplacements().stream()
|
||||
.anyMatch(replacement -> instanceId.equals(replacement.getOriginalInstanceId()));
|
||||
}
|
||||
|
||||
private long reservedRefreshCapacity(AutoScalingGroup asg) {
|
||||
InstanceRefresh refresh = asgService.activeInstanceRefresh(asg);
|
||||
if (refresh == null || refresh.getReplacements() == null) {
|
||||
return 0;
|
||||
}
|
||||
return refresh.getReplacements().stream()
|
||||
.filter(replacement -> !replacement.isComplete())
|
||||
.filter(replacement -> asg.getInstances().stream().noneMatch(instance ->
|
||||
instance.getInstanceId().equals(replacement.getReplacementInstanceId())
|
||||
&& isActiveLifecycleState(instance.getLifecycleState())))
|
||||
.count();
|
||||
}
|
||||
|
||||
private void reconcileRefreshReplacements(AutoScalingGroup asg) {
|
||||
InstanceRefresh refresh = asgService.activeInstanceRefresh(asg);
|
||||
if (refresh == null || refresh.getReplacements() == null || refreshPaused(asg)) {
|
||||
return;
|
||||
}
|
||||
Map<String, List<Instance>> acceptedLaunches = null;
|
||||
for (InstanceRefreshReplacement replacement : refresh.getReplacements()) {
|
||||
if (replacement.isComplete()) {
|
||||
continue;
|
||||
}
|
||||
AsgInstance launchedInstance = asg.getInstances().stream()
|
||||
.filter(instance -> instance.getInstanceId().equals(replacement.getReplacementInstanceId()))
|
||||
.findFirst().orElse(null);
|
||||
if (launchedInstance != null) {
|
||||
if ("InService".equals(launchedInstance.getLifecycleState())) {
|
||||
replacement.setPhase("Complete");
|
||||
asgService.saveInstanceRefresh(refresh);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (asg.getInstances().stream().anyMatch(instance ->
|
||||
instance.getInstanceId().equals(replacement.getOriginalInstanceId()))) {
|
||||
continue;
|
||||
}
|
||||
if (acceptedLaunches == null) {
|
||||
acceptedLaunches = refreshLaunches(asg);
|
||||
}
|
||||
List<Instance> existing = acceptedLaunches.getOrDefault(replacement.getLaunchClientToken(), List.of());
|
||||
if (activeCapacity(asg) >= asg.getDesiredCapacity() && existing.isEmpty()) {
|
||||
replacement.setPhase("NoLongerRequired");
|
||||
asgService.saveInstanceRefresh(refresh);
|
||||
continue;
|
||||
}
|
||||
replacement.setPhase("AwaitingReplacement");
|
||||
asgService.saveInstanceRefresh(refresh);
|
||||
List<String> launched = launchInstances(asg, refresh, replacement, existing, acceptedLaunches);
|
||||
if (!launched.isEmpty()) {
|
||||
replacement.setReplacementInstanceId(launched.getFirst());
|
||||
replacement.setPhase("Warming");
|
||||
asgService.saveInstanceRefresh(refresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static long activeCapacity(AutoScalingGroup asg) {
|
||||
return asg.getInstances().stream()
|
||||
.filter(i -> {
|
||||
@@ -279,7 +353,8 @@ public class AutoScalingReconciler {
|
||||
}
|
||||
|
||||
Set<String> activeInstanceIds = asg.getInstances().stream()
|
||||
.filter(instance -> isActiveLifecycleState(instance.getLifecycleState()))
|
||||
.filter(instance -> isActiveLifecycleState(instance.getLifecycleState())
|
||||
|| pausedRefreshOwns(asg, instance.getInstanceId()))
|
||||
.map(AsgInstance::getInstanceId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
@@ -308,6 +383,7 @@ public class AutoScalingReconciler {
|
||||
private void removeTerminatingInstances(AutoScalingGroup asg) {
|
||||
List<AsgInstance> terminatingInstances = asg.getInstances().stream()
|
||||
.filter(instance -> "Terminating".equals(instance.getLifecycleState()))
|
||||
.filter(instance -> !pausedRefreshOwns(asg, instance.getInstanceId()))
|
||||
.collect(Collectors.toList());
|
||||
if (terminatingInstances.isEmpty()) {
|
||||
return;
|
||||
@@ -362,45 +438,12 @@ public class AutoScalingReconciler {
|
||||
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()),
|
||||
false, null, null, launchSource.blockDeviceMappings());
|
||||
|
||||
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());
|
||||
}
|
||||
List<Instance> launched = launchInstance(asg, launchSource, placement, null, null,
|
||||
List.of(), launchedInstanceIds, false);
|
||||
if (placement.subnetId() != null) {
|
||||
placements.set(placements.indexOf(placement), new LaunchPlacement(placement.subnetId(),
|
||||
placement.availabilityZone(), Math.max(0,
|
||||
placement.availableIpAddresses() - reservation.getInstances().size()),
|
||||
placement.availableIpAddresses() - launched.size()),
|
||||
placement.requiresIpv4Address()));
|
||||
}
|
||||
}
|
||||
@@ -455,6 +498,114 @@ public class AutoScalingReconciler {
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, List<Instance>> refreshLaunches(AutoScalingGroup asg) {
|
||||
return ec2Service.describeInstances(asg.getRegion(), List.of(), null).stream()
|
||||
.flatMap(result -> result.getInstances().stream())
|
||||
.filter(instance -> instance.getClientToken() != null)
|
||||
.filter(instance -> instance.getState() != null
|
||||
&& !ABANDONED_LAUNCH_STATES.contains(instance.getState().getName()))
|
||||
.collect(Collectors.groupingBy(Instance::getClientToken));
|
||||
}
|
||||
|
||||
private List<String> launchInstances(AutoScalingGroup asg, InstanceRefresh refresh,
|
||||
InstanceRefreshReplacement replacement, List<Instance> existing,
|
||||
Map<String, List<Instance>> acceptedLaunches) {
|
||||
String clientToken = replacement.getLaunchClientToken();
|
||||
LaunchSource launchSource = existing.isEmpty() ? resolveLaunchSource(asg) : null;
|
||||
if (existing.isEmpty() && launchSource == null) {
|
||||
LOG.warnv("ASG {0}: no launch source found, cannot scale out", asg.getAutoScalingGroupName());
|
||||
return List.of();
|
||||
}
|
||||
List<String> launchedInstanceIds = new ArrayList<>();
|
||||
LaunchPlacement placement = existing.isEmpty() ? leastPopulatedPlacement(asg, launchPlacements(asg)) : null;
|
||||
InstanceRefreshLaunch metadata = replacement.getLaunch();
|
||||
if (existing.isEmpty()) {
|
||||
metadata = new InstanceRefreshLaunch(launchSource.launchConfigurationName(),
|
||||
launchSource.launchTemplateId(), launchSource.launchTemplateName(),
|
||||
launchSource.launchTemplateVersion(), launchSource.instanceType(), placement.availabilityZone());
|
||||
replacement.setLaunch(metadata);
|
||||
asgService.saveInstanceRefresh(refresh);
|
||||
}
|
||||
List<Instance> launched = launchInstance(asg, launchSource, placement, clientToken, metadata,
|
||||
existing, launchedInstanceIds, true);
|
||||
if (!launched.isEmpty()) {
|
||||
acceptedLaunches.put(clientToken, launched);
|
||||
preserveScaleOutAllocations(asg, launchedInstanceIds);
|
||||
}
|
||||
// Cleanup after a removed group releases these allocations rather than publishing ownership.
|
||||
launchedInstanceIds.removeIf(id -> asg.getInstances().stream()
|
||||
.noneMatch(instance -> id.equals(instance.getInstanceId())));
|
||||
return launchedInstanceIds;
|
||||
}
|
||||
|
||||
private List<Instance> launchInstance(AutoScalingGroup asg, LaunchSource launchSource,
|
||||
LaunchPlacement placement, String clientToken,
|
||||
InstanceRefreshLaunch metadata, List<Instance> existing,
|
||||
List<String> launchedInstanceIds, boolean refreshLaunch) {
|
||||
List<Instance> instances = existing;
|
||||
if (instances.isEmpty()) {
|
||||
Reservation reservation;
|
||||
try {
|
||||
reservation = ec2Service.runInstances(
|
||||
asg.getRegion(), launchSource.imageId(), launchSource.instanceType(), 1, 1,
|
||||
launchSource.keyName(), launchSource.securityGroupIds(), placement.subnetId(), clientToken,
|
||||
propagatedInstanceTags(asg, launchSource), launchSource.userData(),
|
||||
launchSource.iamInstanceProfile(), launchSource.associatePublicIpAddress(), null, 0, null, null, null,
|
||||
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
|
||||
: encodeLegacyUserData(launchSource.userData()),
|
||||
false, null, null, launchSource.blockDeviceMappings());
|
||||
} catch (RuntimeException launchFailure) {
|
||||
if (!refreshLaunch) {
|
||||
throw launchFailure;
|
||||
}
|
||||
recordFailedActivity(asg, "Launching a replacement EC2 instance.",
|
||||
"An instance refresh requested replacement of active instances.", launchFailure);
|
||||
return List.of();
|
||||
}
|
||||
instances = reservation.getInstances();
|
||||
}
|
||||
for (Instance instance : instances) {
|
||||
launchedInstanceIds.add(instance.getInstanceId());
|
||||
}
|
||||
for (Instance ec2Inst : instances) {
|
||||
if (asg.getInstances().stream().anyMatch(instance ->
|
||||
instance.getInstanceId().equals(ec2Inst.getInstanceId()))) {
|
||||
continue;
|
||||
}
|
||||
AsgInstance asgInst = new AsgInstance();
|
||||
asgInst.setInstanceId(ec2Inst.getInstanceId());
|
||||
asgInst.setLifecycleState("Pending");
|
||||
asgInst.setHealthStatus("Healthy");
|
||||
if (metadata != null) {
|
||||
asgInst.setAvailabilityZone(metadata.availabilityZone() != null ? metadata.availabilityZone()
|
||||
: ec2Inst.getPlacement() != null ? ec2Inst.getPlacement().getAvailabilityZone() : null);
|
||||
asgInst.setLaunchConfigurationName(metadata.launchConfigurationName());
|
||||
asgInst.setLaunchTemplateId(metadata.launchTemplateId());
|
||||
asgInst.setLaunchTemplateName(metadata.launchTemplateName());
|
||||
asgInst.setLaunchTemplateVersion(metadata.launchTemplateVersion());
|
||||
asgInst.setInstanceType(metadata.instanceType());
|
||||
} else if (launchSource != null) {
|
||||
asgInst.setAvailabilityZone(placement.subnetId() == null && placement.availabilityZone() != null
|
||||
? placement.availabilityZone() : ec2Inst.getPlacement() != null
|
||||
? ec2Inst.getPlacement().getAvailabilityZone() : placement.availabilityZone());
|
||||
asgInst.setLaunchConfigurationName(launchSource.launchConfigurationName());
|
||||
asgInst.setLaunchTemplateId(launchSource.launchTemplateId());
|
||||
asgInst.setLaunchTemplateName(launchSource.launchTemplateName());
|
||||
asgInst.setLaunchTemplateVersion(launchSource.launchTemplateVersion());
|
||||
asgInst.setInstanceType(launchSource.instanceType());
|
||||
} else {
|
||||
// Older accepted attempts have no saved source identity; retain actual EC2 metadata.
|
||||
asgInst.setInstanceType(ec2Inst.getInstanceType());
|
||||
if (ec2Inst.getPlacement() != null) {
|
||||
asgInst.setAvailabilityZone(ec2Inst.getPlacement().getAvailabilityZone());
|
||||
}
|
||||
}
|
||||
asg.getInstances().add(asgInst);
|
||||
LOG.infov("ASG {0}: launched instance {1} (Pending)", asg.getAutoScalingGroupName(), ec2Inst.getInstanceId());
|
||||
}
|
||||
return instances;
|
||||
}
|
||||
|
||||
private List<LaunchPlacement> launchPlacements(AutoScalingGroup asg) {
|
||||
if (!asg.getSubnetIds().isEmpty()) {
|
||||
Map<String, Subnet> subnets = ec2Service.describeSubnets(asg.getRegion(), asg.getSubnetIds(), Map.of())
|
||||
|
||||
+123
-62
@@ -468,11 +468,12 @@ public class AutoScalingService {
|
||||
});
|
||||
}
|
||||
groups.remove(key);
|
||||
instanceRefreshes.entrySet().removeIf(e -> region.equals(e.getValue().getRegion())
|
||||
&& name.equals(e.getValue().getAutoScalingGroupName()));
|
||||
}
|
||||
// clean up associated hooks and policies
|
||||
hooks.entrySet().removeIf(e -> e.getValue().getAutoScalingGroupName().equals(name));
|
||||
policies.entrySet().removeIf(e -> e.getValue().getAutoScalingGroupName().equals(name));
|
||||
instanceRefreshes.entrySet().removeIf(e -> e.getValue().getAutoScalingGroupName().equals(name));
|
||||
scheduledActions.entrySet().removeIf(e -> region.equals(e.getValue().getRegion())
|
||||
&& name.equals(e.getValue().getAutoScalingGroupName()));
|
||||
warmPools.remove(warmPoolKey(region, name));
|
||||
@@ -502,11 +503,11 @@ public class AutoScalingService {
|
||||
}
|
||||
}
|
||||
|
||||
void adjustCapacityIfPresent(AutoScalingGroup asg, Runnable adjustment) {
|
||||
void reconcileIfPresent(AutoScalingGroup asg, Runnable reconciliation) {
|
||||
String key = asgKey(asg.getRegion(), asg.getAutoScalingGroupName());
|
||||
synchronized (lockFor(key)) {
|
||||
if (groups.get(key) == asg) {
|
||||
adjustment.run();
|
||||
reconciliation.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -563,8 +564,8 @@ public class AutoScalingService {
|
||||
}
|
||||
|
||||
// An empty list suspends all processes. The reconciler honors Launch and Terminate
|
||||
// for desired-capacity adjustments; other names remain stored state. Refresh selection
|
||||
// and cleanup are separate paths and do not yet honor suspended processes.
|
||||
// for desired-capacity adjustments and owned refresh replacements. Other names remain
|
||||
// stored state; InstanceRefresh also pauses its owned replacement work.
|
||||
private static final List<String> ALL_SCALING_PROCESSES = List.of(
|
||||
"Launch", "Terminate", "AddToLoadBalancer", "AlarmNotification", "AZRebalance",
|
||||
"HealthCheck", "InstanceRefresh", "ReplaceUnhealthy", "ScheduledActions");
|
||||
@@ -683,13 +684,19 @@ public class AutoScalingService {
|
||||
|
||||
public void detachInstances(String region, String name, List<String> instanceIds,
|
||||
boolean decrementDesiredCapacity) {
|
||||
AutoScalingGroup asg = requireGroup(region, name);
|
||||
asg.getInstances().removeIf(i -> instanceIds.contains(i.getInstanceId()));
|
||||
if (decrementDesiredCapacity) {
|
||||
int newDesired = Math.max(asg.getMinSize(), asg.getDesiredCapacity() - instanceIds.size());
|
||||
asg.setDesiredCapacity(newDesired);
|
||||
String key = asgKey(region, name);
|
||||
synchronized (lockFor(key)) {
|
||||
AutoScalingGroup asg = requireGroup(region, name);
|
||||
List<String> detached = asg.getInstances().stream().map(AsgInstance::getInstanceId)
|
||||
.filter(instanceIds::contains).toList();
|
||||
releaseRefreshOwnership(asg, detached);
|
||||
asg.getInstances().removeIf(i -> instanceIds.contains(i.getInstanceId()));
|
||||
if (decrementDesiredCapacity) {
|
||||
int newDesired = Math.max(asg.getMinSize(), asg.getDesiredCapacity() - instanceIds.size());
|
||||
asg.setDesiredCapacity(newDesired);
|
||||
}
|
||||
groups.put(key, asg);
|
||||
}
|
||||
groups.put(asgKey(region, name), asg);
|
||||
}
|
||||
|
||||
public void terminateInstanceInAutoScalingGroup(String region, String instanceId,
|
||||
@@ -700,67 +707,109 @@ public class AutoScalingService {
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ValidationError",
|
||||
"Instance '" + instanceId + "' not found in any Auto Scaling group.", 400));
|
||||
asg.getInstances().stream()
|
||||
.filter(i -> instanceId.equals(i.getInstanceId()))
|
||||
.findFirst()
|
||||
.ifPresent(i -> i.setLifecycleState("Terminating"));
|
||||
if (decrementDesiredCapacity) {
|
||||
int newDesired = Math.max(asg.getMinSize(), asg.getDesiredCapacity() - 1);
|
||||
asg.setDesiredCapacity(newDesired);
|
||||
String key = asgKey(region, asg.getAutoScalingGroupName());
|
||||
synchronized (lockFor(key)) {
|
||||
if (groups.get(key) != asg) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Instance '" + instanceId + "' not found in any Auto Scaling group.", 400);
|
||||
}
|
||||
AsgInstance instance = asg.getInstances().stream()
|
||||
.filter(i -> instanceId.equals(i.getInstanceId())).findFirst()
|
||||
.orElseThrow(() -> new AwsException("ValidationError",
|
||||
"Instance '" + instanceId + "' not found in any Auto Scaling group.", 400));
|
||||
releaseRefreshOwnership(asg, List.of(instanceId));
|
||||
instance.setLifecycleState("Terminating");
|
||||
if (decrementDesiredCapacity) {
|
||||
int newDesired = Math.max(asg.getMinSize(), asg.getDesiredCapacity() - 1);
|
||||
asg.setDesiredCapacity(newDesired);
|
||||
}
|
||||
groups.put(key, asg);
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseRefreshOwnership(AutoScalingGroup asg, List<String> instanceIds) {
|
||||
InstanceRefresh refresh = activeInstanceRefresh(asg);
|
||||
if (refresh != null && refresh.getReplacements() != null) {
|
||||
refresh.getReplacements().removeIf(replacement -> instanceIds.stream().anyMatch(instanceId ->
|
||||
instanceId.equals(replacement.getOriginalInstanceId())
|
||||
|| instanceId.equals(replacement.getReplacementInstanceId())));
|
||||
saveInstanceRefresh(refresh);
|
||||
}
|
||||
groups.put(asgKey(region, asg.getAutoScalingGroupName()), asg);
|
||||
}
|
||||
|
||||
// ── Instance refreshes ────────────────────────────────────────────────────
|
||||
|
||||
public InstanceRefresh startInstanceRefresh(String region, String asgName, InstanceRefresh requestedRefresh) {
|
||||
AutoScalingGroup asg = requireGroup(region, asgName);
|
||||
boolean activeRefresh = instanceRefreshes.values().stream()
|
||||
.filter(r -> region.equals(r.getRegion()))
|
||||
.filter(r -> asgName.equals(r.getAutoScalingGroupName()))
|
||||
.anyMatch(r -> isActiveRefreshStatus(r.getStatus()));
|
||||
if (activeRefresh) {
|
||||
throw new AwsException("InstanceRefreshInProgress",
|
||||
"An active instance refresh already exists for Auto Scaling group '" + asgName + "'.", 400);
|
||||
}
|
||||
synchronized (lockFor(asgKey(region, asgName))) {
|
||||
AutoScalingGroup asg = requireGroup(region, asgName);
|
||||
boolean activeRefresh = instanceRefreshes.values().stream()
|
||||
.filter(r -> region.equals(r.getRegion()))
|
||||
.filter(r -> asgName.equals(r.getAutoScalingGroupName()))
|
||||
.anyMatch(r -> isActiveRefreshStatus(r.getStatus()));
|
||||
if (activeRefresh) {
|
||||
throw new AwsException("InstanceRefreshInProgress",
|
||||
"An active instance refresh already exists for Auto Scaling group '" + asgName + "'.", 400);
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
InstanceRefresh refresh = new InstanceRefresh();
|
||||
refresh.setInstanceRefreshId(UUID.randomUUID().toString());
|
||||
refresh.setAutoScalingGroupName(asgName);
|
||||
refresh.setStrategy(normalizeRefreshStrategy(requestedRefresh.getStrategy()));
|
||||
refresh.setStartTime(now);
|
||||
refresh.setRegion(region);
|
||||
copyDesiredConfiguration(requestedRefresh, refresh);
|
||||
copyPreferences(requestedRefresh, refresh);
|
||||
Instant now = Instant.now();
|
||||
InstanceRefresh refresh = new InstanceRefresh();
|
||||
refresh.setInstanceRefreshId(UUID.randomUUID().toString());
|
||||
refresh.setAutoScalingGroupName(asgName);
|
||||
refresh.setStrategy(normalizeRefreshStrategy(requestedRefresh.getStrategy()));
|
||||
refresh.setStartTime(now);
|
||||
refresh.setRegion(region);
|
||||
copyDesiredConfiguration(requestedRefresh, refresh);
|
||||
copyPreferences(requestedRefresh, refresh);
|
||||
|
||||
applyDesiredConfiguration(asg, refresh);
|
||||
List<String> instanceIds = markInstancesForRefresh(asg, refresh);
|
||||
if (instanceIds.isEmpty()) {
|
||||
refresh.setStatus("Successful");
|
||||
refresh.setStatusReason("Instance refresh completed.");
|
||||
refresh.setPercentageComplete(100);
|
||||
refresh.setInstancesToUpdate(0);
|
||||
refresh.setEndTime(now);
|
||||
} else {
|
||||
refresh.setStatus("InProgress");
|
||||
refresh.setStatusReason("Instance refresh in progress.");
|
||||
refresh.setPercentageComplete(0);
|
||||
refresh.setInstancesToUpdate(instanceIds.size());
|
||||
}
|
||||
instanceRefreshes.put(instanceRefreshKey(region, asgName, refresh.getInstanceRefreshId()), refresh);
|
||||
groups.put(asgKey(region, asgName), asg);
|
||||
if (!instanceIds.isEmpty()) {
|
||||
applyDesiredConfiguration(asg, refresh);
|
||||
List<String> instanceIds = markInstancesForRefresh(asg, refresh);
|
||||
List<InstanceRefreshReplacement> replacements = new ArrayList<>();
|
||||
for (String instanceId : instanceIds) {
|
||||
InstanceRefreshReplacement replacement = new InstanceRefreshReplacement();
|
||||
replacement.setOriginalInstanceId(instanceId);
|
||||
replacement.setLaunchClientToken(UUID.randomUUID().toString());
|
||||
replacements.add(replacement);
|
||||
}
|
||||
refresh.setReplacements(replacements);
|
||||
if (instanceIds.isEmpty()) {
|
||||
refresh.setStatus("Successful");
|
||||
refresh.setStatusReason("Instance refresh completed.");
|
||||
refresh.setPercentageComplete(100);
|
||||
refresh.setInstancesToUpdate(0);
|
||||
refresh.setEndTime(now);
|
||||
} else {
|
||||
refresh.setStatus("InProgress");
|
||||
refresh.setStatusReason("Instance refresh in progress.");
|
||||
refresh.setPercentageComplete(0);
|
||||
refresh.setInstancesToUpdate(instanceIds.size());
|
||||
}
|
||||
instanceRefreshes.put(instanceRefreshKey(region, asgName, refresh.getInstanceRefreshId()), refresh);
|
||||
groups.put(asgKey(region, asgName), asg);
|
||||
if (!instanceIds.isEmpty()) {
|
||||
recordActivity(region, asgName,
|
||||
"Marked EC2 instance(s) for refresh: " + instanceIds,
|
||||
"At " + now + " an instance refresh selected active instances for replacement.",
|
||||
"Successful");
|
||||
}
|
||||
recordActivity(region, asgName,
|
||||
"Marked EC2 instance(s) for refresh: " + instanceIds,
|
||||
"At " + now + " an instance refresh selected active instances for replacement.",
|
||||
"Started instance refresh " + refresh.getInstanceRefreshId() + ".",
|
||||
"At " + now + " an instance refresh was started.",
|
||||
"Successful");
|
||||
return refresh;
|
||||
}
|
||||
recordActivity(region, asgName,
|
||||
"Started instance refresh " + refresh.getInstanceRefreshId() + ".",
|
||||
"At " + now + " an instance refresh was started.",
|
||||
"Successful");
|
||||
return refresh;
|
||||
}
|
||||
|
||||
InstanceRefresh activeInstanceRefresh(AutoScalingGroup asg) {
|
||||
return instanceRefreshes.values().stream()
|
||||
.filter(refresh -> asg.getRegion().equals(refresh.getRegion()))
|
||||
.filter(refresh -> asg.getAutoScalingGroupName().equals(refresh.getAutoScalingGroupName()))
|
||||
.filter(refresh -> isActiveRefreshStatus(refresh.getStatus()))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
void saveInstanceRefresh(InstanceRefresh refresh) {
|
||||
instanceRefreshes.put(instanceRefreshKey(refresh.getRegion(), refresh.getAutoScalingGroupName(),
|
||||
refresh.getInstanceRefreshId()), refresh);
|
||||
}
|
||||
|
||||
public void completeInstanceRefreshIfSettled(String region, String asgName) {
|
||||
@@ -771,7 +820,19 @@ public class AutoScalingService {
|
||||
.filter(r -> isActiveRefreshStatus(r.getStatus()))
|
||||
.collect(Collectors.toList());
|
||||
for (InstanceRefresh refresh : activeRefreshes) {
|
||||
int remaining = remainingInstancesToUpdate(asg);
|
||||
if (refresh.getReplacements() != null) {
|
||||
for (InstanceRefreshReplacement replacement : refresh.getReplacements()) {
|
||||
if (asg.getInstances().stream().anyMatch(instance ->
|
||||
instance.getInstanceId().equals(replacement.getReplacementInstanceId())
|
||||
&& "InService".equals(instance.getLifecycleState()))) {
|
||||
replacement.setPhase("Complete");
|
||||
}
|
||||
}
|
||||
}
|
||||
int remaining = refresh.getReplacements() == null ? remainingInstancesToUpdate(asg)
|
||||
: (int) refresh.getReplacements().stream()
|
||||
.filter(replacement -> !replacement.isComplete())
|
||||
.count();
|
||||
refresh.setInstancesToUpdate(remaining);
|
||||
refresh.setPercentageComplete(remaining == 0 ? 100 : 0);
|
||||
if (remaining == 0) {
|
||||
|
||||
+5
@@ -21,6 +21,11 @@ public class InstanceRefresh {
|
||||
private Instant startTime;
|
||||
private Instant endTime;
|
||||
private String region;
|
||||
private List<InstanceRefreshReplacement> replacements;
|
||||
|
||||
public List<InstanceRefreshReplacement> getReplacements() { return replacements; }
|
||||
public void setReplacements(List<InstanceRefreshReplacement> value) { replacements = value; }
|
||||
|
||||
|
||||
private String desiredLaunchTemplateId;
|
||||
private String desiredLaunchTemplateName;
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** Source identity recorded before a refresh launch can be accepted by EC2. */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record InstanceRefreshLaunch(String launchConfigurationName, String launchTemplateId,
|
||||
String launchTemplateName, String launchTemplateVersion,
|
||||
String instanceType, String availabilityZone) {
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class InstanceRefreshReplacement {
|
||||
private String originalInstanceId;
|
||||
private String replacementInstanceId;
|
||||
private String launchClientToken;
|
||||
private String phase = "Selected";
|
||||
private InstanceRefreshLaunch launch;
|
||||
|
||||
public InstanceRefreshLaunch getLaunch() { return launch; }
|
||||
public void setLaunch(InstanceRefreshLaunch value) { launch = value; }
|
||||
|
||||
public String getPhase() { return phase; }
|
||||
public void setPhase(String value) { phase = value; }
|
||||
|
||||
public boolean isComplete() { return "Complete".equals(phase) || "NoLongerRequired".equals(phase); }
|
||||
|
||||
|
||||
public String getOriginalInstanceId() { return originalInstanceId; }
|
||||
public void setOriginalInstanceId(String value) { originalInstanceId = value; }
|
||||
|
||||
public String getReplacementInstanceId() { return replacementInstanceId; }
|
||||
public void setReplacementInstanceId(String value) { replacementInstanceId = value; }
|
||||
|
||||
public String getLaunchClientToken() { return launchClientToken; }
|
||||
public void setLaunchClientToken(String value) { launchClientToken = value; }
|
||||
}
|
||||
Reference in new issue
Block a user