fix(autoscaling): round-trip InstanceMaintenancePolicy, AvailabilityZoneDistribution, CapacityReservationSpecification, ServiceLinkedRoleARN, WeightedCapacity and EnabledMetrics (#5513)

* fix(autoscaling): round-trip InstanceMaintenancePolicy, AvailabilityZoneDistribution, CapacityReservationSpecification, ServiceLinkedRoleARN, WeightedCapacity and EnabledMetrics

DescribeAutoScalingGroups dropped several members of the AutoScalingGroup shape
that CreateAutoScalingGroup and UpdateAutoScalingGroup accept, so a client that
set them read them back as absent and saw a permanent diff.

- AsgOptionalFields gains ServiceLinkedRoleARN, InstanceMaintenancePolicy,
  AvailabilityZoneDistribution and CapacityReservationSpecification with its
  CapacityReservationTarget. The four-argument constructor stays, so existing
  call sites are unchanged.
- MixedInstancesPolicy launch template overrides carry WeightedCapacity.
- EnableMetricsCollection and DisableMetricsCollection are implemented, and
  DescribeAutoScalingGroups reports EnabledMetrics.
- Validation follows the botocore model. MinHealthyPercentage 0 to 100 and
  MaxHealthyPercentage 100 to 200, both required, at most 100 apart, and -1
  on both clears the policy. CapacityDistributionStrategy and
  CapacityReservationPreference enums. No target with preference none.
  CapacityReservationIds 1 to 255 characters matching [A-Za-z0-9-_/] and
  resource group ARNs 1 to 1600. ServiceLinkedRoleARN 1 to 1600 characters.
  WeightedCapacity 1 to 999 in at most 32 characters, set on every override
  or none. Granularity required and 1Minute. Known metric names only.
- The AWS::AutoScaling::AutoScalingGroup provisioner passes the new properties
  and MetricsCollection through, and its update rollback snapshot restores
  them. It requires CapacityReservationPreference and each entry's
  Granularity as the resource schema does, and rejects an unknown metric
  before creating the group.
- The Java SDK compatibility suite gains a round-trip case that sets every
  new member, reads it back through DescribeAutoScalingGroups, then clears
  the maintenance policy and the enabled metrics.

* fix(autoscaling): route the metrics collection actions and close the review gaps

EnableMetricsCollection and DisableMetricsCollection now route to Auto
Scaling when a request carries no credential scope. Both hold the group
lock, so concurrent calls keep each other's changes and a call racing a
delete cannot write the group back.

A failed stack update now clears the service-linked role, AZ
distribution and capacity reservation when the group had none before.
A blank ServiceLinkedRoleARN or WeightedCapacity in a template reaches
the service's validation instead of reading as unset. The provisioner
reuses the service's granularity rule and message.
This commit is contained in:
lex00 authored and GitHub committed 2026-10-12 16:26:44 -04:00
1 parent d21f5f6a05
commit 991bf3ab9e
17 files changed
+1635 -19

No files matched your search

@@ -0,0 +1,400 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* Wire-level coverage for the AutoScalingGroup members that DescribeAutoScalingGroups used to drop:
* ServiceLinkedRoleARN, InstanceMaintenancePolicy, AvailabilityZoneDistribution,
* CapacityReservationSpecification, a mixed instances policy override's WeightedCapacity, and
* EnabledMetrics, which only EnableMetricsCollection and DisableMetricsCollection set.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class AutoScalingGroupOptionalStructuresIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260501/us-east-1/autoscaling/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260501/us-east-1/ec2/aws4_request";
private static final String GROUP = "opt-structures-asg";
private static final String BARE_GROUP = "opt-structures-bare-asg";
private static final String MEMBER =
"DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member.";
private static final String ROLE_ARN =
"arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling_opt";
private static String launchTemplateId;
@Test
@Order(1)
void createRoundTripsEveryOptionalStructure() {
launchTemplateId = given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", "opt-structures-lt")
.formParam("LaunchTemplateData.ImageId", "ami-12345678")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.header("Authorization", EC2_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", GROUP)
.formParam("MinSize", "0")
.formParam("MaxSize", "6")
.formParam("DesiredCapacity", "0")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId",
launchTemplateId)
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "t3.micro")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.WeightedCapacity", "2")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.2.InstanceType", "t3.small")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.2.WeightedCapacity", "4")
.formParam("ServiceLinkedRoleARN", ROLE_ARN)
.formParam("InstanceMaintenancePolicy.MinHealthyPercentage", "100")
.formParam("InstanceMaintenancePolicy.MaxHealthyPercentage", "110")
.formParam("AvailabilityZoneDistribution.CapacityDistributionStrategy", "balanced-only")
.formParam("CapacityReservationSpecification.CapacityReservationPreference",
"capacity-reservations-only")
.formParam("CapacityReservationSpecification.CapacityReservationTarget"
+ ".CapacityReservationIds.member.1", "cr-0123456789abcdef0")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(GROUP)
.body(MEMBER + "ServiceLinkedRoleARN", equalTo(ROLE_ARN))
.body(MEMBER + "InstanceMaintenancePolicy.MinHealthyPercentage", equalTo("100"))
.body(MEMBER + "InstanceMaintenancePolicy.MaxHealthyPercentage", equalTo("110"))
.body(MEMBER + "AvailabilityZoneDistribution.CapacityDistributionStrategy",
equalTo("balanced-only"))
.body(MEMBER + "CapacityReservationSpecification.CapacityReservationPreference",
equalTo("capacity-reservations-only"))
.body(MEMBER + "CapacityReservationSpecification.CapacityReservationTarget"
+ ".CapacityReservationIds.member", equalTo("cr-0123456789abcdef0"))
.body(MEMBER + "MixedInstancesPolicy.LaunchTemplate.Overrides.member[0].WeightedCapacity",
equalTo("2"))
.body(MEMBER + "MixedInstancesPolicy.LaunchTemplate.Overrides.member[1].WeightedCapacity",
equalTo("4"));
}
@Test
@Order(2)
void updateOverwritesOnlyTheStructuresTheRequestCarries() {
given()
.formParam("Action", "UpdateAutoScalingGroup")
.formParam("AutoScalingGroupName", GROUP)
.formParam("AvailabilityZoneDistribution.CapacityDistributionStrategy", "balanced-best-effort")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(GROUP)
.body(MEMBER + "AvailabilityZoneDistribution.CapacityDistributionStrategy",
equalTo("balanced-best-effort"))
.body(MEMBER + "ServiceLinkedRoleARN", equalTo(ROLE_ARN))
.body(MEMBER + "InstanceMaintenancePolicy.MinHealthyPercentage", equalTo("100"))
.body(MEMBER + "CapacityReservationSpecification.CapacityReservationPreference",
equalTo("capacity-reservations-only"));
}
@Test
@Order(3)
void instanceMaintenancePolicyMinusOneOnBothClearsIt() {
given()
.formParam("Action", "UpdateAutoScalingGroup")
.formParam("AutoScalingGroupName", GROUP)
.formParam("InstanceMaintenancePolicy.MinHealthyPercentage", "-1")
.formParam("InstanceMaintenancePolicy.MaxHealthyPercentage", "-1")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(GROUP)
.body(not(containsString("<InstanceMaintenancePolicy>")))
.body(MEMBER + "ServiceLinkedRoleARN", equalTo(ROLE_ARN));
}
@Test
@Order(4)
void enableAndDisableMetricsCollectionRoundTripEnabledMetrics() {
given()
.formParam("Action", "EnableMetricsCollection")
.formParam("AutoScalingGroupName", GROUP)
.formParam("Metrics.member.1", "GroupMinSize")
.formParam("Metrics.member.2", "GroupMaxSize")
.formParam("Granularity", "1Minute")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("EnableMetricsCollectionResponse"));
describe(GROUP)
.body(MEMBER + "EnabledMetrics.member[0].Metric", equalTo("GroupMinSize"))
.body(MEMBER + "EnabledMetrics.member[0].Granularity", equalTo("1Minute"))
.body(MEMBER + "EnabledMetrics.member[1].Metric", equalTo("GroupMaxSize"));
given()
.formParam("Action", "DisableMetricsCollection")
.formParam("AutoScalingGroupName", GROUP)
.formParam("Metrics.member.1", "GroupMinSize")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("DisableMetricsCollectionResponse"));
describe(GROUP)
.body(MEMBER + "EnabledMetrics.member.Metric", equalTo("GroupMaxSize"))
.body(not(containsString("<Metric>GroupMinSize</Metric>")));
given()
.formParam("Action", "DisableMetricsCollection")
.formParam("AutoScalingGroupName", GROUP)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(GROUP).body(not(containsString("<EnabledMetrics>")));
}
@Test
@Order(5)
void enableMetricsCollectionWithNoMetricsEnablesAllOfThem() {
given()
.formParam("Action", "EnableMetricsCollection")
.formParam("AutoScalingGroupName", GROUP)
.formParam("Granularity", "1Minute")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(GROUP)
.body(containsString("<Metric>GroupTotalInstances</Metric>"))
.body(containsString("<Metric>GroupAndWarmPoolTotalCapacity</Metric>"));
}
@Test
@Order(6)
void enableMetricsCollectionRejectsAGranularityOtherThanOneMinute() {
given()
.formParam("Action", "EnableMetricsCollection")
.formParam("AutoScalingGroupName", GROUP)
.formParam("Granularity", "5Minute")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("1Minute"));
}
@Test
@Order(7)
void aGroupThatSetsNoneOfThemOmitsThemFromDescribe() {
given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", BARE_GROUP)
.formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId)
.formParam("MinSize", "0")
.formParam("MaxSize", "1")
.formParam("DesiredCapacity", "0")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
describe(BARE_GROUP)
.body(not(containsString("<ServiceLinkedRoleARN>")))
.body(not(containsString("<InstanceMaintenancePolicy>")))
.body(not(containsString("<AvailabilityZoneDistribution>")))
.body(not(containsString("<CapacityReservationSpecification>")))
.body(not(containsString("<EnabledMetrics>")));
}
@Test
@Order(8)
void createRejectsAMaxHealthyPercentageBelowOneHundred() {
rejectedCreate("opt-structures-bad-max",
"InstanceMaintenancePolicy.MinHealthyPercentage", "50",
"InstanceMaintenancePolicy.MaxHealthyPercentage", "90")
.body(containsString("MaxHealthyPercentage"));
}
@Test
@Order(9)
void createRejectsAHealthyPercentageSpreadAboveOneHundred() {
rejectedCreate("opt-structures-wide-spread",
"InstanceMaintenancePolicy.MinHealthyPercentage", "0",
"InstanceMaintenancePolicy.MaxHealthyPercentage", "150")
.body(containsString("cannot be greater than 100"));
}
@Test
@Order(10)
void createRejectsAnInstanceMaintenancePolicyMissingOnePercentage() {
rejectedCreate("opt-structures-half-policy",
"InstanceMaintenancePolicy.MinHealthyPercentage", "90",
"DesiredCapacity", "0")
.body(containsString("Both MinHealthyPercentage and MaxHealthyPercentage"));
}
@Test
@Order(11)
void createRejectsAnUnknownCapacityDistributionStrategy() {
rejectedCreate("opt-structures-bad-strategy",
"AvailabilityZoneDistribution.CapacityDistributionStrategy", "round-robin",
"DesiredCapacity", "0")
.body(containsString("CapacityDistributionStrategy"));
}
@Test
@Order(12)
void createRejectsAnUnknownCapacityReservationPreference() {
rejectedCreate("opt-structures-bad-preference",
"CapacityReservationSpecification.CapacityReservationPreference", "open",
"DesiredCapacity", "0")
.body(containsString("CapacityReservationPreference"));
}
@Test
@Order(13)
void createRejectsAWeightedCapacityOutsideOneTo999() {
given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", "opt-structures-bad-weight")
.formParam("MinSize", "0")
.formParam("MaxSize", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId",
launchTemplateId)
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "t3.micro")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.WeightedCapacity", "1000")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("WeightedCapacity"));
}
@Test
@Order(14)
void createRejectsAWeightedCapacityOnOnlySomeOverrides() {
given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", "opt-structures-partial-weight")
.formParam("MinSize", "0")
.formParam("MaxSize", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId",
launchTemplateId)
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "t3.micro")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.WeightedCapacity", "1")
.formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.2.InstanceType", "t3.small")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"))
.body(containsString("for all of them"));
}
@Test
@Order(15)
void createRejectsACapacityReservationTargetWithPreferenceNone() {
rejectedCreate("opt-structures-none-target",
"CapacityReservationSpecification.CapacityReservationPreference", "none",
"CapacityReservationSpecification.CapacityReservationTarget.CapacityReservationIds.member.1",
"cr-0123456789abcdef0")
.body(containsString("CapacityReservationTarget"));
}
@Test
@Order(16)
void createRejectsACapacityReservationIdOutsideItsPattern() {
rejectedCreate("opt-structures-bad-reservation-id",
"CapacityReservationSpecification.CapacityReservationPreference", "capacity-reservations-only",
"CapacityReservationSpecification.CapacityReservationTarget.CapacityReservationIds.member.1",
"cr 0123")
.body(containsString("capacityReservationIds"));
}
@Test
@Order(17)
void cleanUp() {
for (String name : new String[] {GROUP, BARE_GROUP}) {
given()
.formParam("Action", "DeleteAutoScalingGroup")
.formParam("AutoScalingGroupName", name)
.formParam("ForceDelete", "true")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
}
}
private static ValidatableResponse rejectedCreate(String name, String key1, String value1,
String key2, String value2) {
return given()
.formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name)
.formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId)
.formParam("MinSize", "0")
.formParam("MaxSize", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam(key1, value1)
.formParam(key2, value2)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("ValidationError"));
}
private static ValidatableResponse describe(String name) {
return given()
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -5,6 +5,9 @@ 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.AvailabilityZoneDistribution;
import io.github.hectorvent.floci.services.autoscaling.model.CapacityReservationSpecification;
import io.github.hectorvent.floci.services.autoscaling.model.InstanceMaintenancePolicy;
import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfigurationBlockDeviceMapping;
@@ -1217,6 +1220,205 @@ class AutoScalingServiceTest {
assertEquals(AutoScalingService.INSTANCE_REQUIREMENTS_MISSING_RANGES_MESSAGE, error.getMessage());
}
@Test
void createAndUpdateCarryTheOptionalStructuresAndUpdateLeavesUnsetOnesAlone() {
CapacityReservationSpecification reservation = new CapacityReservationSpecification();
reservation.setCapacityReservationPreference("capacity-reservations-first");
reservation.setCapacityReservationResourceGroupArns(List.of("arn:aws:resource-groups:us-east-1:000000000000:group/cr"));
createWithStructures("structures-asg", new AsgOptionalFields(null, null, null, null,
"role-arn", new InstanceMaintenancePolicy(90, 120),
new AvailabilityZoneDistribution("balanced-only"), reservation));
service.updateAutoScalingGroup(REGION, "structures-asg", null, null, null, null, null,
null, null, null, null, null, null, null, null, null,
new AsgOptionalFields(null, null, null, null, "other-role-arn", null, null, null));
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("structures-asg")).getFirst();
assertEquals("other-role-arn", group.getServiceLinkedRoleArn());
assertEquals(90, group.getInstanceMaintenancePolicy().getMinHealthyPercentage());
assertEquals(120, group.getInstanceMaintenancePolicy().getMaxHealthyPercentage());
assertEquals("balanced-only", group.getAvailabilityZoneDistribution().getCapacityDistributionStrategy());
assertEquals("capacity-reservations-first",
group.getCapacityReservationSpecification().getCapacityReservationPreference());
}
@Test
void instanceMaintenancePolicyRemovalSentinelClearsTheStoredPolicy() {
createWithStructures("maintenance-asg", new AsgOptionalFields(null, null, null, null,
null, new InstanceMaintenancePolicy(100, 110), null, null));
service.updateAutoScalingGroup(REGION, "maintenance-asg", null, null, null, null, null,
null, null, null, null, null, null, null, null, null,
new AsgOptionalFields(null, null, null, null, null,
new InstanceMaintenancePolicy(-1, -1), null, null));
assertNull(service.describeAutoScalingGroups(REGION, List.of("maintenance-asg"))
.getFirst().getInstanceMaintenancePolicy());
}
@Test
void instanceMaintenancePolicyEnforcesTheModelBounds() {
assertMaintenancePolicyRejected(null, 110, AutoScalingService.INSTANCE_MAINTENANCE_POLICY_BOTH_REQUIRED_MESSAGE);
assertMaintenancePolicyRejected(-1, 110, AutoScalingService.INSTANCE_MAINTENANCE_POLICY_PARTIAL_CLEAR_MESSAGE);
assertMaintenancePolicyRejected(101, 150, AutoScalingService.INVALID_MIN_HEALTHY_PERCENTAGE_MESSAGE);
assertMaintenancePolicyRejected(50, 99, AutoScalingService.INVALID_MAX_HEALTHY_PERCENTAGE_MESSAGE);
assertMaintenancePolicyRejected(50, 201, AutoScalingService.INVALID_MAX_HEALTHY_PERCENTAGE_MESSAGE);
assertMaintenancePolicyRejected(0, 101, AutoScalingService.INSTANCE_MAINTENANCE_POLICY_RANGE_MESSAGE);
createWithStructures("maintenance-bounds-asg", new AsgOptionalFields(null, null, null, null,
null, new InstanceMaintenancePolicy(0, 100), null, null));
assertEquals(0, service.describeAutoScalingGroups(REGION, List.of("maintenance-bounds-asg"))
.getFirst().getInstanceMaintenancePolicy().getMinHealthyPercentage());
}
@Test
void capacityStructuresRejectValuesOutsideTheirEnums() {
AwsException strategy = assertThrows(AwsException.class, () -> createWithStructures("bad-strategy-asg",
new AsgOptionalFields(null, null, null, null, null, null,
new AvailabilityZoneDistribution("round-robin"), null)));
assertEquals(AutoScalingService.INVALID_CAPACITY_DISTRIBUTION_STRATEGY_MESSAGE, strategy.getMessage());
CapacityReservationSpecification badPreference = new CapacityReservationSpecification();
badPreference.setCapacityReservationPreference("open");
AwsException preference = assertThrows(AwsException.class, () -> createWithStructures("bad-preference-asg",
new AsgOptionalFields(null, null, null, null, null, null, null, badPreference)));
assertEquals(AutoScalingService.INVALID_CAPACITY_RESERVATION_PREFERENCE_MESSAGE, preference.getMessage());
}
@Test
void capacityReservationPreferenceNoneRejectsATarget() {
CapacityReservationSpecification specification = new CapacityReservationSpecification();
specification.setCapacityReservationPreference("none");
specification.setCapacityReservationIds(List.of("cr-0123456789abcdef0"));
AwsException error = assertThrows(AwsException.class, () -> createWithStructures("none-target-asg",
new AsgOptionalFields(null, null, null, null, null, null, null, specification)));
assertEquals(AutoScalingService.CAPACITY_RESERVATION_TARGET_WITH_NONE_MESSAGE, error.getMessage());
}
@Test
void capacityReservationTargetMembersFollowTheirModelShapes() {
CapacityReservationSpecification badId = new CapacityReservationSpecification();
badId.setCapacityReservationPreference("capacity-reservations-only");
badId.setCapacityReservationIds(List.of("cr 0123"));
AwsException idError = assertThrows(AwsException.class, () -> createWithStructures("bad-id-asg",
new AsgOptionalFields(null, null, null, null, null, null, null, badId)));
assertEquals("ValidationError", idError.getErrorCode());
CapacityReservationSpecification longId = new CapacityReservationSpecification();
longId.setCapacityReservationPreference("capacity-reservations-only");
longId.setCapacityReservationIds(List.of("c".repeat(256)));
assertThrows(AwsException.class, () -> createWithStructures("long-id-asg",
new AsgOptionalFields(null, null, null, null, null, null, null, longId)));
CapacityReservationSpecification longArn = new CapacityReservationSpecification();
longArn.setCapacityReservationPreference("capacity-reservations-only");
longArn.setCapacityReservationResourceGroupArns(List.of("a".repeat(1601)));
assertThrows(AwsException.class, () -> createWithStructures("long-arn-asg",
new AsgOptionalFields(null, null, null, null, null, null, null, longArn)));
}
@Test
void serviceLinkedRoleArnMustBeOneTo1600Characters() {
AwsException empty = assertThrows(AwsException.class, () -> createWithStructures("empty-role-asg",
new AsgOptionalFields(null, null, null, null, "", null, null, null)));
assertEquals(AutoScalingService.INVALID_SERVICE_LINKED_ROLE_ARN_MESSAGE, empty.getMessage());
AwsException tooLong = assertThrows(AwsException.class, () -> createWithStructures("long-role-asg",
new AsgOptionalFields(null, null, null, null, "a".repeat(1601), null, null, null)));
assertEquals(AutoScalingService.INVALID_SERVICE_LINKED_ROLE_ARN_MESSAGE, tooLong.getMessage());
}
@Test
void weightedCapacityMustBeOneTo999AndSetOnEveryOverrideOrNone() {
AwsException outOfRange = assertThrows(AwsException.class, () -> createWithStructures("weight-range-asg",
AsgOptionalFields.none(), weightedPolicy("0", "2")));
assertEquals(AutoScalingService.INVALID_WEIGHTED_CAPACITY_MESSAGE, outOfRange.getMessage());
AwsException notANumber = assertThrows(AwsException.class, () -> createWithStructures("weight-text-asg",
AsgOptionalFields.none(), weightedPolicy("two", "2")));
assertEquals(AutoScalingService.INVALID_WEIGHTED_CAPACITY_MESSAGE, notANumber.getMessage());
AwsException tooLong = assertThrows(AwsException.class, () -> createWithStructures("weight-long-asg",
AsgOptionalFields.none(), weightedPolicy("0".repeat(32) + "1", "2")));
assertEquals(AutoScalingService.INVALID_WEIGHTED_CAPACITY_MESSAGE, tooLong.getMessage());
AwsException partial = assertThrows(AwsException.class, () -> createWithStructures("weight-partial-asg",
AsgOptionalFields.none(), weightedPolicy("2", null)));
assertEquals(AutoScalingService.PARTIAL_WEIGHTED_CAPACITY_MESSAGE, partial.getMessage());
createWithStructures("weight-ok-asg", AsgOptionalFields.none(), weightedPolicy("1", "999"));
assertEquals("999", service.describeAutoScalingGroups(REGION, List.of("weight-ok-asg")).getFirst()
.getMixedInstancesPolicy().getLaunchTemplate().getOverrides().get(1).getWeightedCapacity());
}
@Test
void enableAndDisableMetricsCollectionMaintainEnabledMetrics() {
service.enableMetricsCollection(REGION, "test-asg", List.of("GroupMinSize", "GroupMaxSize"), "1Minute");
service.enableMetricsCollection(REGION, "test-asg", List.of("GroupMaxSize", "GroupTotalInstances"), "1Minute");
assertEquals(List.of("GroupMinSize", "GroupMaxSize", "GroupTotalInstances"), enabledMetrics());
service.disableMetricsCollection(REGION, "test-asg", List.of("GroupMaxSize"));
assertEquals(List.of("GroupMinSize", "GroupTotalInstances"), enabledMetrics());
service.disableMetricsCollection(REGION, "test-asg", List.of());
assertEquals(List.of(), enabledMetrics());
service.enableMetricsCollection(REGION, "test-asg", List.of(), "1Minute");
assertEquals(AutoScalingService.GROUP_METRICS, enabledMetrics());
}
@Test
void enableMetricsCollectionRequiresOneMinuteGranularityAndKnownMetrics() {
AwsException missing = assertThrows(AwsException.class,
() -> service.enableMetricsCollection(REGION, "test-asg", List.of(), null));
assertEquals(AutoScalingService.MISSING_GRANULARITY_MESSAGE, missing.getMessage());
AwsException wrong = assertThrows(AwsException.class,
() -> service.enableMetricsCollection(REGION, "test-asg", List.of(), "5Minute"));
assertEquals(AutoScalingService.INVALID_GRANULARITY_MESSAGE, wrong.getMessage());
AwsException unknown = assertThrows(AwsException.class,
() -> service.enableMetricsCollection(REGION, "test-asg", List.of("CPUUtilization"), "1Minute"));
assertEquals("ValidationError", unknown.getErrorCode());
assertEquals(List.of(), enabledMetrics());
}
private List<String> enabledMetrics() {
return service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getEnabledMetrics();
}
private void assertMaintenancePolicyRejected(Integer min, Integer max, String message) {
AwsException error = assertThrows(AwsException.class, () -> createWithStructures("maintenance-bad-asg",
new AsgOptionalFields(null, null, null, null, null,
new InstanceMaintenancePolicy(min, max), null, null)));
assertEquals("ValidationError", error.getErrorCode());
assertEquals(message, error.getMessage());
}
private void createWithStructures(String name, AsgOptionalFields optionalFields) {
service.createAutoScalingGroup(REGION, name, null, "lt-original", null, "1", null,
0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0,
List.of("Default"), Map.of(), Map.of(), optionalFields);
}
private void createWithStructures(String name, AsgOptionalFields optionalFields, MixedInstancesPolicy policy) {
service.createAutoScalingGroup(REGION, name, null, null, null, null, policy,
0, 3, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), "EC2", 0,
List.of("Default"), Map.of(), Map.of(), optionalFields);
}
private static MixedInstancesPolicy weightedPolicy(String firstWeight, String secondWeight) {
MixedInstancesPolicy.LaunchTemplateOverride first = new MixedInstancesPolicy.LaunchTemplateOverride();
first.setInstanceType("t3.micro");
first.setWeightedCapacity(firstWeight);
MixedInstancesPolicy.LaunchTemplateOverride second = new MixedInstancesPolicy.LaunchTemplateOverride();
second.setInstanceType("t3.small");
second.setWeightedCapacity(secondWeight);
return policyWithOverrides(List.of(first, second));
}
private static MixedInstancesPolicy attributeBasedPolicy(int minVCpuCount, int minMemoryMiB) {
MixedInstancesPolicy.InstanceRequirements requirements = new MixedInstancesPolicy.InstanceRequirements();
requirements.setVCpuCount(intRange(minVCpuCount));
@@ -52,6 +52,11 @@ class CloudFormationAutoScalingIntegrationTest {
"CapacityRebalance": true,
"MaxInstanceLifetime": 86400,
"DefaultInstanceWarmup": 300,
"ServiceLinkedRoleARN": "arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling_cfn",
"InstanceMaintenancePolicy": {"MinHealthyPercentage": 90, "MaxHealthyPercentage": 120},
"AvailabilityZoneDistribution": {"CapacityDistributionStrategy": "balanced-only"},
"CapacityReservationSpecification": {"CapacityReservationPreference": "none"},
"MetricsCollection": [{"Granularity": "1Minute", "Metrics": ["GroupMinSize", "GroupMaxSize"]}],
"Tags": [
{"Key": "cluster", "Value": "demo", "PropagateAtLaunch": true},
{"Key": "control-plane", "Value": "only", "PropagateAtLaunch": false}
@@ -119,7 +124,17 @@ class CloudFormationAutoScalingIntegrationTest {
.body(containsString("<DesiredCapacityType>units</DesiredCapacityType>"))
.body(containsString("<CapacityRebalance>true</CapacityRebalance>"))
.body(containsString("<MaxInstanceLifetime>86400</MaxInstanceLifetime>"))
.body(containsString("<DefaultInstanceWarmup>300</DefaultInstanceWarmup>"));
.body(containsString("<DefaultInstanceWarmup>300</DefaultInstanceWarmup>"))
.body(containsString("<ServiceLinkedRoleARN>arn:aws:iam::000000000000:role/aws-service-role/"
+ "autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling_cfn</ServiceLinkedRoleARN>"))
.body(containsString("<InstanceMaintenancePolicy><MinHealthyPercentage>90</MinHealthyPercentage>"
+ "<MaxHealthyPercentage>120</MaxHealthyPercentage></InstanceMaintenancePolicy>"))
.body(containsString("<AvailabilityZoneDistribution><CapacityDistributionStrategy>balanced-only"
+ "</CapacityDistributionStrategy></AvailabilityZoneDistribution>"))
.body(containsString("<CapacityReservationSpecification><CapacityReservationPreference>none"
+ "</CapacityReservationPreference></CapacityReservationSpecification>"))
.body(containsString("<member><Metric>GroupMinSize</Metric><Granularity>1Minute</Granularity></member>"))
.body(containsString("<member><Metric>GroupMaxSize</Metric><Granularity>1Minute</Granularity></member>"));
}
@Test
@@ -3,10 +3,15 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
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.AvailabilityZoneDistribution;
import io.github.hectorvent.floci.services.autoscaling.model.CapacityReservationSpecification;
import io.github.hectorvent.floci.services.autoscaling.model.InstanceMaintenancePolicy;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
@@ -168,6 +173,131 @@ class AutoScalingGroupCfnProvisionerTest {
assertNull(optional.defaultInstanceWarmup());
}
@Test
void groupCreateCarriesTheOptionalStructuresAndMetricsCollection() {
when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
.thenReturn(group("my-asg"));
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode()
.put("AutoScalingGroupName", "my-asg")
.put("MinSize", "1")
.put("MaxSize", "3")
.put("ServiceLinkedRoleARN", "role-arn");
props.putObject("InstanceMaintenancePolicy")
.put("MinHealthyPercentage", 90)
.put("MaxHealthyPercentage", 120);
props.putObject("AvailabilityZoneDistribution").put("CapacityDistributionStrategy", "balanced-only");
ObjectNode reservation = props.putObject("CapacityReservationSpecification")
.put("CapacityReservationPreference", "capacity-reservations-only");
reservation.putObject("CapacityReservationTarget").putArray("CapacityReservationIds").add("cr-1");
ObjectNode metrics = props.putArray("MetricsCollection").addObject().put("Granularity", "1Minute");
metrics.putArray("Metrics").add("GroupMinSize").add("GroupMaxSize");
ObjectNode launchTemplate = props.putObject("MixedInstancesPolicy").putObject("LaunchTemplate");
launchTemplate.putObject("LaunchTemplateSpecification").put("LaunchTemplateId", "lt-123");
launchTemplate.putArray("Overrides").addObject()
.put("InstanceType", "t3.micro")
.put("WeightedCapacity", "2");
provisioner.provision(r, props, ctx());
ArgumentCaptor<MixedInstancesPolicy> policyCaptor = ArgumentCaptor.forClass(MixedInstancesPolicy.class);
ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
verify(autoScaling).createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
policyCaptor.capture(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(),
anyList(), any(), anyInt(), anyList(), anyMap(), anyMap(), captor.capture());
AsgOptionalFields optional = captor.getValue();
assertEquals("role-arn", optional.serviceLinkedRoleArn());
assertEquals(90, optional.instanceMaintenancePolicy().getMinHealthyPercentage());
assertEquals(120, optional.instanceMaintenancePolicy().getMaxHealthyPercentage());
assertEquals("balanced-only", optional.availabilityZoneDistribution().getCapacityDistributionStrategy());
assertEquals("capacity-reservations-only",
optional.capacityReservationSpecification().getCapacityReservationPreference());
assertEquals(List.of("cr-1"), optional.capacityReservationSpecification().getCapacityReservationIds());
assertEquals("2", policyCaptor.getValue().getLaunchTemplate().getOverrides().getFirst().getWeightedCapacity());
verify(autoScaling).enableMetricsCollection(REGION, "my-asg", List.of("GroupMinSize", "GroupMaxSize"), "1Minute");
}
@Test
void groupCreateLeavesTheOptionalStructuresNullAndMetricsAloneWhenTheTemplateOmitsThem() {
when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
.thenReturn(group("my-asg"));
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
provisioner.provision(r, props, ctx());
ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
verify(autoScaling).createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), captor.capture());
AsgOptionalFields optional = captor.getValue();
assertNull(optional.serviceLinkedRoleArn());
assertNull(optional.instanceMaintenancePolicy());
assertNull(optional.availabilityZoneDistribution());
assertNull(optional.capacityReservationSpecification());
verify(autoScaling, never()).enableMetricsCollection(anyString(), anyString(), anyList(), anyString());
}
@Test
void groupCreateRejectsAMetricsCollectionEntryWithoutGranularity() {
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
props.putArray("MetricsCollection").addObject().putArray("Metrics").add("GroupMinSize");
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertEquals("ValidationError", error.getErrorCode());
verify(autoScaling, never()).createAutoScalingGroup(any(), any(), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), any());
}
@Test
void groupCreateRejectsAnUnknownMetricBeforeCreatingTheGroup() {
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
props.putArray("MetricsCollection").addObject().put("Granularity", "1Minute")
.putArray("Metrics").add("CPUUtilization");
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertEquals("ValidationError", error.getErrorCode());
verify(autoScaling, never()).createAutoScalingGroup(any(), any(), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), any());
}
@Test
void groupCreateRejectsACapacityReservationSpecificationWithoutPreference() {
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
props.putObject("CapacityReservationSpecification").putObject("CapacityReservationTarget")
.putArray("CapacityReservationIds").add("cr-1");
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertEquals("ValidationError", error.getErrorCode());
}
@Test
void groupUpdateSetsEnabledMetricsToExactlyWhatTheTemplateLists() {
when(autoScaling.describeAutoScalingGroups(REGION, List.of("my-asg")))
.thenReturn(List.of(group("my-asg")));
StackResource r = resource(GROUP, "Asg", "my-asg");
ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
props.putArray("MetricsCollection").addObject().put("Granularity", "1Minute")
.putArray("Metrics").add("GroupTotalInstances");
provisioner.provision(r, props, ctx("my-asg"));
verify(autoScaling).disableMetricsCollection(REGION, "my-asg", List.of());
verify(autoScaling).enableMetricsCollection(REGION, "my-asg", List.of("GroupTotalInstances"), "1Minute");
}
@Test
void groupUpdateReconcilesTheSameNameInsteadOfCreatingItAgain() {
// provision() re-runs on every UpdateStack. createAutoScalingGroup throws AlreadyExists, so
@@ -325,11 +455,77 @@ class AutoScalingGroupCfnProvisionerTest {
assertEquals(0, optionalFields.maxInstanceLifetime());
assertEquals(AsgOptionalFields.DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL,
optionalFields.defaultInstanceWarmup());
// The group had no maintenance policy before the update, so rollback clears whatever the
// update set, and restores the empty set of enabled metrics.
assertEquals(InstanceMaintenancePolicy.REMOVAL_SENTINEL,
optionalFields.instanceMaintenancePolicy().getMinHealthyPercentage());
assertEquals(InstanceMaintenancePolicy.REMOVAL_SENTINEL,
optionalFields.instanceMaintenancePolicy().getMaxHealthyPercentage());
verify(autoScaling).disableMetricsCollection(REGION, "my-asg", List.of());
// Subsequent rollback should return false since snapshot is spent
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void rollbackUpdateClearsMembersTheGroupDidNotHaveBeforeTheUpdate() {
// UpdateAutoScalingGroup has no clearing value for these three, so passing the snapshot's
// null through it would leave what the failed update added.
AutoScalingGroup existing = group("my-asg");
existing.setMinSize(1);
existing.setMaxSize(5);
when(autoScaling.describeAutoScalingGroups(eq(REGION), eq(List.of("my-asg"))))
.thenReturn(List.of(existing));
StackResource r = resource(GROUP, "Asg", "my-asg");
ObjectNode props = mapper.createObjectNode()
.put("AutoScalingGroupName", "my-asg")
.put("ServiceLinkedRoleARN", "role-arn");
props.putObject("AvailabilityZoneDistribution").put("CapacityDistributionStrategy", "balanced-only");
props.putObject("CapacityReservationSpecification").put("CapacityReservationPreference", "none");
provisioner.provision(r, props, ctx("my-asg"));
existing.setServiceLinkedRoleArn("role-arn");
existing.setAvailabilityZoneDistribution(new AvailabilityZoneDistribution("balanced-only"));
CapacityReservationSpecification reservation = new CapacityReservationSpecification();
reservation.setCapacityReservationPreference("none");
existing.setCapacityReservationSpecification(reservation);
assertTrue(provisioner.rollbackUpdate(r));
assertNull(existing.getServiceLinkedRoleArn());
assertNull(existing.getAvailabilityZoneDistribution());
assertNull(existing.getCapacityReservationSpecification());
verify(autoScaling).saveAutoScalingGroupIfPresent(existing);
}
@Test
void groupCreatePassesBlankRoleAndWeightToTheServiceForValidation() {
// The service rejects an empty ServiceLinkedRoleARN or WeightedCapacity. Turning either
// into null here would read as "not set" and let the stack through.
when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
.thenReturn(group("my-asg"));
StackResource r = resource(GROUP, "Asg", null);
ObjectNode props = mapper.createObjectNode()
.put("AutoScalingGroupName", "my-asg")
.put("ServiceLinkedRoleARN", "");
ObjectNode launchTemplate = props.putObject("MixedInstancesPolicy").putObject("LaunchTemplate");
launchTemplate.putObject("LaunchTemplateSpecification").put("LaunchTemplateId", "lt-123");
launchTemplate.putArray("Overrides").addObject()
.put("InstanceType", "t3.micro")
.put("WeightedCapacity", "");
provisioner.provision(r, props, ctx());
ArgumentCaptor<MixedInstancesPolicy> policyCaptor = ArgumentCaptor.forClass(MixedInstancesPolicy.class);
ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
verify(autoScaling).createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
policyCaptor.capture(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(),
anyList(), any(), anyInt(), anyList(), anyMap(), anyMap(), captor.capture());
assertEquals("", captor.getValue().serviceLinkedRoleArn());
assertEquals("", policyCaptor.getValue().getLaunchTemplate().getOverrides().getFirst().getWeightedCapacity());
}
@Test
void clearUpdateRemovesSnapshotAttribute() {
StackResource r = resource(GROUP, "Asg", "my-asg");