feat(autoscaling): describe suspended process reasons (#5941)

* feat(autoscaling): describe suspended process reasons

* fix(autoscaling): record suspended process dates
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-18 14:24:58 -04:00
1 parent 317074e303
commit 7ce4b6bd23
8 files changed
+498 -11

No files matched your search

@@ -0,0 +1,78 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;
import software.amazon.awssdk.services.autoscaling.model.SuspendedProcess;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@DisplayName("Local Auto Scaling suspension reasons")
class AutoScalingSuspensionReasonTest {
private static final List<String> ALL_PROCESSES = List.of("Launch", "Terminate", "AddToLoadBalancer",
"AlarmNotification", "AZRebalance", "HealthCheck", "InstanceRefresh", "ReplaceUnhealthy", "ScheduledActions");
@ParameterizedTest
@ValueSource(booleans = {false, true})
@DisplayName("Suspension dates remain stable until a process resumes")
void reasonsFollowSuspensionAndResume(boolean all) {
assumeFalse(TestFixtures.isRealAws(), "Creates local suspension fixtures");
String name = TestFixtures.uniqueName("sdk-suspension-reason");
try (AutoScalingClient client = TestFixtures.autoScalingClient()) {
client.createLaunchConfiguration(request -> request.launchConfigurationName(name)
.imageId("ami-amazonlinux2023").instanceType("t3.micro"));
try {
client.createAutoScalingGroup(request -> request.autoScalingGroupName(name)
.launchConfigurationName(name).minSize(0).maxSize(1).desiredCapacity(0)
.availabilityZones(TestFixtures.availabilityZone()));
try {
assertProcesses(group(client, name), List.of());
List<String> names = all ? List.of() : List.of("Launch", "Terminate");
client.suspendProcesses(request -> request.autoScalingGroupName(name).scalingProcesses(names));
List<SuspendedProcess> original = group(client, name).suspendedProcesses();
client.suspendProcesses(request -> request.autoScalingGroupName(name)
.scalingProcesses("Launch", "Launch"));
assertThat(group(client, name).suspendedProcesses()).isEqualTo(original);
List<String> expected = all ? ALL_PROCESSES : List.of("Launch", "Terminate");
assertProcesses(group(client, name), expected);
client.resumeProcesses(request -> request.autoScalingGroupName(name).scalingProcesses("Launch"));
List<String> remaining = new ArrayList<>(expected);
remaining.remove("Launch");
assertProcesses(group(client, name), remaining);
client.resumeProcesses(request -> request.autoScalingGroupName(name));
assertProcesses(group(client, name), List.of());
} finally {
client.deleteAutoScalingGroup(request -> request.autoScalingGroupName(name).forceDelete(true));
}
} finally {
client.deleteLaunchConfiguration(request -> request.launchConfigurationName(name));
}
}
}
private static AutoScalingGroup group(AutoScalingClient client, String name) {
List<AutoScalingGroup> groups = client.describeAutoScalingGroups(request -> request
.autoScalingGroupNames(name)).autoScalingGroups();
assertThat(groups).hasSize(1);
return groups.get(0);
}
private static void assertProcesses(AutoScalingGroup group, List<String> expected) {
assertThat(group.instances()).isEmpty();
assertThat(group.suspendedProcesses()).extracting(SuspendedProcess::processName)
.containsExactlyInAnyOrderElementsOf(expected);
assertThat(group.suspendedProcesses()).allSatisfy(process -> {
String prefix = "User suspended at ";
assertThat(process.suspensionReason()).startsWith(prefix);
Instant date = Instant.parse(process.suspensionReason().substring(prefix.length()));
assertThat(date.getNano()).isZero();
});
}
}
+13
View File
@@ -165,6 +165,19 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash.
| `DescribeMetricCollectionTypes` | Returns standard metric and granularity names |
| `DescribeAutoScalingNotificationTypes` | Returns all notification type names |
## Suspended Process Reasons
`SuspendProcesses` records when each newly suspended process entered that state.
`DescribeAutoScalingGroups` returns `SuspensionReason` in the form
`User suspended at 2026-10-18T16:00:00Z`. Repeating a suspension preserves its
original time. Resuming a process removes its recorded time; suspending it again
starts a new interval.
Saved groups without a recorded suspension time still report the process name
and omit the optional reason. Floci does not invent a date for those existing
suspensions. A repeated suspension leaves an unknown time unknown until the
process is resumed and suspended again.
## Capacity Reconciler (Phase 2)
Floci runs a background reconciler (10 s fixed rate) that keeps each group's InService instance count aligned with `DesiredCapacity`:
@@ -343,8 +343,14 @@ public class AutoScalingQueryHandler {
xml.end("TerminationPolicies");
xml.start("SuspendedProcesses");
for (String sp : asg.getSuspendedProcesses()) {
xml.start("member").elem("ProcessName", sp).end("member");
AutoScalingGroup.SuspensionState suspension = asg.suspensionState();
for (String sp : suspension.processes()) {
xml.start("member").elem("ProcessName", sp);
Instant suspendedAt = suspension.times().get(sp);
if (suspendedAt != null) {
xml.elem("SuspensionReason", "User suspended at " + suspendedAt);
}
xml.end("member");
}
xml.end("SuspendedProcesses");
@@ -22,6 +22,7 @@ import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.Base64;
import java.util.concurrent.ConcurrentHashMap;
@@ -660,9 +661,17 @@ public class AutoScalingService {
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
List<String> toSuspend = processes.isEmpty() ? ALL_SCALING_PROCESSES : processes;
Set<String> suspended = new LinkedHashSet<>(asg.getSuspendedProcesses());
suspended.addAll(toSuspend);
asg.setSuspendedProcesses(new ArrayList<>(suspended));
AutoScalingGroup.SuspensionState previous = asg.suspensionState();
Set<String> suspended = new LinkedHashSet<>(previous.processes());
Map<String, Instant> times = new LinkedHashMap<>(previous.times());
Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
for (String process : toSuspend) {
if (suspended.add(process)) {
times.put(process, now);
}
}
times.keySet().retainAll(suspended);
asg.updateSuspensionState(new ArrayList<>(suspended), times);
groups.put(key, asg);
}
}
@@ -671,13 +680,16 @@ public class AutoScalingService {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
AutoScalingGroup.SuspensionState previous = asg.suspensionState();
List<String> remaining = new ArrayList<>(previous.processes());
if (processes.isEmpty()) {
asg.setSuspendedProcesses(new ArrayList<>());
remaining.clear();
} else {
List<String> remaining = new ArrayList<>(asg.getSuspendedProcesses());
remaining.removeAll(processes);
asg.setSuspendedProcesses(remaining);
}
Map<String, Instant> times = new LinkedHashMap<>(previous.times());
times.keySet().retainAll(remaining);
asg.updateSuspensionState(remaining, times);
groups.put(key, asg);
}
}
@@ -5,6 +5,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -32,7 +34,7 @@ public class AutoScalingGroup {
private int healthCheckGracePeriod = 0;
private List<AsgInstance> instances = new ArrayList<>();
private List<String> terminationPolicies = new ArrayList<>();
private List<String> suspendedProcesses = new ArrayList<>();
private volatile SuspensionState suspensionState = new SuspensionState(List.of(), Map.of());
// AttachTrafficSources (the modern elbv2/vpc-lattice ASG-to-load-balancer wiring API,
// which aws_autoscaling_traffic_source_attachment uses instead of the older
// AttachLoadBalancerTargetGroups) - identifier -> type ("elbv2", "elb", "vpc-lattice").
@@ -117,8 +119,28 @@ public class AutoScalingGroup {
public List<String> getTerminationPolicies() { return terminationPolicies; }
public void setTerminationPolicies(List<String> v) { this.terminationPolicies = v; }
public List<String> getSuspendedProcesses() { return suspendedProcesses; }
public void setSuspendedProcesses(List<String> v) { this.suspendedProcesses = v; }
/** One immutable view keeps a process name attached to its recorded suspension interval. */
public record SuspensionState(List<String> processes, Map<String, Instant> times) {
public SuspensionState {
processes = processes == null ? List.of() : List.copyOf(processes);
times = times == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(times));
}
}
public List<String> getSuspendedProcesses() { return suspensionState.processes(); }
public void setSuspendedProcesses(List<String> v) {
suspensionState = new SuspensionState(v, suspensionState.times());
}
public Map<String, Instant> getSuspendedProcessTimes() { return suspensionState.times(); }
public void setSuspendedProcessTimes(Map<String, Instant> v) {
suspensionState = new SuspensionState(suspensionState.processes(), v);
}
public SuspensionState suspensionState() { return suspensionState; }
public void updateSuspensionState(List<String> processes, Map<String, Instant> times) {
suspensionState = new SuspensionState(processes, times);
}
public Map<String, String> getTrafficSourceTypeByIdentifier() { return trafficSourceTypeByIdentifier; }
public void setTrafficSourceTypeByIdentifier(Map<String, String> v) { this.trafficSourceTypeByIdentifier = v; }
@@ -30,6 +30,7 @@ import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -141,6 +142,34 @@ class AutoScalingRefreshStorageTest {
assertEquals("us-east-1b", group.getInstances().getFirst().getAvailabilityZone());
}
@ParameterizedTest
@ValueSource(strings = {"persistent", "hybrid", "wal"})
void suspensionDatesSurviveQuiescentStorageReload(String mode) throws IOException {
setUp(mode);
service.suspendProcesses(REGION, "suspended-group", List.of("Launch", "Terminate"));
Map<String, Instant> recorded = group.getSuspendedProcessTimes();
restart(mode);
assertEquals(List.of("Launch", "Terminate"), group.getSuspendedProcesses());
assertEquals(recorded, group.getSuspendedProcessTimes());
service.suspendProcesses(REGION, "suspended-group", List.of("Launch"));
assertEquals(recorded, group.getSuspendedProcessTimes());
service.resumeProcesses(REGION, "suspended-group", List.of("Launch"));
restart(mode);
assertEquals(Map.of("Terminate", recorded.get("Terminate")), group.getSuspendedProcessTimes());
service.resumeProcesses(REGION, "suspended-group", List.of());
restart(mode);
assertTrue(group.getSuspendedProcessTimes().isEmpty());
assertTrue(group.getSuspendedProcesses().isEmpty());
group.updateSuspensionState(List.of("Launch"), Map.of());
service.saveAutoScalingGroupIfPresent(group);
restart(mode);
service.suspendProcesses(REGION, "suspended-group", List.of("Launch"));
assertTrue(group.getSuspendedProcessTimes().isEmpty(), "legacy history remains unknown");
service.resumeProcesses(REGION, "suspended-group", List.of("Launch"));
service.suspendProcesses(REGION, "suspended-group", List.of("Launch"));
assertNotNull(group.getSuspendedProcessTimes().get("Launch"));
}
@AfterEach
void closeStorage() {
factories.forEach(StorageFactory::shutdownAll);
@@ -0,0 +1,157 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class AutoScalingSuspensionReasonIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static final String REGION = "us-east-1";
private static final String GROUP = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member";
private static final String REASON_PREFIX = "User suspended at ";
private static final List<String> ALL_PROCESSES = List.of("Launch", "Terminate", "AddToLoadBalancer",
"AlarmNotification", "AZRebalance", "HealthCheck", "InstanceRefresh", "ReplaceUnhealthy", "ScheduledActions");
@ParameterizedTest
@ValueSource(booleans = {false, true})
void suspensionReasonsFollowExplicitAndAllProcessTransitions(boolean all) {
String name = "reason-" + UUID.randomUUID();
createConfiguration(ACCOUNT, REGION, name);
try {
createGroup(ACCOUNT, REGION, name);
try {
Response initial = describe(ACCOUNT, REGION, name);
process(ACCOUNT, REGION, "SuspendProcesses", name,
all ? List.of() : List.of("Launch", "Terminate"));
Response firstSuspension = describe(ACCOUNT, REGION, name);
process(ACCOUNT, REGION, "SuspendProcesses", name, List.of("Launch", "Launch"));
Response suspended = describe(ACCOUNT, REGION, name);
process(ACCOUNT, REGION, "ResumeProcesses", name, List.of("Launch"));
Response partial = describe(ACCOUNT, REGION, name);
process(ACCOUNT, REGION, "ResumeProcesses", name, List.of());
Response resumed = describe(ACCOUNT, REGION, name);
process(ACCOUNT, REGION, "SuspendProcesses", name, List.of("Launch"));
Response resuspended = describe(ACCOUNT, REGION, name);
List<String> expected = all ? ALL_PROCESSES : List.of("Launch", "Terminate");
List<String> remaining = new ArrayList<>(expected);
remaining.remove("Launch");
assertAll(() -> assertSuspensions(initial, List.of()),
() -> assertSuspensions(suspended, expected),
() -> assertSuspensions(partial, remaining),
() -> assertSuspensions(resumed, List.of()),
() -> assertSuspensions(resuspended, List.of("Launch")),
() -> assertEquals(firstSuspension.xmlPath().getList(GROUP + ".SuspendedProcesses.member"),
suspended.xmlPath().getList(GROUP + ".SuspendedProcesses.member")));
} finally {
deleteGroup(ACCOUNT, REGION, name);
}
} finally {
deleteConfiguration(ACCOUNT, REGION, name);
}
}
@ParameterizedTest
@CsvSource({"222222222222,us-east-1", "111111111111,us-west-2"})
void sameNamedGroupsKeepTheirOwnReasons(String otherAccount, String otherRegion) {
String name = "reason-scope-" + UUID.randomUUID();
createConfiguration(ACCOUNT, REGION, name);
try {
createGroup(ACCOUNT, REGION, name);
try {
createConfiguration(otherAccount, otherRegion, name);
try {
createGroup(otherAccount, otherRegion, name);
try {
process(ACCOUNT, REGION, "SuspendProcesses", name, List.of("Launch"));
Response unrelated = describe(otherAccount, otherRegion, name);
process(otherAccount, otherRegion, "SuspendProcesses", name, List.of("Terminate"));
Response owner = describe(ACCOUNT, REGION, name);
Response other = describe(otherAccount, otherRegion, name);
assertAll(() -> assertSuspensions(unrelated, List.of()),
() -> assertSuspensions(owner, List.of("Launch")),
() -> assertSuspensions(other, List.of("Terminate")));
} finally {
deleteGroup(otherAccount, otherRegion, name);
}
} finally {
deleteConfiguration(otherAccount, otherRegion, name);
}
} finally {
deleteGroup(ACCOUNT, REGION, name);
}
} finally {
deleteConfiguration(ACCOUNT, REGION, name);
}
}
private static void assertSuspensions(Response response, List<String> expected) {
List<String> names = response.xmlPath().getList(GROUP + ".SuspendedProcesses.member.ProcessName", String.class);
List<String> reasons = response.xmlPath().getList(GROUP + ".SuspendedProcesses.member.SuspensionReason", String.class);
assertAll(() -> assertEquals(expected.size(), names.size()),
() -> assertEquals(new HashSet<>(expected), new HashSet<>(names)),
() -> assertEquals(expected.size(), reasons.size()),
() -> reasons.forEach(reason -> {
assertTrue(reason.startsWith(REASON_PREFIX), reason);
assertDoesNotThrow(() -> Instant.parse(reason.substring(REASON_PREFIX.length())));
}),
() -> assertTrue(response.xmlPath().getList(GROUP + ".Instances.member").isEmpty()));
}
private static RequestSpecification request(String account, String region, String action) {
return given().header("Authorization", auth(account, "20261018", region, "autoscaling"))
.formParam("Action", action);
}
private static void createConfiguration(String account, String region, String name) {
request(account, region, "CreateLaunchConfiguration").formParam("LaunchConfigurationName", name)
.formParam("ImageId", "ami-amazonlinux2023").formParam("InstanceType", "t3.micro")
.post("/").then().statusCode(200);
}
private static void createGroup(String account, String region, String name) {
request(account, region, "CreateAutoScalingGroup").formParam("AutoScalingGroupName", name)
.formParam("LaunchConfigurationName", name).formParam("MinSize", 0).formParam("MaxSize", 1)
.formParam("DesiredCapacity", 0).formParam("AvailabilityZones.member.1", region + "a")
.post("/").then().statusCode(200);
}
private static Response describe(String account, String region, String name) {
Response response = request(account, region, "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200).extract().response();
assertEquals(List.of(name), response.xmlPath().getList(GROUP + ".AutoScalingGroupName", String.class));
return response;
}
private static void process(String account, String region, String action, String name, List<String> names) {
RequestSpecification request = request(account, region, action).formParam("AutoScalingGroupName", name);
for (int i = 0; i < names.size(); i++) {
request.formParam("ScalingProcesses.member." + (i + 1), names.get(i));
}
request.post("/").then().statusCode(200);
}
private static void deleteGroup(String account, String region, String name) {
request(account, region, "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", name)
.formParam("ForceDelete", true).post("/").then().statusCode(200);
}
private static void deleteConfiguration(String account, String region, String name) {
request(account, region, "DeleteLaunchConfiguration").formParam("LaunchConfigurationName", name)
.post("/").then().statusCode(200);
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.autoscaling;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.restassured.path.xml.XmlPath;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class AutoScalingSuspensionReasonTest {
private static final Instant OLD = Instant.parse("2024-02-09T01:26:39Z");
private static final String PATH = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.SuspendedProcesses.member";
@ParameterizedTest
@ValueSource(booleans = {false, true})
void legacyProcessNamesOmitReasonsWhenNoSuspensionTimeWasRecorded(boolean explicitNull) throws Exception {
ObjectMapper mapper = mapper();
String extra = explicitNull ? ", \"suspendedProcessTimes\":null" : "";
AutoScalingGroup group = mapper.readValue("{\"suspendedProcesses\":[\"Launch\",\"Terminate\"]"
+ extra + "}", AutoScalingGroup.class);
AutoScalingService service = service(group, "legacy-reason");
XmlPath xml = describe(service, "legacy-reason");
assertEquals(List.of("Launch", "Terminate"), xml.getList(PATH + ".ProcessName", String.class));
assertTrue(xml.getList(PATH + ".SuspensionReason", String.class).isEmpty());
service.suspendProcesses("us-east-1", "legacy-reason", List.of("Launch"));
assertTrue(group.getSuspendedProcessTimes().isEmpty(), "duplicate suspension must not invent a legacy date");
assertFalse(mapper.writeValueAsString(group).contains("suspensionState"));
}
@Test
void timestampsRestoreInEitherJsonPropertyOrderAndSnapshotCopiesInputs() throws Exception {
for (String json : List.of(
"{\"suspendedProcessTimes\":{\"Launch\":\"2024-02-09T01:26:39Z\"},\"suspendedProcesses\":[\"Launch\"]}",
"{\"suspendedProcesses\":[\"Launch\"],\"suspendedProcessTimes\":{\"Launch\":\"2024-02-09T01:26:39Z\"}}")) {
AutoScalingGroup restored = mapper().readValue(json, AutoScalingGroup.class);
assertEquals(Map.of("Launch", OLD), restored.suspensionState().times());
assertEquals(List.of("Launch"), restored.suspensionState().processes());
}
AutoScalingGroup group = new AutoScalingGroup();
List<String> names = new ArrayList<>(List.of("Launch"));
Map<String, Instant> times = new LinkedHashMap<>(Map.of("Launch", OLD));
group.updateSuspensionState(names, times);
names.clear();
times.clear();
assertEquals(List.of("Launch"), group.suspensionState().processes());
assertEquals(Map.of("Launch", OLD), group.suspensionState().times());
assertThrows(UnsupportedOperationException.class, () -> group.suspensionState().times().clear());
assertThrows(UnsupportedOperationException.class, () -> group.suspensionState().processes().clear());
}
@Test
void duplicatePreservesTheIntervalAndNewSuspensionReplacesOrphanHistory() {
AutoScalingGroup group = new AutoScalingGroup();
group.updateSuspensionState(List.of("Launch"), Map.of("Launch", OLD, "Terminate", OLD));
AutoScalingService service = service(group, "interval");
service.suspendProcesses("us-east-1", "interval", List.of("Launch", "Launch"));
assertEquals(Map.of("Launch", OLD), group.getSuspendedProcessTimes());
service.suspendProcesses("us-east-1", "interval", List.of("Terminate"));
assertNotEquals(OLD, group.getSuspendedProcessTimes().get("Terminate"));
service.resumeProcesses("us-east-1", "interval", List.of("Launch"));
assertFalse(group.getSuspendedProcessTimes().containsKey("Launch"));
service.suspendProcesses("us-east-1", "interval", List.of("Launch"));
assertNotEquals(OLD, group.getSuspendedProcessTimes().get("Launch"));
assertEquals(0, group.getSuspendedProcessTimes().get("Launch").getNano());
service.resumeProcesses("us-east-1", "interval", List.of());
assertTrue(group.getSuspendedProcesses().isEmpty());
assertTrue(group.getSuspendedProcessTimes().isEmpty());
}
@Test
void describeKeepsOneIntervalSnapshotWhileSameGroupAndUnrelatedGroupProgress() throws Exception {
CountDownLatch captured = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> reader = new AtomicReference<>();
AutoScalingGroup group = new AutoScalingGroup() {
@Override
public SuspensionState suspensionState() {
SuspensionState snapshot = super.suspensionState();
if (Thread.currentThread() == reader.get()) {
captured.countDown();
try {
assertTrue(release.await(5, TimeUnit.SECONDS));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
return snapshot;
}
};
group.updateSuspensionState(List.of("Launch"), Map.of("Launch", OLD));
AutoScalingService service = service(group, "snapshot");
service(service, new AutoScalingGroup(), "unrelated");
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
Future<XmlPath> description = workers.submit(() -> {
reader.set(Thread.currentThread());
return describe(service, "snapshot");
});
assertTrue(captured.await(5, TimeUnit.SECONDS));
Future<?> mutations = workers.submit(() -> {
service.resumeProcesses("us-east-1", "snapshot", List.of());
service.suspendProcesses("us-east-1", "snapshot", List.of("Terminate"));
service.suspendProcesses("us-east-1", "unrelated", List.of("Launch"));
});
mutations.get(2, TimeUnit.SECONDS);
release.countDown();
XmlPath old = description.get(5, TimeUnit.SECONDS);
assertEquals(List.of("Launch"), old.getList(PATH + ".ProcessName", String.class));
assertEquals(List.of("User suspended at " + OLD), old.getList(PATH + ".SuspensionReason", String.class));
reader.set(null);
XmlPath current = describe(service, "snapshot");
assertEquals(List.of("Terminate"), current.getList(PATH + ".ProcessName", String.class));
assertEquals(List.of("User suspended at " + group.getSuspendedProcessTimes().get("Terminate")),
current.getList(PATH + ".SuspensionReason", String.class));
assertEquals(List.of("Launch"), service.describeAutoScalingGroups("us-east-1", List.of("unrelated"))
.getFirst().getSuspendedProcesses());
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
}
}
private static ObjectMapper mapper() {
return new ObjectMapper().registerModule(new JavaTimeModule());
}
private static AutoScalingService service(AutoScalingGroup group, String name) {
AutoScalingService service = new AutoScalingService();
service.regionResolver = new RegionResolver("us-east-1", "000000000000");
service(service, group, name);
return service;
}
private static void service(AutoScalingService service, AutoScalingGroup group, String name) {
group.setAutoScalingGroupName(name);
group.setAutoScalingGroupArn("arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:id:autoScalingGroupName/" + name);
group.setCreatedTime(OLD);
group.setRegion("us-east-1");
service.groups.put(AutoScalingService.asgKey("us-east-1", name), group);
}
private static XmlPath describe(AutoScalingService service, String name) {
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
params.add("AutoScalingGroupNames.member.1", name);
Response response = new AutoScalingQueryHandler(service).handle("DescribeAutoScalingGroups", params, "us-east-1");
assertEquals(200, response.getStatus());
return new XmlPath((String) response.getEntity());
}
}