diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index cb67dc6a57..f4f62a5e55 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -256,6 +256,11 @@ software.amazon.awssdk scheduler + + + software.amazon.awssdk + autoscaling + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index ef8beedbe8..08a4e67de4 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -56,6 +56,7 @@ import software.amazon.awssdk.services.eks.EksClient; import software.amazon.awssdk.services.scheduler.SchedulerClient; import software.amazon.awssdk.services.appconfig.AppConfigClient; import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient; +import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.backup.BackupClient; import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; import software.amazon.awssdk.services.appsync.AppSyncClient; @@ -626,6 +627,14 @@ public final class TestFixtures { .build(); } + public static AutoScalingClient autoScalingClient() { + return AutoScalingClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static AppConfigClient appConfigClient() { return AppConfigClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java new file mode 100644 index 0000000000..c735dad2c0 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java @@ -0,0 +1,123 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.autoscaling.AutoScalingClient; +import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; +import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest; +import software.amazon.awssdk.services.autoscaling.model.CreateLaunchConfigurationRequest; +import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateLaunchTemplateRequest; +import software.amazon.awssdk.services.ec2.model.RequestLaunchTemplateData; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Auto Scaling") +class AutoScalingTest { + + private static final String MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE = + "You must use a valid fully-formed launch template. The request must contain the parameter ImageId"; + private static final String INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE = + "Valid requests must contain either the InstanceID parameter " + + "or both the ImageId and InstanceType parameters."; + + private static AutoScalingClient autoScaling; + private static Ec2Client ec2; + + @BeforeAll + static void setup() { + autoScaling = TestFixtures.autoScalingClient(); + ec2 = TestFixtures.ec2Client(); + } + + @AfterAll + static void cleanup() { + if (autoScaling != null) { + autoScaling.close(); + } + if (ec2 != null) { + ec2.close(); + } + } + + @Test + @DisplayName("CreateAutoScalingGroup rejects launch templates without ImageId") + void missingLaunchTemplateImageIdMapsToSdkAutoScalingException() { + String launchTemplateName = TestFixtures.uniqueName("sdk-missing-image"); + String autoScalingGroupName = TestFixtures.uniqueName("sdk-missing-image-asg"); + + ec2.createLaunchTemplate(CreateLaunchTemplateRequest.builder() + .launchTemplateName(launchTemplateName) + .launchTemplateData(RequestLaunchTemplateData.builder() + .instanceType("t3.micro") + .build()) + .build()); + + assertThatThrownBy(() -> autoScaling.createAutoScalingGroup(CreateAutoScalingGroupRequest.builder() + .autoScalingGroupName(autoScalingGroupName) + .launchTemplate(LaunchTemplateSpecification.builder() + .launchTemplateName(launchTemplateName) + .version("1") + .build()) + .minSize(0) + .maxSize(1) + .desiredCapacity(1) + .availabilityZones("us-east-1a") + .build())) + .isInstanceOfSatisfying(AutoScalingException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().serviceName()).isEqualTo("AutoScaling"); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(error.awsErrorDetails().errorMessage()) + .isEqualTo(MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE); + assertThat(error.requestId()).isNotBlank(); + assertThat(error.getMessage()).contains( + MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, + "Service: AutoScaling", + "Status Code: 400", + "Request ID: ", + "SDK Attempt Count: 1"); + }); + } + + @Test + @DisplayName("CreateLaunchConfiguration rejects missing ImageId or InstanceType") + void missingLaunchConfigurationImageIdMapsToSdkAutoScalingExceptionAtCreateTime() { + String suffix = TestFixtures.uniqueName("sdk-lc"); + + assertThatThrownBy(() -> autoScaling.createLaunchConfiguration(CreateLaunchConfigurationRequest.builder() + .launchConfigurationName(suffix + "-missing-image") + .instanceType("t3.micro") + .build())) + .isInstanceOfSatisfying(AutoScalingException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().serviceName()).isEqualTo("AutoScaling"); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(error.awsErrorDetails().errorMessage()) + .isEqualTo(INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE); + assertThat(error.requestId()).isNotBlank(); + assertThat(error.getMessage()).contains( + INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE, + "Service: AutoScaling", + "Status Code: 400", + "Request ID: ", + "SDK Attempt Count: 1"); + }); + + assertThatThrownBy(() -> autoScaling.createLaunchConfiguration(CreateLaunchConfigurationRequest.builder() + .launchConfigurationName(suffix + "-missing-type") + .imageId("ami-12345678") + .build())) + .isInstanceOfSatisfying(AutoScalingException.class, error -> { + assertThat(error.statusCode()).isEqualTo(400); + assertThat(error.awsErrorDetails().serviceName()).isEqualTo("AutoScaling"); + assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(error.awsErrorDetails().errorMessage()) + .isEqualTo(INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE); + }); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java index 862e10bdd4..1e2c63335f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java @@ -95,6 +95,7 @@ public class AutoScalingQueryHandler { private Response handleCreateLaunchConfiguration(MultivaluedMap p, String region) { service.createLaunchConfiguration(region, p.getFirst("LaunchConfigurationName"), + p.getFirst("InstanceId"), p.getFirst("ImageId"), p.getFirst("InstanceType"), p.getFirst("KeyName"), @@ -121,10 +122,10 @@ public class AutoScalingQueryHandler { xml.start("member") .elem("LaunchConfigurationName", lc.getLaunchConfigurationName()) .elem("LaunchConfigurationARN", lc.getLaunchConfigurationArn()) - .elem("ImageId", lc.getImageId() != null ? lc.getImageId() : "") - .elem("InstanceType", lc.getInstanceType() != null ? lc.getInstanceType() : "t3.micro") .elem("CreatedTime", ISO_FMT.format(lc.getCreatedTime())) .elem("AssociatePublicIpAddress", String.valueOf(lc.isAssociatePublicIpAddress())); + if (lc.getImageId() != null) { xml.elem("ImageId", lc.getImageId()); } + if (lc.getInstanceType() != null) { xml.elem("InstanceType", lc.getInstanceType()); } if (lc.getKeyName() != null) { xml.elem("KeyName", lc.getKeyName()); } if (lc.getUserData() != null) { xml.elem("UserData", lc.getUserData()); } if (lc.getIamInstanceProfile() != null) { xml.elem("IamInstanceProfile", lc.getIamInstanceProfile()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index 4062e90f2d..02310059df 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.storage.StorageBackedMap; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.autoscaling.model.*; 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.LaunchTemplate; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -20,6 +22,14 @@ import java.util.stream.Collectors; @ApplicationScoped public class AutoScalingService { + static final String MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE = + "You must use a valid fully-formed launch template. The request must contain the parameter ImageId"; + static final String INVALID_LAUNCH_TEMPLATE_MESSAGE = + "The specified launch template does not exist."; + static final String INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE = + "Valid requests must contain either the InstanceID parameter " + + "or both the ImageId and InstanceType parameters."; + @Inject RegionResolver regionResolver; @@ -58,8 +68,8 @@ public class AutoScalingService { // ── Launch Configurations ────────────────────────────────────────────────── - public LaunchConfiguration createLaunchConfiguration(String region, String name, String imageId, - String instanceType, String keyName, + public LaunchConfiguration createLaunchConfiguration(String region, String name, String instanceId, + String imageId, String instanceType, String keyName, List securityGroups, String userData, String iamInstanceProfile, boolean associatePublicIpAddress) { @@ -68,13 +78,47 @@ public class AutoScalingService { throw new AwsException("AlreadyExists", "Launch configuration '" + name + "' already exists.", 400); } + if (isBlank(instanceId) && (isBlank(imageId) || isBlank(instanceType))) { + throw new AwsException("ValidationError", INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE, 400); + } + if (notBlank(instanceId) && ec2Service != null) { + List sourceInstances = ec2Service.describeInstances(region, List.of(instanceId), Map.of()) + .stream() + .flatMap(reservation -> reservation.getInstances().stream()) + .collect(Collectors.toList()); + if (!sourceInstances.isEmpty()) { + Instance source = sourceInstances.getFirst(); + if (isBlank(imageId)) { + imageId = source.getImageId(); + } + if (isBlank(instanceType)) { + instanceType = source.getInstanceType(); + } + if (isBlank(keyName)) { + keyName = source.getKeyName(); + } + if ((securityGroups == null || securityGroups.isEmpty()) + && source.getSecurityGroups() != null) { + securityGroups = source.getSecurityGroups().stream() + .map(group -> group.getGroupId() != null ? group.getGroupId() : group.getGroupName()) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + if (isBlank(userData)) { + userData = source.getUserData(); + } + if (isBlank(iamInstanceProfile)) { + iamInstanceProfile = source.getIamInstanceProfileArn(); + } + } + } LaunchConfiguration lc = new LaunchConfiguration(); lc.setLaunchConfigurationName(name); lc.setLaunchConfigurationArn( AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(), "launchConfiguration:" + name).toString()); lc.setImageId(imageId); - lc.setInstanceType(instanceType != null ? instanceType : "t3.micro"); + lc.setInstanceType(instanceType); lc.setKeyName(keyName); lc.setSecurityGroups(securityGroups != null ? new ArrayList<>(securityGroups) : new ArrayList<>()); lc.setUserData(userData); @@ -131,6 +175,8 @@ public class AutoScalingService { "Valid requests must contain either LaunchTemplate, LaunchConfigurationName, " + "InstanceId or MixedInstancesPolicy parameter.", 400); } + validateEffectiveLaunchImage(region, launchConfigName, launchTemplateId, launchTemplateName, + launchTemplateVersion, mixedInstancesPolicy); AutoScalingGroup asg = new AutoScalingGroup(); asg.setAutoScalingGroupName(name); @@ -174,6 +220,14 @@ public class AutoScalingService { List terminationPolicies) { AutoScalingGroup asg = requireGroup(region, name); validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy); + LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName, + launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy); + validateEffectiveLaunchImage(region, + effectiveIdentity.launchConfigurationName(), + effectiveIdentity.launchTemplateId(), + effectiveIdentity.launchTemplateName(), + effectiveIdentity.launchTemplateVersion(), + effectiveIdentity.mixedInstancesPolicy()); if (launchConfigName != null) { asg.setLaunchConfigurationName(launchConfigName); asg.setLaunchTemplateId(null); @@ -668,6 +722,107 @@ public class AutoScalingService { return value != null && !value.isBlank(); } + private LaunchIdentity effectiveLaunchIdentity(AutoScalingGroup asg, + String launchConfigName, + String launchTemplateId, + String launchTemplateName, + String launchTemplateVersion, + MixedInstancesPolicy mixedInstancesPolicy) { + LaunchIdentity identity = new LaunchIdentity( + asg.getLaunchConfigurationName(), + asg.getLaunchTemplateId(), + asg.getLaunchTemplateName(), + asg.getLaunchTemplateVersion(), + asg.getMixedInstancesPolicy()); + if (launchConfigName != null) { + return new LaunchIdentity(launchConfigName, null, null, null, null); + } + if (launchTemplateId != null || launchTemplateName != null) { + return new LaunchIdentity(null, launchTemplateId, launchTemplateName, launchTemplateVersion, null); + } + if (mixedInstancesPolicy != null) { + return new LaunchIdentity(null, null, null, null, mixedInstancesPolicy); + } + return identity; + } + + private void validateEffectiveLaunchImage(String region, + String launchConfigName, + String launchTemplateId, + String launchTemplateName, + String launchTemplateVersion, + MixedInstancesPolicy mixedInstancesPolicy) { + if (launchConfigName != null) { + return; + } + if (launchTemplateId != null || launchTemplateName != null) { + validateLaunchTemplateImage(region, launchTemplateId, launchTemplateName, launchTemplateVersion); + return; + } + MixedInstancesPolicy.LaunchTemplateSpecification specification = + mixedInstancesLaunchTemplateSpecification(mixedInstancesPolicy); + if (specification != null) { + validateLaunchTemplateImage(region, + specification.getLaunchTemplateId(), + specification.getLaunchTemplateName(), + specification.getVersion()); + } + } + + private void validateLaunchTemplateImage(String region, String launchTemplateId, + String launchTemplateName, String launchTemplateVersion) { + if (ec2Service == null) { + return; + } + List versions = isBlank(launchTemplateVersion) ? List.of() : List.of(launchTemplateVersion); + List launchTemplateVersions = ec2Service.describeLaunchTemplateVersions( + region, + launchTemplateId, + launchTemplateName, + versions); + if (launchTemplateVersions.isEmpty()) { + throw invalidLaunchTemplate(); + } + if (isBlank(launchTemplateVersions.getFirst().getImageId())) { + throw missingLaunchTemplateImageId(); + } + } + + private static MixedInstancesPolicy.LaunchTemplateSpecification mixedInstancesLaunchTemplateSpecification( + MixedInstancesPolicy policy) { + if (policy == null || policy.getLaunchTemplate() == null) { + return null; + } + MixedInstancesPolicy.LaunchTemplateSpecification specification = + policy.getLaunchTemplate().getLaunchTemplateSpecification(); + if (specification == null) { + return null; + } + if (isBlank(specification.getLaunchTemplateId()) && isBlank(specification.getLaunchTemplateName())) { + return null; + } + return specification; + } + + private static AwsException missingLaunchTemplateImageId() { + return new AwsException("ValidationError", MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, 400); + } + + private static AwsException invalidLaunchTemplate() { + return new AwsException("ValidationError", INVALID_LAUNCH_TEMPLATE_MESSAGE, 400); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } + + private record LaunchIdentity( + String launchConfigurationName, + String launchTemplateId, + String launchTemplateName, + String launchTemplateVersion, + MixedInstancesPolicy mixedInstancesPolicy) {} + private static String instanceRefreshKey(String region, String asgName, String refreshId) { return region + "::" + asgName + "::" + refreshId; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index c4b3edd06b..a822df2246 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -746,6 +746,7 @@ public class CloudFormationResourceProvisioner { } String associatePublicIp = resolveOptional(props, "AssociatePublicIpAddress", engine); var lc = autoScalingService.createLaunchConfiguration(region, name, + resolveOptional(props, "InstanceId", engine), resolveOptional(props, "ImageId", engine), resolveOptional(props, "InstanceType", engine), resolveOptional(props, "KeyName", engine), diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 3d35ffaec6..4ac5c956b8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -318,6 +318,9 @@ public class Ec2Service { List securityGroupIds, String subnetId, String clientToken, List instanceTags, String userData, String iamInstanceProfileArn) { + if (imageId == null || imageId.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter ImageId", 400); + } ensureDefaultResources(region); // Resolve subnet @@ -363,7 +366,7 @@ public class Ec2Service { Instance inst = new Instance(); inst.setInstanceId(instanceId); - inst.setImageId(imageId != null ? imageId : "ami-default"); + inst.setImageId(imageId); inst.setState(InstanceState.pending()); inst.setInstanceType(instanceType != null ? instanceType : "t2.micro"); inst.setPlacement(new Placement(az)); diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java index 3cd0011c9c..e61a64a73e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java @@ -16,10 +16,16 @@ class AutoScalingIntegrationTest { 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 String policyArn; private static String instanceRefreshId; private static String pagedInstanceRefreshId; + private static String launchTemplateId; + private static String refreshLaunchTemplateId; + private static String mixedLaunchTemplateId; + private static String replacementLaunchTemplateId; // ── Launch Configurations ───────────────────────────────────────────────── @@ -433,10 +439,12 @@ class AutoScalingIntegrationTest { @Test @Order(23) void createAutoScalingGroupWithLaunchTemplateId() { + launchTemplateId = createLaunchTemplate("asg-integration-lt"); + given() .formParam("Action", "CreateAutoScalingGroup") .formParam("AutoScalingGroupName", "my-lt-asg") - .formParam("LaunchTemplate.LaunchTemplateId", "lt-0123456789abcdef0") + .formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId) .formParam("LaunchTemplate.Version", "$Latest") .formParam("MinSize", "0") .formParam("MaxSize", "1") @@ -477,7 +485,7 @@ class AutoScalingIntegrationTest { .then() .statusCode(200) .body(containsString("my-lt-asg")) - .body(containsString("lt-0123456789abcdef0")) + .body(containsString("" + launchTemplateId + "")) .body(containsString("$Latest")) .body(containsString("subnet-12345678,subnet-87654321")) .body(containsString("owner")) @@ -509,11 +517,14 @@ class AutoScalingIntegrationTest { @Test @Order(25) void startInstanceRefresh() { + refreshLaunchTemplateId = createLaunchTemplate("asg-integration-refresh-lt"); + createLaunchTemplateVersion(refreshLaunchTemplateId, "t3.small"); + instanceRefreshId = given() .formParam("Action", "StartInstanceRefresh") .formParam("AutoScalingGroupName", "my-lt-asg") .formParam("Strategy", "Rolling") - .formParam("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", "lt-0fedcba9876543210") + .formParam("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", refreshLaunchTemplateId) .formParam("DesiredConfiguration.LaunchTemplate.Version", "2") .formParam("Preferences.MinHealthyPercentage", "90") .formParam("Preferences.MaxHealthyPercentage", "120") @@ -556,7 +567,7 @@ class AutoScalingIntegrationTest { assertThat(body, containsString("100")); assertThat(body, containsString("0")); assertThat(body, containsString("Rolling")); - assertThat(body, containsString("lt-0fedcba9876543210")); + assertThat(body, containsString("" + refreshLaunchTemplateId + "")); assertThat(body, containsString("2")); assertThat(body, containsString("90")); assertThat(body, containsString("120")); @@ -573,7 +584,7 @@ class AutoScalingIntegrationTest { .post("/") .then() .statusCode(200) - .body(containsString("lt-0fedcba9876543210")) + .body(containsString("" + refreshLaunchTemplateId + "")) .body(containsString("2")); } @@ -624,11 +635,15 @@ class AutoScalingIntegrationTest { @Test @Order(28) void createAutoScalingGroupWithMixedInstancesPolicy() { + mixedLaunchTemplateId = createLaunchTemplate("asg-integration-mixed-lt"); + createLaunchTemplateVersion(mixedLaunchTemplateId, "t3.small"); + createLaunchTemplateVersion(mixedLaunchTemplateId, "t3.medium"); + given() .formParam("Action", "CreateAutoScalingGroup") .formParam("AutoScalingGroupName", "my-mixed-asg") .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", - "lt-mixed") + mixedLaunchTemplateId) .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "3") .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "t4g.medium") .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.2.InstanceType", "m7g.large") @@ -656,7 +671,7 @@ class AutoScalingIntegrationTest { .statusCode(200) .body(containsString("")) .body(containsString("")) - .body(containsString("lt-mixed")) + .body(containsString("" + mixedLaunchTemplateId + "")) .body(containsString("3")) .body(containsString("t4g.medium")) .body(containsString("m7g.large")) @@ -668,11 +683,16 @@ class AutoScalingIntegrationTest { @Test @Order(29) void updateAutoScalingGroupFromLaunchTemplateToMixedInstancesPolicy() { + replacementLaunchTemplateId = createLaunchTemplate("asg-integration-replacement-lt"); + createLaunchTemplateVersion(replacementLaunchTemplateId, "t3.small"); + createLaunchTemplateVersion(replacementLaunchTemplateId, "t3.medium"); + createLaunchTemplateVersion(replacementLaunchTemplateId, "t3.large"); + given() .formParam("Action", "UpdateAutoScalingGroup") .formParam("AutoScalingGroupName", "my-lt-asg") .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", - "lt-replacement") + replacementLaunchTemplateId) .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "4") .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "c7g.large") .formParam("MixedInstancesPolicy.InstancesDistribution.OnDemandBaseCapacity", "0") @@ -694,7 +714,7 @@ class AutoScalingIntegrationTest { .then() .statusCode(200) .body(containsString("")) - .body(containsString("lt-replacement")) + .body(containsString("" + replacementLaunchTemplateId + "")) .body(containsString("4")) .body(containsString("c7g.large")) .body(containsString("0")) @@ -705,11 +725,14 @@ class AutoScalingIntegrationTest { @Test @Order(30) void updateMixedInstancesPolicyOverridesAndDistribution() { + createLaunchTemplateVersion(mixedLaunchTemplateId, "t3.large"); + createLaunchTemplateVersion(mixedLaunchTemplateId, "t3.xlarge"); + given() .formParam("Action", "UpdateAutoScalingGroup") .formParam("AutoScalingGroupName", "my-mixed-asg") .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId", - "lt-mixed") + mixedLaunchTemplateId) .formParam("MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.Version", "5") .formParam("MixedInstancesPolicy.LaunchTemplate.Overrides.member.1.InstanceType", "r7g.large") .formParam("MixedInstancesPolicy.InstancesDistribution.OnDemandBaseCapacity", "2") @@ -812,4 +835,31 @@ class AutoScalingIntegrationTest { .statusCode(200) .body(not(containsString("my-asg"))); } + + private static String createLaunchTemplate(String name) { + return given() + .formParam("Action", "CreateLaunchTemplate") + .formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", "ami-12345678") + .formParam("LaunchTemplateData.InstanceType", "t3.micro") + .header("Authorization", EC2_AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId"); + } + + private static void createLaunchTemplateVersion(String id, String instanceType) { + given() + .formParam("Action", "CreateLaunchTemplateVersion") + .formParam("LaunchTemplateId", id) + .formParam("LaunchTemplateData.ImageId", "ami-12345678") + .formParam("LaunchTemplateData.InstanceType", instanceType) + .header("Authorization", EC2_AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java index 33bae9b837..395b87916f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java @@ -6,6 +6,10 @@ import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh; import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; +import io.github.hectorvent.floci.services.ec2.model.Reservation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; class AutoScalingServiceTest { @@ -88,6 +93,184 @@ class AutoScalingServiceTest { assertNull(group.getLaunchConfigurationName()); } + @Test + void createAutoScalingGroupRejectsResolvedLaunchTemplateWithoutImageId() { + Ec2Service ec2Service = mock(Ec2Service.class); + service.ec2Service = ec2Service; + LaunchTemplate version = new LaunchTemplate(); + version.setImageId(null); + when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("1"))) + .thenReturn(List.of(version)); + + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "missing-image-asg", + null, + "lt-no-image", + null, + "1", + null, + 0, + 1, + 1, + 300, + List.of("us-east-1a"), + List.of(), + List.of(), + List.of(), + "EC2", + 0, + List.of("Default"), + java.util.Map.of())); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(service.describeAutoScalingGroups(REGION, List.of("missing-image-asg")).isEmpty()); + } + + @Test + void createLaunchConfigurationRejectsMissingImageOrInstanceTypeWithoutInstanceId() { + AwsException missingImage = assertThrows(AwsException.class, () -> service.createLaunchConfiguration(REGION, + "lc-no-image", + null, + "", + "t3.micro", + null, + List.of(), + null, + null, + false)); + + assertEquals("ValidationError", missingImage.getErrorCode()); + assertEquals(AutoScalingService.INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE, missingImage.getMessage()); + assertEquals(400, missingImage.getHttpStatus()); + assertTrue(service.describeLaunchConfigurations(REGION, List.of("lc-no-image")).isEmpty()); + + AwsException missingInstanceType = assertThrows(AwsException.class, + () -> service.createLaunchConfiguration(REGION, + "lc-no-instance-type", + null, + "ami-12345678", + null, + null, + List.of(), + null, + null, + false)); + + assertEquals("ValidationError", missingInstanceType.getErrorCode()); + assertEquals(AutoScalingService.INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE, + missingInstanceType.getMessage()); + assertEquals(400, missingInstanceType.getHttpStatus()); + assertTrue(service.describeLaunchConfigurations(REGION, List.of("lc-no-instance-type")).isEmpty()); + } + + @Test + void createLaunchConfigurationWithInstanceIdCopiesSourceInstanceLaunchAttributes() { + Ec2Service ec2Service = mock(Ec2Service.class); + service.ec2Service = ec2Service; + Instance source = new Instance(); + source.setInstanceId("i-1234567890abcdef0"); + source.setImageId("ami-from-instance"); + source.setInstanceType("m7g.large"); + source.setKeyName("source-key"); + source.setSecurityGroups(List.of(new GroupIdentifier("sg-source", "default"))); + source.setUserData("source-user-data"); + source.setIamInstanceProfileArn("arn:aws:iam::000000000000:instance-profile/source"); + Reservation reservation = new Reservation(); + reservation.getInstances().add(source); + when(ec2Service.describeInstances(REGION, List.of("i-1234567890abcdef0"), java.util.Map.of())) + .thenReturn(List.of(reservation)); + + var launchConfiguration = service.createLaunchConfiguration(REGION, + "lc-from-instance", + "i-1234567890abcdef0", + null, + null, + null, + List.of(), + null, + null, + false); + + assertEquals("ami-from-instance", launchConfiguration.getImageId()); + assertEquals("m7g.large", launchConfiguration.getInstanceType()); + assertEquals("source-key", launchConfiguration.getKeyName()); + assertEquals(List.of("sg-source"), launchConfiguration.getSecurityGroups()); + assertEquals("source-user-data", launchConfiguration.getUserData()); + assertEquals("arn:aws:iam::000000000000:instance-profile/source", + launchConfiguration.getIamInstanceProfile()); + assertEquals(launchConfiguration, + service.describeLaunchConfigurations(REGION, List.of("lc-from-instance")).getFirst()); + } + + @Test + void createAutoScalingGroupRejectsUnresolvedLaunchTemplateBeforeMutation() { + Ec2Service ec2Service = mock(Ec2Service.class); + service.ec2Service = ec2Service; + when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-missing", null, List.of("1"))) + .thenReturn(List.of()); + + AwsException error = assertThrows(AwsException.class, () -> service.createAutoScalingGroup(REGION, + "missing-template-asg", + null, + "lt-missing", + null, + "1", + null, + 0, + 1, + 1, + 300, + List.of("us-east-1a"), + List.of(), + List.of(), + List.of(), + "EC2", + 0, + List.of("Default"), + java.util.Map.of())); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.INVALID_LAUNCH_TEMPLATE_MESSAGE, error.getMessage()); + assertEquals(400, error.getHttpStatus()); + assertTrue(service.describeAutoScalingGroups(REGION, List.of("missing-template-asg")).isEmpty()); + } + + @Test + void updateAutoScalingGroupRejectsResolvedLaunchTemplateWithoutImageIdBeforeMutation() { + Ec2Service ec2Service = mock(Ec2Service.class); + service.ec2Service = ec2Service; + LaunchTemplate version = new LaunchTemplate(); + version.setImageId(""); + when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("2"))) + .thenReturn(List.of(version)); + + AwsException error = assertThrows(AwsException.class, () -> service.updateAutoScalingGroup( + REGION, + "test-asg", + null, + "lt-no-image", + null, + "2", + null, + null, + 5, + null, + null, + null, + null, + null, + null, + null)); + + assertEquals("ValidationError", error.getErrorCode()); + assertEquals(AutoScalingService.MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE, error.getMessage()); + var group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst(); + assertEquals("lt-original", group.getLaunchTemplateId()); + assertEquals(3, group.getMaxSize()); + } + @Test void describeInstanceRefreshesPaginatesNewestFirst() { InstanceRefresh first = service.startInstanceRefresh(REGION, "test-asg", new InstanceRefresh()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index e74ab2420c..4b178551f7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ec2; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -15,6 +16,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -37,6 +39,20 @@ class Ec2ServiceTest { verifyNoInteractions(containerManager); } + @Test + void runInstancesRequiresImageIdInsteadOfDefaulting() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new InMemoryStorageFactory()); + + AwsException error = assertThrows(AwsException.class, () -> service.runInstances( + "us-east-1", null, "t3.micro", 1, 1, null, List.of(), null, null, + List.of(), null, null)); + + assertEquals("MissingParameter", error.getErrorCode()); + assertEquals("The request must contain the parameter ImageId", error.getMessage()); + assertEquals(400, error.getHttpStatus()); + } + @Test void launchTemplateVersionInheritsOmittedFieldsFromRequestedSourceVersion() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),