mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(autoscaling): name the group and capitalize health in DescribeAutoScalingInstances (#6940)
This commit is contained in:
1 parent
8270cc7c41
commit
b73f643d3f
7 files changed
+230
-13
No files matched your search
+83
@@ -0,0 +1,83 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
|
||||
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
|
||||
import software.amazon.awssdk.services.autoscaling.model.AutoScalingInstanceDetails;
|
||||
import software.amazon.awssdk.services.autoscaling.model.Instance;
|
||||
import software.amazon.awssdk.services.autoscaling.model.LifecycleState;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.InstanceType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* {@code DescribeAutoScalingInstances} names the group of each instance, a required member of
|
||||
* {@code AutoScalingInstanceDetails}, and spells its health in capitals, while the instance list of
|
||||
* {@code DescribeAutoScalingGroups} keeps {@code Healthy} and {@code Unhealthy}.
|
||||
*/
|
||||
@DisplayName("Auto Scaling instance details")
|
||||
class AutoScalingInstanceDetailsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("DescribeAutoScalingInstances names the group and reports HEALTHY and UNHEALTHY")
|
||||
void describeAutoScalingInstancesNamesTheGroupAndCapitalizesHealth() throws InterruptedException {
|
||||
String name = TestFixtures.uniqueName("instance-details");
|
||||
String zone = TestFixtures.availabilityZone();
|
||||
try (AutoScalingClient autoScaling = TestFixtures.autoScalingClient();
|
||||
Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
ec2.createLaunchTemplate(request -> request.launchTemplateName(name).launchTemplateData(data -> data
|
||||
.imageId("ami-amazonlinux2023").instanceType(InstanceType.T3_MICRO)));
|
||||
try {
|
||||
autoScaling.createAutoScalingGroup(request -> request.autoScalingGroupName(name)
|
||||
.launchTemplate(template -> template.launchTemplateName(name).version("1"))
|
||||
.minSize(0).maxSize(2).desiredCapacity(2).availabilityZones(zone));
|
||||
|
||||
AtomicReference<List<Instance>> members = new AtomicReference<>(List.of());
|
||||
TestFixtures.await(() -> {
|
||||
members.set(autoScaling.describeAutoScalingGroups(request -> request.autoScalingGroupNames(name))
|
||||
.autoScalingGroups().get(0).instances());
|
||||
// Floci overwrites health with Healthy when it promotes a Pending member, so a
|
||||
// member is marked unhealthy only once both are in service.
|
||||
return members.get().size() == 2 && members.get().stream()
|
||||
.allMatch(member -> member.lifecycleState() == LifecycleState.IN_SERVICE);
|
||||
}, name, "two in-service instances", TimeUnit.SECONDS.toNanos(120), 1000);
|
||||
String healthy = members.get().get(0).instanceId();
|
||||
String unhealthy = members.get().get(1).instanceId();
|
||||
// AWS replaces an unhealthy member; the group keeps it here for the assertions.
|
||||
autoScaling.suspendProcesses(request -> request.autoScalingGroupName(name)
|
||||
.scalingProcesses("ReplaceUnhealthy"));
|
||||
autoScaling.setInstanceHealth(request -> request.instanceId(unhealthy).healthStatus("Unhealthy")
|
||||
.shouldRespectGracePeriod(false));
|
||||
|
||||
List<AutoScalingInstanceDetails> details = autoScaling.describeAutoScalingInstances(request ->
|
||||
request.instanceIds(healthy, unhealthy)).autoScalingInstances();
|
||||
assertThat(details).extracting(AutoScalingInstanceDetails::autoScalingGroupName)
|
||||
.containsExactly(name, name);
|
||||
assertThat(details).filteredOn(detail -> detail.instanceId().equals(healthy))
|
||||
.extracting(AutoScalingInstanceDetails::healthStatus).containsExactly("HEALTHY");
|
||||
assertThat(details).filteredOn(detail -> detail.instanceId().equals(unhealthy))
|
||||
.extracting(AutoScalingInstanceDetails::healthStatus).containsExactly("UNHEALTHY");
|
||||
|
||||
List<Instance> group = autoScaling.describeAutoScalingGroups(request ->
|
||||
request.autoScalingGroupNames(name)).autoScalingGroups().get(0).instances();
|
||||
assertThat(group).filteredOn(instance -> instance.instanceId().equals(healthy))
|
||||
.extracting(Instance::healthStatus).containsExactly("Healthy");
|
||||
assertThat(group).filteredOn(instance -> instance.instanceId().equals(unhealthy))
|
||||
.extracting(Instance::healthStatus).containsExactly("Unhealthy");
|
||||
} finally {
|
||||
try {
|
||||
autoScaling.deleteAutoScalingGroup(request -> request.autoScalingGroupName(name).forceDelete(true));
|
||||
} catch (AutoScalingException ignored) {
|
||||
// A group that was never created has nothing to clean up.
|
||||
}
|
||||
ec2.deleteLaunchTemplate(request -> request.launchTemplateName(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ EC2 instance can use a default subnet in a different zone.
|
||||
|
||||
| Operation | Notes |
|
||||
|---|---|
|
||||
| `DescribeAutoScalingInstances` | Returns all ASG-tracked instances with lifecycle state and health status |
|
||||
| `DescribeAutoScalingInstances` | Returns all ASG-tracked instances with their group name, lifecycle state and health status. Health is in capitals here: `HEALTHY`, as the AWS samples show, and `UNHEALTHY` by the same rule. `DescribeAutoScalingGroups` reports `Healthy` or `Unhealthy` |
|
||||
| `SetInstanceHealth` | Updates an instance's health status immediately; accepts but does not enforce the grace-period flag |
|
||||
| `SetInstanceProtection` | Enables or disables scale-in protection for named instances in a group |
|
||||
| `SetDesiredCapacity` | Updates desired count; reconciler handles scale-out / scale-in within 10 s |
|
||||
|
||||
+8
-3
@@ -602,18 +602,23 @@ public class AutoScalingQueryHandler {
|
||||
// ── Instances ─────────────────────────────────────────────────────────────
|
||||
|
||||
private Response handleDescribeAutoScalingInstances(MultivaluedMap<String, String> p, String region) {
|
||||
List<AsgInstance> instances = service.describeAutoScalingInstances(
|
||||
List<AutoScalingService.AutoScalingInstanceDetails> instances = service.describeAutoScalingInstances(
|
||||
region, memberList(p, "InstanceIds"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeAutoScalingInstancesResponse", NS)
|
||||
.start("DescribeAutoScalingInstancesResult")
|
||||
.start("AutoScalingInstances");
|
||||
for (AsgInstance inst : instances) {
|
||||
for (AutoScalingService.AutoScalingInstanceDetails details : instances) {
|
||||
AsgInstance inst = details.instance();
|
||||
// AWS's samples of this API spell health HEALTHY, and UNHEALTHY follows the same rule.
|
||||
// DescribeAutoScalingGroups and SetInstanceHealth use the stored Healthy and Unhealthy.
|
||||
String healthStatus = inst.getHealthStatus() == null ? null : inst.getHealthStatus().toUpperCase(Locale.ROOT);
|
||||
xml.start("member")
|
||||
.elem("InstanceId", inst.getInstanceId())
|
||||
.elem("AutoScalingGroupName", details.autoScalingGroupName())
|
||||
.elem("AvailabilityZone", inst.getAvailabilityZone())
|
||||
.elem("LifecycleState", inst.getLifecycleState())
|
||||
.elem("HealthStatus", inst.getHealthStatus())
|
||||
.elem("HealthStatus", healthStatus)
|
||||
.elem("ProtectedFromScaleIn", String.valueOf(inst.isProtectedFromScaleIn()));
|
||||
if (inst.getLaunchConfigurationName() != null) {
|
||||
xml.elem("LaunchConfigurationName", inst.getLaunchConfigurationName());
|
||||
|
||||
+8
-4
@@ -766,15 +766,19 @@ public class AutoScalingService implements PassedRoleLookup {
|
||||
|
||||
// ── Instance management ────────────────────────────────────────────────────
|
||||
|
||||
public List<AsgInstance> describeAutoScalingInstances(String region, List<String> instanceIds) {
|
||||
List<AsgInstance> all = groups.values().stream()
|
||||
/** An instance as {@code DescribeAutoScalingInstances} reports it: with the name of the group it belongs to. */
|
||||
public record AutoScalingInstanceDetails(String autoScalingGroupName, AsgInstance instance) {}
|
||||
|
||||
public List<AutoScalingInstanceDetails> describeAutoScalingInstances(String region, List<String> instanceIds) {
|
||||
List<AutoScalingInstanceDetails> all = groups.values().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.filter(g -> region.equals(g.getRegion()))
|
||||
.flatMap(g -> g.getInstances().stream())
|
||||
.flatMap(g -> g.getInstances().stream()
|
||||
.map(i -> new AutoScalingInstanceDetails(g.getAutoScalingGroupName(), i)))
|
||||
.collect(Collectors.toList());
|
||||
if (instanceIds != null && !instanceIds.isEmpty()) {
|
||||
Set<String> ids = new HashSet<>(instanceIds);
|
||||
return all.stream().filter(i -> ids.contains(i.getInstanceId())).collect(Collectors.toList());
|
||||
return all.stream().filter(d -> ids.contains(d.instance().getInstanceId())).collect(Collectors.toList());
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* {@code DescribeAutoScalingInstances} as the EC2 Auto Scaling API reference shows it: every member
|
||||
* names the group it belongs to, a required member of {@code AutoScalingInstanceDetails}, and spells
|
||||
* its health in capitals ({@code HEALTHY}). The same instances keep the {@code Healthy} spelling in the
|
||||
* instance list of {@code DescribeAutoScalingGroups}, which is also what {@code SetInstanceHealth} accepts.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AutoScalingInstanceDetailsIntegrationTest {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=434343434343/20261028/us-east-1/autoscaling/aws4_request";
|
||||
private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/");
|
||||
private static final String DETAILS =
|
||||
"DescribeAutoScalingInstancesResponse.DescribeAutoScalingInstancesResult.AutoScalingInstances.member";
|
||||
private static final String GROUP_INSTANCES =
|
||||
"DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member.Instances.member";
|
||||
|
||||
@Inject
|
||||
AutoScalingReconciler reconciler;
|
||||
|
||||
@Test
|
||||
void eachInstanceNamesItsGroupAndReportsHealthInCapitals() {
|
||||
String name = "instance-details-" + UUID.randomUUID();
|
||||
String other = name + "-other";
|
||||
given().header("Authorization", EC2_AUTH).formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-12345678")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.post("/").then().statusCode(200);
|
||||
createGroup(name, name, 2);
|
||||
createGroup(other, name, 1);
|
||||
try {
|
||||
// The first pass launches the members and the second puts them in service. Floci's
|
||||
// reconciler overwrites health with Healthy when it promotes a Pending member, so a
|
||||
// member is marked unhealthy only once both are in service.
|
||||
reconciler.reconcileAll();
|
||||
reconciler.reconcileAll();
|
||||
XmlPath launched = groupInstances(name);
|
||||
assertEquals(List.of("InService", "InService"), launched.getList(GROUP_INSTANCES + ".LifecycleState"));
|
||||
List<String> members = launched.getList(GROUP_INSTANCES + ".InstanceId");
|
||||
String healthy = members.get(0);
|
||||
String unhealthy = members.get(1);
|
||||
String otherMember = groupInstances(other).getString(GROUP_INSTANCES + ".InstanceId");
|
||||
// AWS replaces an unhealthy member; the group keeps it here for the assertions.
|
||||
given().header("Authorization", AUTH).formParam("Action", "SuspendProcesses")
|
||||
.formParam("AutoScalingGroupName", name)
|
||||
.formParam("ScalingProcesses.member.1", "ReplaceUnhealthy")
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", AUTH).formParam("Action", "SetInstanceHealth")
|
||||
.formParam("InstanceId", unhealthy).formParam("HealthStatus", "Unhealthy")
|
||||
.formParam("ShouldRespectGracePeriod", "false")
|
||||
.post("/").then().statusCode(200);
|
||||
|
||||
XmlPath details = given().header("Authorization", AUTH)
|
||||
.formParam("Action", "DescribeAutoScalingInstances")
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
assertEquals(3, details.getList(DETAILS + ".InstanceId").size());
|
||||
assertAll(
|
||||
() -> assertEquals(3, details.getList(DETAILS + ".AutoScalingGroupName").size(),
|
||||
"AutoScalingGroupName is a required member of every AutoScalingInstanceDetails"),
|
||||
() -> assertEquals(name, member(details, healthy, "AutoScalingGroupName")),
|
||||
() -> assertEquals(name, member(details, unhealthy, "AutoScalingGroupName")),
|
||||
() -> assertEquals(other, member(details, otherMember, "AutoScalingGroupName")),
|
||||
() -> assertEquals("HEALTHY", member(details, healthy, "HealthStatus")),
|
||||
() -> assertEquals("UNHEALTHY", member(details, unhealthy, "HealthStatus")),
|
||||
() -> assertEquals("HEALTHY", member(details, otherMember, "HealthStatus")));
|
||||
|
||||
XmlPath filtered = given().header("Authorization", AUTH)
|
||||
.formParam("Action", "DescribeAutoScalingInstances")
|
||||
.formParam("InstanceIds.member.1", otherMember)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
assertEquals(List.of(other), filtered.getList(DETAILS + ".AutoScalingGroupName"));
|
||||
|
||||
XmlPath group = groupInstances(name);
|
||||
assertEquals("Healthy", member(group, GROUP_INSTANCES, healthy, "HealthStatus"));
|
||||
assertEquals("Unhealthy", member(group, GROUP_INSTANCES, unhealthy, "HealthStatus"));
|
||||
} finally {
|
||||
for (String group : List.of(name, other)) {
|
||||
given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/");
|
||||
}
|
||||
given().header("Authorization", EC2_AUTH).formParam("Action", "DeleteLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name).post("/");
|
||||
}
|
||||
}
|
||||
|
||||
private static void createGroup(String group, String launchTemplate, int desiredCapacity) {
|
||||
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", group)
|
||||
.formParam("LaunchTemplate.LaunchTemplateName", launchTemplate)
|
||||
.formParam("LaunchTemplate.Version", "1")
|
||||
.formParam("MinSize", "0").formParam("MaxSize", "3")
|
||||
.formParam("DesiredCapacity", String.valueOf(desiredCapacity))
|
||||
.formParam("AvailabilityZones.member.1", "us-east-1a")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static XmlPath groupInstances(String group) {
|
||||
return given().header("Authorization", AUTH).formParam("Action", "DescribeAutoScalingGroups")
|
||||
.formParam("AutoScalingGroupNames.member.1", group)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static String member(XmlPath xml, String instanceId, String field) {
|
||||
return member(xml, DETAILS, instanceId, field);
|
||||
}
|
||||
|
||||
private static String member(XmlPath xml, String path, String instanceId, String field) {
|
||||
return xml.getString(path + ".find { it.InstanceId == '" + instanceId + "' }." + field);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -212,7 +212,7 @@ class AutoScalingQueryHandlerTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("<SetInstanceProtectionResponse"));
|
||||
assertTrue(service.describeAutoScalingInstances(REGION, List.of("i-protected"))
|
||||
.getFirst().isProtectedFromScaleIn());
|
||||
.getFirst().instance().isProtectedFromScaleIn());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,7 +238,7 @@ class AutoScalingQueryHandlerTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("<SetInstanceHealthResponse"));
|
||||
assertEquals("Unhealthy", service.describeAutoScalingInstances(REGION, List.of("i-unhealthy"))
|
||||
.getFirst().getHealthStatus());
|
||||
.getFirst().instance().getHealthStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -266,7 +266,7 @@ class AutoScalingQueryHandlerTest {
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("ValidationError"));
|
||||
assertEquals(false, service.describeAutoScalingInstances(REGION, List.of("i-flagless"))
|
||||
.getFirst().isProtectedFromScaleIn(),
|
||||
.getFirst().instance().isProtectedFromScaleIn(),
|
||||
"a rejected request must not silently strip/apply protection");
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ class AutoScalingQueryHandlerTest {
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals(false, service.describeAutoScalingInstances(REGION, List.of("i-malformed"))
|
||||
.getFirst().isProtectedFromScaleIn(),
|
||||
.getFirst().instance().isProtectedFromScaleIn(),
|
||||
"a malformed boolean must not silently coerce to false and succeed");
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1065,7 +1065,7 @@ class AutoScalingServiceTest {
|
||||
|
||||
assertDoesNotThrow(() -> service.setInstanceHealth(REGION, "i-health", "Unhealthy", true));
|
||||
assertEquals("Unhealthy", service.describeAutoScalingInstances(REGION, List.of("i-health"))
|
||||
.getFirst().getHealthStatus());
|
||||
.getFirst().instance().getHealthStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user