mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
4d3f3b664d
commit
ead5d4a3fe
11 files changed
+1776
-88
No files matched your search
+70
@@ -919,6 +919,76 @@ class AutoScalingReconcilerTest {
|
||||
eq("Successful"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Pending", "Terminating"})
|
||||
void memberEc2HasNoRecordOfIsPrunedAsStale(String lifecycleState) {
|
||||
AutoScalingService asgService = scalingService();
|
||||
stubActivityRecording(asgService);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("app-asg");
|
||||
asg.setDesiredCapacity(0);
|
||||
asg.getInstances().add(instance("i-gone", lifecycleState));
|
||||
// Ec2Service answers an id it has no record of with InvalidInstanceID.NotFound, not with an empty list.
|
||||
AwsException notFound = new AwsException("InvalidInstanceID.NotFound",
|
||||
"The instance ID 'i-gone' does not exist", 400);
|
||||
when(ec2Service.describeInstances("us-east-1", List.of("i-gone"), null)).thenThrow(notFound);
|
||||
when(ec2Service.terminateInstances("us-east-1", List.of("i-gone"))).thenThrow(notFound);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
assertEquals(0, asg.getInstances().size());
|
||||
verify(asgService).recordActivity(
|
||||
eq("us-east-1"),
|
||||
eq("app-asg"),
|
||||
eq("Removing stale EC2 instance reference(s): [i-gone]"),
|
||||
eq("Persisted Auto Scaling state referenced instance containers that are no longer running."),
|
||||
eq("Successful"));
|
||||
verify(asgService, never()).recordActivity(anyString(), anyString(),
|
||||
ArgumentMatchers.startsWith("Terminating EC2 instance(s) for refresh"), anyString(), eq("Failed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminatingBatchWithAMemberEc2HasNoRecordOfStillTerminatesTheRest() {
|
||||
AutoScalingService asgService = scalingService();
|
||||
stubActivityRecording(asgService);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("app-asg");
|
||||
asg.setDesiredCapacity(0);
|
||||
asg.getInstances().add(instance("i-gone", "Terminating"));
|
||||
asg.getInstances().add(instance("i-alive", "Terminating"));
|
||||
AwsException notFound = new AwsException("InvalidInstanceID.NotFound",
|
||||
"The instance ID 'i-gone' does not exist", 400);
|
||||
when(ec2Service.describeInstances("us-east-1", List.of("i-gone"), null)).thenThrow(notFound);
|
||||
when(ec2Service.describeInstances("us-east-1", List.of("i-alive"), null))
|
||||
.thenReturn(List.of(reservation(runningEc2Instance("i-alive"))));
|
||||
// Ec2Service terminates a batch in order and stops at the first id it has no record of.
|
||||
when(ec2Service.terminateInstances("us-east-1", List.of("i-gone", "i-alive"))).thenThrow(notFound);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
verify(ec2Service).terminateInstances("us-east-1", List.of("i-alive"));
|
||||
assertEquals(0, asg.getInstances().size());
|
||||
verify(asgService).recordActivity(
|
||||
eq("us-east-1"),
|
||||
eq("app-asg"),
|
||||
eq("Terminating EC2 instance(s) for refresh: [i-alive]"),
|
||||
eq("An instance refresh requested replacement of active instances."),
|
||||
eq("Successful"));
|
||||
verify(asgService).recordActivity(
|
||||
eq("us-east-1"),
|
||||
eq("app-asg"),
|
||||
eq("Removing stale EC2 instance reference(s): [i-gone]"),
|
||||
anyString(),
|
||||
eq("Successful"));
|
||||
verify(asgService, never()).recordActivity(anyString(), anyString(), anyString(), anyString(), eq("Failed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminatingInstanceWithMissingEc2RecordIsPrunedAsStale() {
|
||||
AutoScalingService asgService = scalingService();
|
||||
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The standby round trip a client stopping a node's traffic makes, over the Query API: lower MinSize,
|
||||
* EnterStandby with ShouldDecrementDesiredCapacity, wait for Standby, later ExitStandby and wait for
|
||||
* InService. On the way the instance leaves and rejoins the group's target group and Classic load balancer,
|
||||
* and the group launches no replacement for it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AutoScalingStandbyIntegrationTest {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=616161616161/20261028/us-east-1/autoscaling/aws4_request";
|
||||
private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/");
|
||||
private static final String ELB_AUTH = AUTH.replace("/autoscaling/", "/elasticloadbalancing/");
|
||||
private static final String GROUP_PATH = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
|
||||
+ ".AutoScalingGroups.member";
|
||||
private static final String ENTERED = "EnterStandbyResponse.EnterStandbyResult.Activities.member";
|
||||
private static final String EXITED = "ExitStandbyResponse.ExitStandbyResult.Activities.member";
|
||||
|
||||
@Inject
|
||||
AutoScalingReconciler reconciler;
|
||||
|
||||
@Test
|
||||
void anInstanceLeavesServiceForStandbyAndComesBack() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String name = "standby-" + suffix;
|
||||
String loadBalancer = "sb-" + suffix;
|
||||
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);
|
||||
String targetGroup = given().header("Authorization", ELB_AUTH).formParam("Action", "CreateTargetGroup")
|
||||
.formParam("Version", "2015-12-01").formParam("Name", loadBalancer)
|
||||
.formParam("Protocol", "HTTP").formParam("Port", "80").formParam("VpcId", "vpc-00000001")
|
||||
.formParam("TargetType", "instance")
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
given().header("Authorization", ELB_AUTH).formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Version", "2012-06-01").formParam("LoadBalancerName", loadBalancer)
|
||||
.formParam("Listeners.member.1.Protocol", "TCP")
|
||||
.formParam("Listeners.member.1.LoadBalancerPort", "80")
|
||||
.formParam("Listeners.member.1.InstancePort", "80")
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", name)
|
||||
.formParam("LaunchTemplate.LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplate.Version", "1")
|
||||
.formParam("MinSize", "2").formParam("MaxSize", "2").formParam("DesiredCapacity", "2")
|
||||
.formParam("AvailabilityZones.member.1", "us-east-1a")
|
||||
.formParam("TargetGroupARNs.member.1", targetGroup)
|
||||
.formParam("LoadBalancerNames.member.1", loadBalancer)
|
||||
.post("/").then().statusCode(200);
|
||||
try {
|
||||
reconciler.reconcileAll();
|
||||
reconciler.reconcileAll();
|
||||
XmlPath launched = group(name);
|
||||
assertEquals(List.of("InService", "InService"), launched.getList(GROUP_PATH + ".Instances.member.LifecycleState"));
|
||||
List<String> members = launched.getList(GROUP_PATH + ".Instances.member.InstanceId");
|
||||
String standby = members.get(0);
|
||||
String serving = members.get(1);
|
||||
assertEquals(List.copyOf(members).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
|
||||
|
||||
// MinSize 2 leaves no room to decrement, so the client lowers it first.
|
||||
XmlPath refused = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
|
||||
.formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", standby)
|
||||
.formParam("ShouldDecrementDesiredCapacity", "true")
|
||||
.post("/").then().statusCode(400).extract().xmlPath();
|
||||
assertEquals("ValidationError", refused.getString("ErrorResponse.Error.Code"));
|
||||
assertEquals("AutoScalingGroup " + name + " has min-size=2, max-size=2, and desired-size=2. To place"
|
||||
+ " into standby 1 instances, please update the AutoScalingGroup sizes appropriately.",
|
||||
refused.getString("ErrorResponse.Error.Message"));
|
||||
given().header("Authorization", AUTH).formParam("Action", "UpdateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", name).formParam("MinSize", "0")
|
||||
.post("/").then().statusCode(200);
|
||||
|
||||
XmlPath entered = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
|
||||
.formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", standby)
|
||||
.formParam("ShouldDecrementDesiredCapacity", "true")
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
String enterActivity = entered.getString(ENTERED + ".ActivityId");
|
||||
assertAll(
|
||||
() -> assertEquals(name, entered.getString(ENTERED + ".AutoScalingGroupName")),
|
||||
() -> assertEquals("Moving EC2 instance to Standby: " + standby,
|
||||
entered.getString(ENTERED + ".Description")),
|
||||
() -> assertTrue(entered.getString(ENTERED + ".Cause").endsWith(" instance " + standby
|
||||
+ " was moved to standby in response to a user request, shrinking the capacity"
|
||||
+ " from 2 to 1.")),
|
||||
() -> assertEquals("InProgress", entered.getString(ENTERED + ".StatusCode")),
|
||||
() -> assertEquals("50", entered.getString(ENTERED + ".Progress")));
|
||||
|
||||
reconciler.reconcileAll();
|
||||
assertEquals("Standby", given().header("Authorization", AUTH)
|
||||
.formParam("Action", "DescribeAutoScalingInstances").formParam("InstanceIds.member.1", standby)
|
||||
.post("/").then().statusCode(200).extract().xmlPath().getString(
|
||||
"DescribeAutoScalingInstancesResponse.DescribeAutoScalingInstancesResult"
|
||||
+ ".AutoScalingInstances.member.LifecycleState"));
|
||||
XmlPath inStandby = group(name);
|
||||
assertEquals("1", inStandby.getString(GROUP_PATH + ".DesiredCapacity"));
|
||||
assertEquals("Standby", member(inStandby, standby, "LifecycleState"));
|
||||
assertEquals("InService", member(inStandby, serving, "LifecycleState"));
|
||||
assertEquals(List.of(serving), targets(targetGroup));
|
||||
assertEquals(List.of(serving), classicInstances(loadBalancer));
|
||||
assertEquals("Successful", activity(name, enterActivity, "StatusCode"));
|
||||
assertEquals("The instance " + serving + " is not in Standby.", given().header("Authorization", AUTH)
|
||||
.formParam("Action", "ExitStandby")
|
||||
.formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", serving)
|
||||
.post("/").then().statusCode(400).extract().xmlPath().getString("ErrorResponse.Error.Message"));
|
||||
|
||||
reconciler.reconcileAll();
|
||||
assertEquals(2, group(name).getList(GROUP_PATH + ".Instances.member.InstanceId").size(),
|
||||
"The group launches no replacement for an instance whose capacity it gave up");
|
||||
|
||||
XmlPath exited = given().header("Authorization", AUTH).formParam("Action", "ExitStandby")
|
||||
.formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", standby)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
String exitActivity = exited.getString(EXITED + ".ActivityId");
|
||||
assertAll(
|
||||
() -> assertEquals("Moving EC2 instance out of Standby: " + standby,
|
||||
exited.getString(EXITED + ".Description")),
|
||||
() -> assertTrue(exited.getString(EXITED + ".Cause").endsWith(" instance " + standby
|
||||
+ " was moved out of standby in response to a user request, increasing the capacity"
|
||||
+ " from 1 to 2.")),
|
||||
() -> assertEquals("PreInService", exited.getString(EXITED + ".StatusCode")),
|
||||
() -> assertEquals("30", exited.getString(EXITED + ".Progress")));
|
||||
|
||||
reconciler.reconcileAll();
|
||||
XmlPath back = group(name);
|
||||
assertEquals("2", back.getString(GROUP_PATH + ".DesiredCapacity"));
|
||||
assertEquals(List.of("InService", "InService"), back.getList(GROUP_PATH + ".Instances.member.LifecycleState"));
|
||||
assertEquals(List.of(serving, standby).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
|
||||
assertEquals(List.of(serving, standby).stream().sorted().toList(),
|
||||
classicInstances(loadBalancer).stream().sorted().toList());
|
||||
assertEquals("Successful", activity(name, exitActivity, "StatusCode"));
|
||||
} finally {
|
||||
given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", name).formParam("ForceDelete", "true").post("/");
|
||||
given().header("Authorization", EC2_AUTH).formParam("Action", "DeleteLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name).post("/");
|
||||
given().header("Authorization", ELB_AUTH).formParam("Action", "DeleteLoadBalancer")
|
||||
.formParam("Version", "2012-06-01").formParam("LoadBalancerName", loadBalancer).post("/");
|
||||
given().header("Authorization", ELB_AUTH).formParam("Action", "DeleteTargetGroup")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", targetGroup).post("/");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorsUseTheQueryErrorShape() {
|
||||
XmlPath missing = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
|
||||
.formParam("AutoScalingGroupName", "no-such-standby-group")
|
||||
.formParam("InstanceIds.member.1", "i-0123456789abcdef0")
|
||||
.formParam("ShouldDecrementDesiredCapacity", "false")
|
||||
.post("/").then().statusCode(400).extract().xmlPath();
|
||||
assertEquals("ValidationError", missing.getString("ErrorResponse.Error.Code"));
|
||||
assertEquals("Sender", missing.getString("ErrorResponse.Error.Type"));
|
||||
|
||||
XmlPath noDecrement = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
|
||||
.formParam("AutoScalingGroupName", "no-such-standby-group")
|
||||
.post("/").then().statusCode(400).extract().xmlPath();
|
||||
assertEquals("1 validation error detected: Value null at 'shouldDecrementDesiredCapacity' failed to"
|
||||
+ " satisfy constraint: Member must not be null", noDecrement.getString("ErrorResponse.Error.Message"));
|
||||
}
|
||||
|
||||
private static XmlPath group(String name) {
|
||||
return given().header("Authorization", AUTH).formParam("Action", "DescribeAutoScalingGroups")
|
||||
.formParam("AutoScalingGroupNames.member.1", name)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static String member(XmlPath group, String instanceId, String field) {
|
||||
return group.getString(GROUP_PATH + ".Instances.member.find { it.InstanceId == '" + instanceId + "' }."
|
||||
+ field);
|
||||
}
|
||||
|
||||
private static List<String> targets(String targetGroup) {
|
||||
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeTargetHealth")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", targetGroup)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getList("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions"
|
||||
+ ".member.Target.Id", String.class);
|
||||
}
|
||||
|
||||
private static List<String> classicInstances(String loadBalancer) {
|
||||
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeLoadBalancers")
|
||||
.formParam("Version", "2012-06-01").formParam("LoadBalancerNames.member.1", loadBalancer)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getList("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancerDescriptions"
|
||||
+ ".member.Instances.member.InstanceId", String.class);
|
||||
}
|
||||
|
||||
private static String activity(String group, String activityId, String field) {
|
||||
return given().header("Authorization", AUTH).formParam("Action", "DescribeScalingActivities")
|
||||
.formParam("AutoScalingGroupName", group)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("DescribeScalingActivitiesResponse.DescribeScalingActivitiesResult.Activities.member"
|
||||
+ ".find { it.ActivityId == '" + activityId + "' }." + field);
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.elb.ElbClassicService;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.testing.StorageFactories;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* A move into or out of standby that a restart interrupts finishes after the restart: the member's
|
||||
* transient lifecycle state and the activity it completes are both stored, and a group stored before
|
||||
* standby existed loads and enters standby unchanged.
|
||||
*/
|
||||
class AutoScalingStandbyStorageTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String GROUP = "stored-standby";
|
||||
private static final String ACTIVITIES =
|
||||
"DescribeScalingActivitiesResponse.DescribeScalingActivitiesResult.Activities.member";
|
||||
@TempDir Path directory;
|
||||
private final List<StorageFactory> factories = new ArrayList<>();
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void movesInterruptedByARestartFinishAfterIt(String mode) throws IOException {
|
||||
AutoScalingService service = storedService(mode);
|
||||
storeGroup(service);
|
||||
String entered = ok(handler(service).handle("EnterStandby", request(true), REGION))
|
||||
.getString("EnterStandbyResponse.EnterStandbyResult.Activities.member.ActivityId");
|
||||
|
||||
service = restart(mode);
|
||||
assertEquals("EnteringStandby", lifecycle(service, "i-a"));
|
||||
assertEquals("InProgress", activity(service, entered, "StatusCode"));
|
||||
reconcile(service, Set.of());
|
||||
assertEquals("Standby", lifecycle(service, "i-a"));
|
||||
assertEquals("Successful", activity(service, entered, "StatusCode"));
|
||||
assertEquals(1, group(service).getDesiredCapacity());
|
||||
|
||||
String exited = ok(handler(service).handle("ExitStandby", request(null), REGION))
|
||||
.getString("ExitStandbyResponse.ExitStandbyResult.Activities.member.ActivityId");
|
||||
service = restart(mode);
|
||||
assertEquals("Pending", lifecycle(service, "i-a"));
|
||||
reconcile(service, Set.of());
|
||||
|
||||
assertEquals("InService", lifecycle(service, "i-a"));
|
||||
assertEquals("Successful", activity(service, exited, "StatusCode"));
|
||||
assertTrue(activities(service).getList(ACTIVITIES + ".Description", String.class).stream()
|
||||
.noneMatch(description -> description.startsWith("Launching a new EC2 instance")),
|
||||
"The restored member is recognised as returning from standby, not as a launch");
|
||||
assertEquals(2, group(service).getDesiredCapacity());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void aReturnThatFailsTheHealthCheckAfterARestartIsStillReplaced(String mode) throws IOException {
|
||||
AutoScalingService service = storedService(mode);
|
||||
storeGroup(service);
|
||||
ok(handler(service).handle("EnterStandby", request(true), REGION));
|
||||
reconcile(service, Set.of());
|
||||
assertEquals("Standby", lifecycle(service, "i-a"));
|
||||
String exited = ok(handler(service).handle("ExitStandby", request(null), REGION))
|
||||
.getString("ExitStandbyResponse.ExitStandbyResult.Activities.member.ActivityId");
|
||||
|
||||
service = restart(mode);
|
||||
Ec2Service ec2 = reconcile(service, Set.of("i-a"));
|
||||
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-a"));
|
||||
assertEquals(List.of("i-b"), memberIds(service));
|
||||
assertEquals("Cancelled", activity(service, exited, "StatusCode"));
|
||||
assertEquals("Successful", activities(service).getString(ACTIVITIES
|
||||
+ ".find { it.Description == 'Terminating EC2 instance: i-a' }.StatusCode"));
|
||||
service = restart(mode);
|
||||
assertEquals(List.of("i-b"), memberIds(service));
|
||||
}
|
||||
|
||||
private AutoScalingService restart(String mode) {
|
||||
factories.removeFirst().shutdownAll();
|
||||
String snapshot = mode.equals("wal") ? "autoscaling-groups-snapshot.json" : "autoscaling-groups.json";
|
||||
assertTrue(Files.exists(directory.resolve(snapshot)), "No real group snapshot was written");
|
||||
return storedService(mode);
|
||||
}
|
||||
|
||||
/** One reconcile pass in which EC2 reports every instance running, except {@code stopped}. */
|
||||
private Ec2Service reconcile(AutoScalingService service, Set<String> stopped) {
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
when(ec2.isInstanceContainerRunning(anyString())).thenAnswer(invocation ->
|
||||
!stopped.contains(invocation.<String>getArgument(0)));
|
||||
when(ec2.describeInstances(eq(REGION), anyList(), isNull())).thenAnswer(invocation -> {
|
||||
List<Instance> found = new ArrayList<>();
|
||||
for (String id : invocation.<List<String>>getArgument(1)) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(id);
|
||||
instance.setState(stopped.contains(id) ? InstanceState.stopped() : InstanceState.running());
|
||||
found.add(instance);
|
||||
}
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(found);
|
||||
return List.of(reservation);
|
||||
});
|
||||
service.ec2Service = ec2;
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(service, ec2, mock(ElbV2Service.class),
|
||||
mock(ElbClassicService.class), null);
|
||||
reconciler.reconcile(group(service));
|
||||
return ec2;
|
||||
}
|
||||
|
||||
/** A group with two InService members, as stored before standby existed: no standbyActivityId field. */
|
||||
private static void storeGroup(AutoScalingService service) throws IOException {
|
||||
String json = "{\"autoScalingGroupName\":\"" + GROUP + "\",\"region\":\"us-east-1\","
|
||||
+ "\"minSize\":0,\"maxSize\":2,\"desiredCapacity\":2,\"availabilityZones\":[\"us-east-1a\"],"
|
||||
+ "\"instances\":["
|
||||
+ "{\"instanceId\":\"i-a\",\"availabilityZone\":\"us-east-1a\",\"lifecycleState\":\"InService\","
|
||||
+ "\"healthStatus\":\"Healthy\"},"
|
||||
+ "{\"instanceId\":\"i-b\",\"availabilityZone\":\"us-east-1a\",\"lifecycleState\":\"InService\","
|
||||
+ "\"healthStatus\":\"Healthy\"}]}";
|
||||
AccountAwareStorageBackend<AutoScalingGroup> store = service.storageFactory.create("autoscaling",
|
||||
"autoscaling-groups.json", new TypeReference<Map<String, AutoScalingGroup>>() {});
|
||||
store.put(REGION + "::" + GROUP, new ObjectMapper().readValue(json, AutoScalingGroup.class));
|
||||
}
|
||||
|
||||
private static List<String> memberIds(AutoScalingService service) {
|
||||
return group(service).getInstances().stream().map(AsgInstance::getInstanceId).toList();
|
||||
}
|
||||
|
||||
private static MultivaluedHashMap<String, String> request(Boolean decrement) {
|
||||
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("AutoScalingGroupName", GROUP);
|
||||
params.add("InstanceIds.member.1", "i-a");
|
||||
if (decrement != null) {
|
||||
params.add("ShouldDecrementDesiredCapacity", decrement.toString());
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
private static AutoScalingQueryHandler handler(AutoScalingService service) {
|
||||
return new AutoScalingQueryHandler(service);
|
||||
}
|
||||
|
||||
private static XmlPath ok(Response response) {
|
||||
assertEquals(200, response.getStatus(), (String) response.getEntity());
|
||||
return new XmlPath((String) response.getEntity());
|
||||
}
|
||||
|
||||
private static XmlPath activities(AutoScalingService service) {
|
||||
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("AutoScalingGroupName", GROUP);
|
||||
return ok(handler(service).handle("DescribeScalingActivities", params, REGION));
|
||||
}
|
||||
|
||||
private static String activity(AutoScalingService service, String activityId, String field) {
|
||||
return activities(service).getString(ACTIVITIES + ".find { it.ActivityId == '" + activityId + "' }." + field);
|
||||
}
|
||||
|
||||
private static AutoScalingGroup group(AutoScalingService service) {
|
||||
return service.describeAutoScalingGroups(REGION, List.of(GROUP)).getFirst();
|
||||
}
|
||||
|
||||
private static String lifecycle(AutoScalingService service, String instanceId) {
|
||||
return group(service).getInstances().stream()
|
||||
.filter(member -> instanceId.equals(member.getInstanceId()))
|
||||
.map(AsgInstance::getLifecycleState)
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private AutoScalingService storedService(String mode) {
|
||||
StorageFactory factory = StorageFactories.open(directory, mode, ACCOUNT);
|
||||
factories.add(factory);
|
||||
AutoScalingService service = new AutoScalingService();
|
||||
service.regionResolver = new RegionResolver(REGION, ACCOUNT);
|
||||
service.storageFactory = factory;
|
||||
service.initializeStorage();
|
||||
return service;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeStorage() {
|
||||
factories.forEach(StorageFactory::shutdownAll);
|
||||
}
|
||||
}
|
||||
+713
@@ -0,0 +1,713 @@
|
||||
package io.github.hectorvent.floci.services.autoscaling;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
|
||||
import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.elb.ElbClassicService;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Duration;
|
||||
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.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* EnterStandby and ExitStandby as the EC2 Auto Scaling user guide describes them: an InService instance
|
||||
* leaves its group's load balancers and waits in Standby, outside the group's capacity, until it is put
|
||||
* back in service; one activity per instance records each move. Driven through the Query handler and a
|
||||
* real service and reconciler, with EC2 and both load balancer services mocked.
|
||||
*/
|
||||
class AutoScalingStandbyTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String GROUP = "standby-group";
|
||||
private static final String TARGET_GROUP =
|
||||
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/standby/0123456789abcdef";
|
||||
private static final String CLASSIC = "standby-classic";
|
||||
private static final String ENTERED = "EnterStandbyResponse.EnterStandbyResult.Activities.member";
|
||||
private static final String EXITED = "ExitStandbyResponse.ExitStandbyResult.Activities.member";
|
||||
private static final String ACTIVITIES =
|
||||
"DescribeScalingActivitiesResponse.DescribeScalingActivitiesResult.Activities.member";
|
||||
private static final String CAUSE_TIME = "At \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z ";
|
||||
|
||||
private AutoScalingService service;
|
||||
private AutoScalingQueryHandler handler;
|
||||
private AutoScalingReconciler reconciler;
|
||||
private Ec2Service ec2;
|
||||
private ElbV2Service elbV2;
|
||||
private ElbClassicService elbClassic;
|
||||
private final Map<String, InstanceState> ec2States = new LinkedHashMap<>();
|
||||
private final AtomicInteger launches = new AtomicInteger();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AutoScalingService();
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
service.createAutoScalingGroup(REGION, GROUP, null, "lt-standby", null, "1", null,
|
||||
0, 3, 2, 300, List.of("us-east-1a"), List.of(), List.of(TARGET_GROUP), List.of(CLASSIC),
|
||||
"EC2", 0, List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
AutoScalingGroup group = group();
|
||||
group.getInstances().add(member("i-a"));
|
||||
group.getInstances().add(member("i-b"));
|
||||
service.saveAutoScalingGroupIfPresent(group);
|
||||
ec2States.put("i-a", InstanceState.running());
|
||||
ec2States.put("i-b", InstanceState.running());
|
||||
|
||||
ec2 = mock(Ec2Service.class);
|
||||
elbV2 = mock(ElbV2Service.class);
|
||||
elbClassic = mock(ElbClassicService.class);
|
||||
service.ec2Service = ec2;
|
||||
handler = new AutoScalingQueryHandler(service);
|
||||
reconciler = new AutoScalingReconciler(service, ec2, elbV2, elbClassic, null);
|
||||
when(ec2.isInstanceContainerRunning(anyString())).thenAnswer(invocation -> {
|
||||
InstanceState state = ec2States.get(invocation.<String>getArgument(0));
|
||||
return state != null && "running".equals(state.getName());
|
||||
});
|
||||
// As Ec2Service does, an id EC2 has no record of fails the whole call with InvalidInstanceID.NotFound.
|
||||
when(ec2.describeInstances(eq(REGION), anyList(), isNull())).thenAnswer(invocation -> {
|
||||
List<Instance> found = new ArrayList<>();
|
||||
for (String id : invocation.<List<String>>getArgument(1)) {
|
||||
if (!ec2States.containsKey(id)) {
|
||||
throw instanceNotFound(id);
|
||||
}
|
||||
found.add(instance(id, ec2States.get(id)));
|
||||
}
|
||||
return found.isEmpty() ? List.of() : List.of(reservation(found));
|
||||
});
|
||||
// Ec2Service terminates the ids in order and stops at the first it has no record of.
|
||||
when(ec2.terminateInstances(eq(REGION), anyList())).thenAnswer(invocation -> {
|
||||
for (String id : invocation.<List<String>>getArgument(1)) {
|
||||
if (!ec2States.containsKey(id)) {
|
||||
throw instanceNotFound(id);
|
||||
}
|
||||
ec2States.put(id, InstanceState.terminated());
|
||||
}
|
||||
return List.of();
|
||||
});
|
||||
LaunchTemplate template = new LaunchTemplate();
|
||||
template.setLaunchTemplateId("lt-standby");
|
||||
template.setLatestVersionNumber("1");
|
||||
template.getData().setImageId("ami-standby");
|
||||
template.getData().setInstanceType("t3.micro");
|
||||
when(ec2.describeLaunchTemplates(eq(REGION), anyList(), anyList(), anyMap())).thenReturn(List.of(template));
|
||||
when(ec2.describeLaunchTemplateVersions(eq(REGION), eq("lt-standby"), isNull(), anyList()))
|
||||
.thenReturn(List.of(template));
|
||||
when(ec2.runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(), any(),
|
||||
anyList(), any(), any(), any(), isNull(), eq(0), eq(REGION + "a"), isNull(), isNull(), isNull(),
|
||||
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull()))
|
||||
.thenAnswer(invocation -> {
|
||||
String id = "i-replacement-" + launches.incrementAndGet();
|
||||
ec2States.put(id, InstanceState.running());
|
||||
return reservation(List.of(instance(id, InstanceState.running())));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void enterStandbyWithDecrementLeavesTheLoadBalancersAndKeepsTheGroupFromReplacingIt() {
|
||||
Response response = enterStandby(true, "i-a");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
XmlPath entered = xml(response);
|
||||
assertEquals(1, entered.getList(ENTERED + ".ActivityId").size());
|
||||
assertEquals(GROUP, entered.getString(ENTERED + ".AutoScalingGroupName"));
|
||||
assertEquals("Moving EC2 instance to Standby: i-a", entered.getString(ENTERED + ".Description"));
|
||||
assertTrue(entered.getString(ENTERED + ".Cause").matches(CAUSE_TIME
|
||||
+ "instance i-a was moved to standby in response to a user request,"
|
||||
+ " shrinking the capacity from 2 to 1\\."),
|
||||
entered.getString(ENTERED + ".Cause"));
|
||||
assertEquals("InProgress", entered.getString(ENTERED + ".StatusCode"));
|
||||
assertEquals("50", entered.getString(ENTERED + ".Progress"));
|
||||
assertEquals(1, group().getDesiredCapacity());
|
||||
assertEquals("EnteringStandby", lifecycle("i-a"));
|
||||
verify(elbV2, never()).deregisterTargets(anyString(), anyString(), anyList());
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals("InService", lifecycle("i-b"));
|
||||
verify(elbV2).deregisterTargets(eq(REGION), eq(TARGET_GROUP),
|
||||
argThat(targets -> targets.stream().map(TargetDescription::getId).toList().equals(List.of("i-a"))));
|
||||
verify(elbClassic).deregisterInstances(REGION, CLASSIC, List.of("i-a"));
|
||||
verify(elbV2, never()).registerTargets(anyString(), anyString(), anyList());
|
||||
assertNoLaunch();
|
||||
verify(ec2, never()).terminateInstances(anyString(), anyList());
|
||||
XmlPath activities = describeScalingActivities();
|
||||
String activityId = entered.getString(ENTERED + ".ActivityId");
|
||||
assertEquals("Successful", activity(activities, activityId, "StatusCode"));
|
||||
assertEquals("100", activity(activities, activityId, "Progress"));
|
||||
assertFalse(activity(activities, activityId, "EndTime").isEmpty());
|
||||
assertEquals("Moving EC2 instance to Standby: i-a", activity(activities, activityId, "Description"));
|
||||
|
||||
reconciler.reconcile(group());
|
||||
assertEquals(List.of("i-a", "i-b"), memberIds());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals(1, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enterStandbyWithoutDecrementLaunchesAReplacement() {
|
||||
XmlPath entered = ok(enterStandby(false, "i-a"));
|
||||
|
||||
assertTrue(entered.getString(ENTERED + ".Cause").matches(CAUSE_TIME
|
||||
+ "instance i-a was moved to standby in response to a user request\\."),
|
||||
entered.getString(ENTERED + ".Cause"));
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals(List.of("i-a", "i-b", "i-replacement-1"), memberIds());
|
||||
assertEquals("Pending", lifecycle("i-replacement-1"));
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("InService", lifecycle("i-replacement-1"));
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals(1, launches.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exitStandbyGoesThroughPendingAndRegistersWithTheLoadBalancers() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
clearInvocations(elbV2, elbClassic);
|
||||
|
||||
Response response = exitStandby("i-a");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
XmlPath exited = xml(response);
|
||||
assertEquals(1, exited.getList(EXITED + ".ActivityId").size());
|
||||
assertEquals(GROUP, exited.getString(EXITED + ".AutoScalingGroupName"));
|
||||
assertEquals("Moving EC2 instance out of Standby: i-a", exited.getString(EXITED + ".Description"));
|
||||
assertTrue(exited.getString(EXITED + ".Cause").matches(CAUSE_TIME
|
||||
+ "instance i-a was moved out of standby in response to a user request,"
|
||||
+ " increasing the capacity from 1 to 2\\."),
|
||||
exited.getString(EXITED + ".Cause"));
|
||||
assertEquals("PreInService", exited.getString(EXITED + ".StatusCode"));
|
||||
assertEquals("30", exited.getString(EXITED + ".Progress"));
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
assertEquals("Pending", lifecycle("i-a"));
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("InService", lifecycle("i-a"));
|
||||
assertEquals("Healthy", group().getInstances().stream()
|
||||
.filter(member -> "i-a".equals(member.getInstanceId())).findFirst().orElseThrow().getHealthStatus());
|
||||
verify(elbV2).registerTargets(eq(REGION), eq(TARGET_GROUP),
|
||||
argThat(targets -> targets.stream().map(TargetDescription::getId).toList().equals(List.of("i-a"))));
|
||||
verify(elbClassic).registerInstances(REGION, CLASSIC, List.of("i-a"));
|
||||
assertNoLaunch();
|
||||
XmlPath activities = describeScalingActivities();
|
||||
String activityId = exited.getString(EXITED + ".ActivityId");
|
||||
assertEquals("Successful", activity(activities, activityId, "StatusCode"));
|
||||
assertEquals("100", activity(activities, activityId, "Progress"));
|
||||
assertTrue(activities.getList(ACTIVITIES + ".Description", String.class).stream()
|
||||
.noneMatch(description -> description.startsWith("Launching a new EC2 instance")),
|
||||
"A member returning from standby was not launched");
|
||||
assertEquals(List.of("i-a", "i-b"), memberIds());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"stopped", "terminated", "gone"})
|
||||
void standbyMembersAreNotScaledInOrRemovedWhenTheirInstanceStops(String fate) {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
setEc2State("i-a", fate);
|
||||
|
||||
service.setDesiredCapacity(REGION, GROUP, 0);
|
||||
reconciler.reconcile(group());
|
||||
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-b"));
|
||||
verify(ec2, never()).terminateInstances(REGION, List.of("i-a"));
|
||||
assertEquals(List.of("i-a"), memberIds());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals(0, AutoScalingReconciler.activeCapacity(group()));
|
||||
reconciler.reconcile(group());
|
||||
assertEquals(List.of("i-a"), memberIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachInstancesCountsOnlyMembersOutsideStandby() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
|
||||
MultivaluedHashMap<String, String> attach = params(GROUP);
|
||||
attach.add("InstanceIds.member.1", "i-c");
|
||||
assertEquals(200, handler.handle("AttachInstances", attach, REGION).getStatus());
|
||||
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesInstancesOutsideTheGroupOrInTheWrongState() {
|
||||
assertError(enterStandby(true, "i-missing"),
|
||||
"The instance i-missing is not part of Auto Scaling group standby-group.");
|
||||
assertError(enterStandby(true, "i-x", "i-y"),
|
||||
"The instances i-x, i-y are not part of Auto Scaling group standby-group.");
|
||||
assertError(exitStandby("i-a"), "The instance i-a is not in Standby.");
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
|
||||
ok(enterStandby(true, "i-a"));
|
||||
assertError(enterStandby(true, "i-a"), "The instance i-a is not in InService.");
|
||||
assertError(exitStandby("i-a"), "The instance i-a is not in Standby.");
|
||||
assertError(enterStandby(true, "i-b", "i-missing"),
|
||||
"The instance i-missing is not part of Auto Scaling group standby-group.");
|
||||
assertEquals(1, group().getDesiredCapacity());
|
||||
assertEquals("InService", lifecycle("i-b"));
|
||||
|
||||
MultivaluedHashMap<String, String> unknown = params("no-such-group");
|
||||
unknown.add("InstanceIds.member.1", "i-a");
|
||||
unknown.add("ShouldDecrementDesiredCapacity", "true");
|
||||
assertError(handler.handle("EnterStandby", unknown, REGION), "Auto Scaling group 'no-such-group' not found.");
|
||||
assertError(handler.handle("ExitStandby", unknown, REGION), "Auto Scaling group 'no-such-group' not found.");
|
||||
assertEquals(1, xml(describeScalingActivitiesResponse()).getList(ACTIVITIES + ".ActivityId").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesARequestWithoutItsRequiredMembers() {
|
||||
MultivaluedHashMap<String, String> noDecrement = params(GROUP);
|
||||
noDecrement.add("InstanceIds.member.1", "i-a");
|
||||
assertError(handler.handle("EnterStandby", noDecrement, REGION), "1 validation error detected: Value null"
|
||||
+ " at 'shouldDecrementDesiredCapacity' failed to satisfy constraint: Member must not be null");
|
||||
|
||||
MultivaluedHashMap<String, String> nothing = new MultivaluedHashMap<>();
|
||||
nothing.add("InstanceIds.member.1", "i-a");
|
||||
assertError(handler.handle("EnterStandby", nothing, REGION), "2 validation errors detected: Value null"
|
||||
+ " at 'autoScalingGroupName' failed to satisfy constraint: Member must not be null; Value null"
|
||||
+ " at 'shouldDecrementDesiredCapacity' failed to satisfy constraint: Member must not be null");
|
||||
assertError(handler.handle("ExitStandby", nothing, REGION), "1 validation error detected: Value null"
|
||||
+ " at 'autoScalingGroupName' failed to satisfy constraint: Member must not be null");
|
||||
assertEquals("InService", lifecycle("i-a"));
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void desiredCapacityMustStayBetweenMinSizeAndMaxSize() {
|
||||
service.updateAutoScalingGroup(REGION, GROUP, null, null, null, null, null, 2, 2, null, null,
|
||||
null, null, null, null, null, AsgOptionalFields.none());
|
||||
|
||||
assertError(enterStandby(true, "i-a"), "AutoScalingGroup standby-group has min-size=2, max-size=2,"
|
||||
+ " and desired-size=2. To place into standby 1 instances, please update the AutoScalingGroup"
|
||||
+ " sizes appropriately.");
|
||||
assertEquals("InService", lifecycle("i-a"));
|
||||
|
||||
assertEquals(200, enterStandby(false, "i-a").getStatus());
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertError(exitStandby("i-a"), "AutoScalingGroup standby-group has min-size=2, max-size=2,"
|
||||
+ " and desired-size=2. To exit standby 1 instances, please update the AutoScalingGroup"
|
||||
+ " sizes appropriately.");
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enteringTwoInstancesRecordsOneActivityEachAndOneCapacityChange() {
|
||||
XmlPath entered = ok(enterStandby(true, "i-a", "i-b", "i-a"));
|
||||
|
||||
assertEquals(List.of("Moving EC2 instance to Standby: i-a", "Moving EC2 instance to Standby: i-b"),
|
||||
entered.getList(ENTERED + ".Description"));
|
||||
assertTrue(entered.getList(ENTERED + ".Cause", String.class).stream().allMatch(cause ->
|
||||
cause.endsWith("shrinking the capacity from 2 to 0.")), entered.prettify());
|
||||
assertEquals(0, group().getDesiredCapacity());
|
||||
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
assertEquals("Standby", lifecycle("i-b"));
|
||||
verify(elbClassic).deregisterInstances(REGION, CLASSIC, List.of("i-a", "i-b"));
|
||||
|
||||
XmlPath exited = ok(exitStandby("i-b", "i-a"));
|
||||
assertEquals(List.of("Moving EC2 instance out of Standby: i-b", "Moving EC2 instance out of Standby: i-a"),
|
||||
exited.getList(EXITED + ".Description"));
|
||||
assertTrue(exited.getList(EXITED + ".Cause", String.class).stream().allMatch(cause ->
|
||||
cause.endsWith("increasing the capacity from 0 to 2.")), exited.prettify());
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyInstanceListMovesNothing() {
|
||||
MultivaluedHashMap<String, String> enter = params(GROUP);
|
||||
enter.add("ShouldDecrementDesiredCapacity", "true");
|
||||
Response entered = handler.handle("EnterStandby", enter, REGION);
|
||||
assertEquals(200, entered.getStatus());
|
||||
assertTrue(xml(entered).getList(ENTERED + ".ActivityId").isEmpty());
|
||||
|
||||
Response exited = handler.handle("ExitStandby", params(GROUP), REGION);
|
||||
assertEquals(200, exited.getStatus());
|
||||
assertTrue(xml(exited).getList(EXITED + ".ActivityId").isEmpty());
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMoveInterruptedByTerminationIsCancelled() {
|
||||
String activityId = ok(enterStandby(true, "i-a")).getString(ENTERED + ".ActivityId");
|
||||
service.terminateInstanceInAutoScalingGroup(REGION, "i-a", false);
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("Cancelled", activity(describeScalingActivities(), activityId, "StatusCode"));
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-a"));
|
||||
assertFalse(memberIds().contains("i-a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceEc2NoLongerHasIsReplacedWhenItLeavesStandby() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
ec2States.remove("i-a");
|
||||
String activityId = ok(exitStandby("i-a")).getString(EXITED + ".ActivityId");
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
verify(ec2, never()).terminateInstances(eq(REGION), argThat(ids -> ids.contains("i-a")));
|
||||
assertEquals(List.of("i-b", "i-replacement-1"), memberIds());
|
||||
XmlPath activities = describeScalingActivities();
|
||||
assertEquals("Cancelled", activity(activities, activityId, "StatusCode"));
|
||||
assertEquals("Successful", activities.getString(ACTIVITIES
|
||||
+ ".find { it.Description == 'Terminating EC2 instance: i-a' }.StatusCode"), activities.prettify());
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceThatStoppedOrTerminatedInStandbyFailsTheHealthCheckOnItsReturn() {
|
||||
ok(enterStandby(true, "i-a", "i-b"));
|
||||
reconciler.reconcile(group());
|
||||
ec2States.put("i-a", InstanceState.stopped());
|
||||
ec2States.put("i-b", InstanceState.terminated());
|
||||
ok(exitStandby("i-a", "i-b"));
|
||||
assertEquals(2, group().getDesiredCapacity());
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-a"));
|
||||
verify(ec2, never()).terminateInstances(eq(REGION), argThat(ids -> ids.contains("i-b")));
|
||||
assertEquals(List.of("i-replacement-1", "i-replacement-2"), memberIds());
|
||||
XmlPath activities = describeScalingActivities();
|
||||
for (String id : List.of("i-a", "i-b")) {
|
||||
String path = ACTIVITIES + ".find { it.Description == 'Terminating EC2 instance: " + id + "' }";
|
||||
assertEquals("Successful", activities.getString(path + ".StatusCode"), activities.prettify());
|
||||
assertTrue(activities.getString(path + ".Cause").matches(CAUSE_TIME
|
||||
+ "an instance was taken out of service in response to an EC2 health check indicating it"
|
||||
+ " has been terminated or stopped\\."), activities.getString(path + ".Cause"));
|
||||
}
|
||||
assertTrue(activities.getList(ACTIVITIES + ".Description", String.class).stream()
|
||||
.noneMatch(description -> description.startsWith("Removing stale")), activities.prettify());
|
||||
assertEquals(List.of("Cancelled", "Cancelled"), activities.getList(ACTIVITIES
|
||||
+ ".findAll { it.Description.text().startsWith('Moving EC2 instance out of Standby') }.StatusCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returningFromStandbyKeepsTheHealthStatus() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
MultivaluedHashMap<String, String> health = new MultivaluedHashMap<>();
|
||||
health.add("InstanceId", "i-a");
|
||||
health.add("HealthStatus", "Unhealthy");
|
||||
health.add("ShouldRespectGracePeriod", "false");
|
||||
assertEquals(200, handler.handle("SetInstanceHealth", health, REGION).getStatus());
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("Unhealthy", healthOf("i-a"));
|
||||
|
||||
ok(exitStandby("i-a"));
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("InService", lifecycle("i-a"));
|
||||
assertEquals("Unhealthy", healthOf("i-a"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void detachRefusesAnInstanceWhileItsStandbyMoveIsInProgress(boolean entering) {
|
||||
String activityId = ok(enterStandby(true, "i-a")).getString(ENTERED + ".ActivityId");
|
||||
if (!entering) {
|
||||
reconciler.reconcile(group());
|
||||
activityId = ok(exitStandby("i-a")).getString(EXITED + ".ActivityId");
|
||||
}
|
||||
int desired = group().getDesiredCapacity();
|
||||
|
||||
MultivaluedHashMap<String, String> detach = params(GROUP);
|
||||
detach.add("InstanceIds.member.1", "i-b");
|
||||
detach.add("InstanceIds.member.2", "i-a");
|
||||
detach.add("ShouldDecrementDesiredCapacity", "true");
|
||||
assertError(handler.handle("DetachInstances", detach, REGION), "The instance i-a is not in InService or Standby.");
|
||||
|
||||
assertEquals(entering ? "EnteringStandby" : "Pending", lifecycle("i-a"));
|
||||
assertEquals(List.of("i-a", "i-b"), memberIds());
|
||||
assertEquals(desired, group().getDesiredCapacity());
|
||||
assertEquals(entering ? "InProgress" : "PreInService",
|
||||
activity(describeScalingActivities(), activityId, "StatusCode"));
|
||||
verify(ec2, never()).deleteSystemTag(anyString(), anyList(), anyString(), anyString());
|
||||
reconciler.reconcile(group());
|
||||
assertEquals(entering ? "Standby" : "InService", lifecycle("i-a"));
|
||||
assertEquals("Successful", activity(describeScalingActivities(), activityId, "StatusCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedTerminationOfAReturningInstanceIsRetriedOnTheNextPass() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
ec2States.put("i-a", InstanceState.stopped());
|
||||
String activityId = ok(exitStandby("i-a")).getString(EXITED + ".ActivityId");
|
||||
doThrow(new AwsException("RequestLimitExceeded", "Request limit exceeded.", 400))
|
||||
.doReturn(List.of())
|
||||
.when(ec2).terminateInstances(REGION, List.of("i-a"));
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals(List.of("i-a", "i-b"), memberIds());
|
||||
assertEquals("Pending", lifecycle("i-a"));
|
||||
XmlPath refused = describeScalingActivities();
|
||||
assertEquals("PreInService", activity(refused, activityId, "StatusCode"));
|
||||
assertTrue(refused.getList(ACTIVITIES + ".Description", String.class).stream()
|
||||
.noneMatch(description -> description.startsWith("Terminating EC2 instance")), refused.prettify());
|
||||
assertNoLaunch();
|
||||
|
||||
reconciler.reconcile(group());
|
||||
|
||||
verify(ec2, times(2)).terminateInstances(REGION, List.of("i-a"));
|
||||
assertEquals(List.of("i-b", "i-replacement-1"), memberIds());
|
||||
XmlPath retried = describeScalingActivities();
|
||||
assertEquals("Cancelled", activity(retried, activityId, "StatusCode"));
|
||||
assertEquals("Successful", retried.getString(ACTIVITIES
|
||||
+ ".find { it.Description == 'Terminating EC2 instance: i-a' }.StatusCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceRefreshCancelsTheMoveOfAnInstanceOnItsWayBack() {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
reconciler.reconcile(group());
|
||||
String activityId = ok(exitStandby("i-a")).getString(EXITED + ".ActivityId");
|
||||
|
||||
assertEquals(200, handler.handle("StartInstanceRefresh", params(GROUP), REGION).getStatus());
|
||||
assertEquals("Terminating", lifecycle("i-a"));
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("Cancelled", activity(describeScalingActivities(), activityId, "StatusCode"));
|
||||
verify(ec2).terminateInstances(REGION, List.of("i-a", "i-b"));
|
||||
assertFalse(memberIds().contains("i-a"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"SetDesiredCapacity", "UpdateAutoScalingGroup"})
|
||||
void capacityChangesWaitForTheGroupLock(String action) throws Exception {
|
||||
CountDownLatch held = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Thread> changer = new AtomicReference<>();
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> holder = workers.submit(() -> service.reconcileIfPresent(group(), () -> {
|
||||
held.countDown();
|
||||
try {
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}));
|
||||
assertTrue(held.await(5, TimeUnit.SECONDS));
|
||||
MultivaluedHashMap<String, String> change = params(GROUP);
|
||||
change.add("SetDesiredCapacity".equals(action) ? "DesiredCapacity" : "MaxSize", "3");
|
||||
Future<Response> changing = workers.submit(() -> {
|
||||
changer.set(Thread.currentThread());
|
||||
return handler.handle(action, change, REGION);
|
||||
});
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> changing.isDone()
|
||||
|| changer.get() != null && changer.get().getState() == Thread.State.BLOCKED);
|
||||
assertFalse(changing.isDone(), action + " must wait for a standby move or reconcile pass in progress");
|
||||
release.countDown();
|
||||
assertEquals(200, changing.get(5, TimeUnit.SECONDS).getStatus());
|
||||
holder.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
workers.shutdownNow();
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theResponseShowsEachMoveAsItStarted() {
|
||||
List<ScalingActivity> started = service.enterStandby(REGION, GROUP, List.of("i-a"), true);
|
||||
reconciler.reconcile(group());
|
||||
|
||||
assertEquals("Successful",
|
||||
activity(describeScalingActivities(), started.getFirst().getActivityId(), "StatusCode"));
|
||||
assertEquals("InProgress", started.getFirst().getStatusCode());
|
||||
assertEquals(50, started.getFirst().getProgress());
|
||||
assertNull(started.getFirst().getEndTime());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void anInstanceRefreshLeavesStandbyMembersAlone(boolean settled) {
|
||||
ok(enterStandby(true, "i-a"));
|
||||
if (settled) {
|
||||
reconciler.reconcile(group());
|
||||
}
|
||||
|
||||
MultivaluedHashMap<String, String> refresh = params(GROUP);
|
||||
assertEquals(200, handler.handle("StartInstanceRefresh", refresh, REGION).getStatus());
|
||||
|
||||
assertEquals(settled ? "Standby" : "EnteringStandby", lifecycle("i-a"));
|
||||
assertEquals("Terminating", lifecycle("i-b"));
|
||||
reconciler.reconcile(group());
|
||||
assertEquals("Standby", lifecycle("i-a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingTheGroupCancelsItsMoves() {
|
||||
String activityId = ok(enterStandby(true, "i-a")).getString(ENTERED + ".ActivityId");
|
||||
|
||||
service.deleteAutoScalingGroup(REGION, GROUP, true);
|
||||
|
||||
assertEquals("Cancelled", activity(describeScalingActivities(), activityId, "StatusCode"));
|
||||
}
|
||||
|
||||
private Response enterStandby(boolean decrement, String... instanceIds) {
|
||||
MultivaluedHashMap<String, String> params = params(GROUP);
|
||||
for (int index = 0; index < instanceIds.length; index++) {
|
||||
params.add("InstanceIds.member." + (index + 1), instanceIds[index]);
|
||||
}
|
||||
params.add("ShouldDecrementDesiredCapacity", String.valueOf(decrement));
|
||||
return handler.handle("EnterStandby", params, REGION);
|
||||
}
|
||||
|
||||
private Response exitStandby(String... instanceIds) {
|
||||
MultivaluedHashMap<String, String> params = params(GROUP);
|
||||
for (int index = 0; index < instanceIds.length; index++) {
|
||||
params.add("InstanceIds.member." + (index + 1), instanceIds[index]);
|
||||
}
|
||||
return handler.handle("ExitStandby", params, REGION);
|
||||
}
|
||||
|
||||
private Response describeScalingActivitiesResponse() {
|
||||
return handler.handle("DescribeScalingActivities", params(GROUP), REGION);
|
||||
}
|
||||
|
||||
private XmlPath describeScalingActivities() {
|
||||
return xml(describeScalingActivitiesResponse());
|
||||
}
|
||||
|
||||
private static MultivaluedHashMap<String, String> params(String group) {
|
||||
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.add("AutoScalingGroupName", group);
|
||||
return params;
|
||||
}
|
||||
|
||||
private static XmlPath ok(Response response) {
|
||||
assertEquals(200, response.getStatus(), (String) response.getEntity());
|
||||
return xml(response);
|
||||
}
|
||||
|
||||
private static XmlPath xml(Response response) {
|
||||
return new XmlPath((String) response.getEntity());
|
||||
}
|
||||
|
||||
private static void assertError(Response response, String message) {
|
||||
assertEquals(400, response.getStatus(), (String) response.getEntity());
|
||||
XmlPath error = xml(response);
|
||||
assertEquals("ValidationError", error.getString("ErrorResponse.Error.Code"));
|
||||
assertEquals(message, error.getString("ErrorResponse.Error.Message"));
|
||||
}
|
||||
|
||||
private static String activity(XmlPath activities, String activityId, String field) {
|
||||
return activities.getString(ACTIVITIES + ".find { it.ActivityId == '" + activityId + "' }." + field);
|
||||
}
|
||||
|
||||
private static String activityFor(XmlPath response, String path, String instanceId) {
|
||||
return response.getString(path + ".find { it.Description.text().endsWith(': " + instanceId + "') }.ActivityId");
|
||||
}
|
||||
|
||||
private AutoScalingGroup group() {
|
||||
return service.describeAutoScalingGroups(REGION, List.of(GROUP)).getFirst();
|
||||
}
|
||||
|
||||
private List<String> memberIds() {
|
||||
return group().getInstances().stream().map(AsgInstance::getInstanceId).toList();
|
||||
}
|
||||
|
||||
private String healthOf(String instanceId) {
|
||||
return group().getInstances().stream()
|
||||
.filter(member -> instanceId.equals(member.getInstanceId()))
|
||||
.map(AsgInstance::getHealthStatus)
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/** Sets what EC2 reports for an instance: a state name, or {@code gone} for no instance at all. */
|
||||
private void setEc2State(String instanceId, String fate) {
|
||||
switch (fate) {
|
||||
case "stopped" -> ec2States.put(instanceId, InstanceState.stopped());
|
||||
case "terminated" -> ec2States.put(instanceId, InstanceState.terminated());
|
||||
case "gone" -> ec2States.remove(instanceId);
|
||||
default -> throw new IllegalArgumentException(fate);
|
||||
}
|
||||
}
|
||||
|
||||
private String lifecycle(String instanceId) {
|
||||
return group().getInstances().stream()
|
||||
.filter(member -> instanceId.equals(member.getInstanceId()))
|
||||
.map(AsgInstance::getLifecycleState)
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private void assertNoLaunch() {
|
||||
verify(ec2, never()).runInstances(eq(REGION), any(), any(), anyInt(), anyInt(), any(), anyList(), any(),
|
||||
any(), anyList(), any(), any(), any(), isNull(), eq(0), eq(REGION + "a"), isNull(), isNull(), isNull(),
|
||||
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
|
||||
}
|
||||
|
||||
private static AsgInstance member(String id) {
|
||||
AsgInstance member = new AsgInstance();
|
||||
member.setInstanceId(id);
|
||||
member.setAvailabilityZone("us-east-1a");
|
||||
member.setLifecycleState("InService");
|
||||
member.setHealthStatus("Healthy");
|
||||
member.setLaunchTemplateId("lt-standby");
|
||||
member.setLaunchTemplateVersion("1");
|
||||
return member;
|
||||
}
|
||||
|
||||
private static Instance instance(String id, InstanceState state) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(id);
|
||||
instance.setState(state);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static AwsException instanceNotFound(String instanceId) {
|
||||
return new AwsException("InvalidInstanceID.NotFound",
|
||||
"The instance ID '" + instanceId + "' does not exist", 400);
|
||||
}
|
||||
|
||||
private static Reservation reservation(List<Instance> instances) {
|
||||
Reservation reservation = new Reservation();
|
||||
reservation.setInstances(instances);
|
||||
return reservation;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user