Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ec2): report NotFound for launch templates requested by name (#3246)

BingEdward8bc4891a9a9f
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
index 0160e42210..bce1108164 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.autoscaling;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
@@ -35,6 +36,10 @@ public class AutoScalingReconciler {
private static final Logger LOG = Logger.getLogger(AutoScalingReconciler.class);
+ /** The codes DescribeLaunchTemplates raises for an explicit name or id that does not exist. */
+ private static final Set<String> LAUNCH_TEMPLATE_NOT_FOUND_CODES =
+ Set.of("InvalidLaunchTemplateName.NotFoundException", "InvalidLaunchTemplateId.NotFound");
+
private final AutoScalingService asgService;
private final Ec2Service ec2Service;
private final ElbV2Service elbV2Service;
@@ -553,12 +558,34 @@ public class AutoScalingReconciler {
if ((ltId == null || ltId.isBlank()) && (ltName == null || ltName.isBlank())) {
return null;
}
- List<LaunchTemplate> launchTemplates = ec2Service.describeLaunchTemplates(
- asg.getRegion(),
- ltId == null || ltId.isBlank() ? List.of() : List.of(ltId),
- ltName == null || ltName.isBlank() ? List.of() : List.of(ltName),
- Map.of());
- return launchTemplates.isEmpty() ? null : launchTemplates.get(0);
+ return lookupLaunchTemplate(asg, ltId, ltName);
+ }
+
+ /**
+ * The launch template a group points at, or null when it is gone. DescribeLaunchTemplates
+ * reports an explicitly requested name or id that does not exist as an error, which must not
+ * abort a reconcile pass: a group whose template was deleted simply has nothing to launch from.
+ * Only those NotFound codes read as "gone"; any other failure propagates rather than quietly
+ * skipping the group's scaling.
+ */
+ private LaunchTemplate lookupLaunchTemplate(AutoScalingGroup asg, String ltId, String ltName) {
+ try {
+ List<LaunchTemplate> launchTemplates = ec2Service.describeLaunchTemplates(
+ asg.getRegion(),
+ ltId == null || ltId.isBlank() ? List.of() : List.of(ltId),
+ ltName == null || ltName.isBlank() ? List.of() : List.of(ltName),
+ Map.of());
+ return launchTemplates.isEmpty() ? null : launchTemplates.get(0);
+ } catch (AwsException e) {
+ if (!LAUNCH_TEMPLATE_NOT_FOUND_CODES.contains(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("ASG {0}: launch template {1} is gone: {2}",
+ asg.getAutoScalingGroupName(),
+ ltId == null || ltId.isBlank() ? ltName : ltId,
+ e.getMessage());
+ return null;
+ }
}
private MixedInstancesPolicy.LaunchTemplateSpecification mixedInstancesLaunchTemplateSpecification(
@@ -582,14 +609,8 @@ public class AutoScalingReconciler {
private LaunchTemplate resolveMixedInstancesLaunchTemplate(
AutoScalingGroup asg, MixedInstancesPolicy.LaunchTemplateSpecification specification) {
- String ltId = specification.getLaunchTemplateId();
- String ltName = specification.getLaunchTemplateName();
- List<LaunchTemplate> launchTemplates = ec2Service.describeLaunchTemplates(
- asg.getRegion(),
- ltId == null || ltId.isBlank() ? List.of() : List.of(ltId),
- ltName == null || ltName.isBlank() ? List.of() : List.of(ltName),
- Map.of());
- return launchTemplates.isEmpty() ? null : launchTemplates.get(0);
+ return lookupLaunchTemplate(
+ asg, specification.getLaunchTemplateId(), specification.getLaunchTemplateName());
}
private String mixedInstancesInstanceType(AutoScalingGroup asg, LaunchTemplate version) {
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 198955bdfa..6fcefdcec7 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
@@ -4370,9 +4370,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return launchTemplate;
}
+ /**
+ * Unknown ids and names yield an empty list here rather than the NotFound that
+ * {@link #describeLaunchTemplates} raises: AutoScaling resolves a group's launch template
+ * through this method and reports its own ValidationError when nothing comes back.
+ */
public List<LaunchTemplate> describeLaunchTemplateVersions(String region, String id, String name,
List<String> requestedVersions) {
- List<LaunchTemplate> templates = describeLaunchTemplates(
+ List<LaunchTemplate> templates = matchingLaunchTemplates(
region,
id != null && !id.isBlank() ? List.of(id) : List.of(),
name != null && !name.isBlank() ? List.of(name) : List.of(),
@@ -4414,8 +4419,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return launchTemplate;
}
+ /**
+ * DescribeLaunchTemplates as EC2 defines it: an explicitly requested name or id that does not
+ * exist is an error, not an empty result. Callers that only want to look a template up, where
+ * "absent" is an answer rather than a failure, use {@link #matchingLaunchTemplates} instead.
+ */
public List<LaunchTemplate> describeLaunchTemplates(String region, List<String> ids,
List<String> names, Map<String, List<String>> filters) {
+ if (!names.isEmpty() || !ids.isEmpty()) {
+ List<LaunchTemplate> regionTemplates =
+ matchingLaunchTemplates(region, List.of(), List.of(), Map.of());
+ for (String name : names) {
+ if (regionTemplates.stream().noneMatch(lt -> name.equals(lt.getLaunchTemplateName()))) {
+ throw new AwsException("InvalidLaunchTemplateName.NotFoundException",
+ "The launch template '" + name + "' does not exist.", 400);
+ }
+ }
+ for (String id : ids) {
+ if (regionTemplates.stream().noneMatch(lt -> id.equals(lt.getLaunchTemplateId()))) {
+ throw new AwsException("InvalidLaunchTemplateId.NotFound",
+ "The launch template ID '" + id + "' does not exist.", 400);
+ }
+ }
+ }
+ return matchingLaunchTemplates(region, ids, names, filters);
+ }
+
+ private List<LaunchTemplate> matchingLaunchTemplates(String region, List<String> ids,
+ List<String> names, Map<String, List<String>> filters) {
ensureDefaultResources(region);
return launchTemplates.scan(k -> true).stream()
.filter(lt -> lt.getRegion().equals(region))
@@ -4462,6 +4493,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return launchTemplate;
}
+ /**
+ * EC2 spells the two not-found codes asymmetrically —
+ * {@code InvalidLaunchTemplateName.NotFoundException} but {@code InvalidLaunchTemplateId.NotFound},
+ * no suffix. Both are reproduced as AWS emits them; making them consistent would break clients
+ * such as Karpenter, which match on the exact strings.
+ */
private LaunchTemplate findLaunchTemplate(String region, String id, String name) {
if (id != null && !id.isBlank()) {
LaunchTemplate launchTemplate = launchTemplates.get(key(region, id)).orElse(null);
@@ -4475,7 +4512,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
.orElseThrow(() -> new AwsException("InvalidLaunchTemplateName.NotFoundException",
"The specified launch template does not exist.", 400));
}
- throw new AwsException("InvalidLaunchTemplateId.NotFoundException",
+ throw new AwsException("InvalidLaunchTemplateId.NotFound",
"The specified launch template does not exist.", 400);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
index 71816bebc3..edec6f7ae9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.autoscaling;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
@@ -25,6 +26,7 @@ import java.util.Set;
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.mockito.Mockito.anyList;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
@@ -467,6 +469,48 @@ class AutoScalingReconcilerTest {
verify(asgService, times(2)).saveAutoScalingGroup(asg);
}
+ @Test
+ void deletedLaunchTemplateDoesNotAbortTheReconcilePass() {
+ AutoScalingService asgService = mock(AutoScalingService.class);
+ Ec2Service ec2Service = mock(Ec2Service.class);
+ AutoScalingGroup asg = asgWhoseLaunchTemplateLookupFails(ec2Service,
+ new AwsException("InvalidLaunchTemplateName.NotFoundException",
+ "The launch template 'app-lt' does not exist.", 400));
+ AutoScalingReconciler reconciler =
+ new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
+
+ reconciler.reconcile(asg);
+
+ assertEquals(0, asg.getInstances().size());
+ verify(asgService).completeInstanceRefreshIfSettled("us-east-1", "app-asg");
+ }
+
+ @Test
+ void otherLaunchTemplateErrorsSurfaceRatherThanSilentlySkippingScaling() {
+ AutoScalingService asgService = mock(AutoScalingService.class);
+ Ec2Service ec2Service = mock(Ec2Service.class);
+ AutoScalingGroup asg = asgWhoseLaunchTemplateLookupFails(ec2Service,
+ new AwsException("RequestLimitExceeded", "Request limit exceeded.", 503));
+ AutoScalingReconciler reconciler =
+ new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
+
+ AwsException thrown = assertThrows(AwsException.class, () -> reconciler.reconcile(asg));
+
+ assertEquals("RequestLimitExceeded", thrown.getErrorCode());
+ }
+
+ private static AutoScalingGroup asgWhoseLaunchTemplateLookupFails(Ec2Service ec2Service,
+ AwsException failure) {
+ AutoScalingGroup asg = new AutoScalingGroup();
+ asg.setRegion("us-east-1");
+ asg.setAutoScalingGroupName("app-asg");
+ asg.setDesiredCapacity(1);
+ asg.setLaunchTemplateName("app-lt");
+ when(ec2Service.describeLaunchTemplates("us-east-1", List.of(), List.of("app-lt"), Map.of()))
+ .thenThrow(failure);
+ return asg;
+ }
+
private static AsgInstance instance(String lifecycleState) {
AsgInstance instance = new AsgInstance();
instance.setLifecycleState(lifecycleState);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
index 1f34b80592..c99f3c6a4b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java
@@ -2015,6 +2015,35 @@ class Ec2IntegrationTest {
equalTo("sample-template"));
}
+ @Test
+ @Order(44)
+ void describeLaunchTemplatesRejectsMissingName() {
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("LaunchTemplateName.1", "no-such-template")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidLaunchTemplateName.NotFoundException"));
+ }
+
+ @Test
+ @Order(44)
+ void describeLaunchTemplatesWithNoMatchingFilterStaysAnEmptyList() {
+ given()
+ .formParam("Action", "DescribeLaunchTemplates")
+ .formParam("Filter.1.Name", "launch-template-name")
+ .formParam("Filter.1.Value.1", "no-such-template")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("<item>")));
+ }
+
@Test
@Order(45)
void describeLaunchTemplateVersionsById() {
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 cae65ce583..2e04a1e8b4 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
@@ -379,6 +379,81 @@ class Ec2ServiceTest {
assertEquals(400, error.getHttpStatus());
}
+ @Test
+ void describeLaunchTemplatesRejectsMissingExplicitNamesAndIds() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory());
+
+ // An unfiltered describe on an account with no templates is not an error.
+ assertTrue(service.describeLaunchTemplates("us-east-1", List.of(), List.of(), Map.of()).isEmpty());
+
+ LaunchTemplateData data = new LaunchTemplateData();
+ data.setImageId("ami-present");
+ LaunchTemplate present = service.createLaunchTemplate("us-east-1", "present-template", data, List.of());
+
+ assertEquals(1, service.describeLaunchTemplates(
+ "us-east-1", List.of(), List.of("present-template"), Map.of()).size());
+
+ // Karpenter creates a launch template only when the lookup fails with this code; an empty
+ // success reads as "already there" and leaves it waiting on a template nothing will create.
+ AwsException byName = assertThrows(AwsException.class, () -> service.describeLaunchTemplates(
+ "us-east-1", List.of(), List.of("absent-template"), Map.of()));
+ assertEquals("InvalidLaunchTemplateName.NotFoundException", byName.getErrorCode());
+ assertEquals(400, byName.getHttpStatus());
+
+ // A missing name is not masked by a present one in the same request.
+ AwsException mixed = assertThrows(AwsException.class, () -> service.describeLaunchTemplates(
+ "us-east-1", List.of(), List.of("present-template", "absent-template"), Map.of()));
+ assertEquals("InvalidLaunchTemplateName.NotFoundException", mixed.getErrorCode());
+
+ AwsException byId = assertThrows(AwsException.class, () -> service.describeLaunchTemplates(
+ "us-east-1", List.of("lt-0000000000000dead"), List.of(), Map.of()));
+ assertEquals("InvalidLaunchTemplateId.NotFound", byId.getErrorCode());
+
+ // Another region does not hold the template, so the same name is missing there.
+ AwsException otherRegion = assertThrows(AwsException.class, () -> service.describeLaunchTemplates(
+ "eu-west-1", List.of(), List.of("present-template"), Map.of()));
+ assertEquals("InvalidLaunchTemplateName.NotFoundException", otherRegion.getErrorCode());
+
+ // A filter that matches nothing still returns an empty list rather than an error.
+ assertTrue(service.describeLaunchTemplates("us-east-1", List.of(), List.of(),
+ Map.of("launch-template-name", List.of("no-such-template"))).isEmpty());
+ assertTrue(service.describeLaunchTemplates("us-east-1", List.of(present.getLaunchTemplateId()),
+ List.of(), Map.of("launch-template-name", List.of("no-such-template"))).isEmpty());
+
+ // AutoScaling reports its own ValidationError for an unresolved template, so the version
+ // lookup it goes through keeps answering with an empty list instead of raising NotFound.
+ assertTrue(service.describeLaunchTemplateVersions(
+ "us-east-1", null, "absent-template", List.of()).isEmpty());
+ }
+
+ @Test
+ void missingLaunchTemplateIdReportsTheSameCodeWhicheverCallLooksItUp() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory());
+
+ // The mutating paths resolve the template through findLaunchTemplate rather than
+ // describeLaunchTemplates, and used to spell the same condition
+ // InvalidLaunchTemplateId.NotFoundException.
+ AwsException modify = assertThrows(AwsException.class, () -> service.modifyLaunchTemplate(
+ "us-east-1", "lt-0000000000000dead", null, "1"));
+ assertEquals("InvalidLaunchTemplateId.NotFound", modify.getErrorCode());
+ assertEquals(400, modify.getHttpStatus());
+
+ AwsException delete = assertThrows(AwsException.class, () -> service.deleteLaunchTemplate(
+ "us-east-1", "lt-0000000000000dead", null));
+ assertEquals("InvalidLaunchTemplateId.NotFound", delete.getErrorCode());
+
+ // A missing name keeps the Exception suffix EC2 uses on that one.
+ AwsException byName = assertThrows(AwsException.class, () -> service.deleteLaunchTemplate(
+ "us-east-1", null, "absent-template"));
+ assertEquals("InvalidLaunchTemplateName.NotFoundException", byName.getErrorCode());
+ }
+
@Test
void launchTemplateVersionInheritsOmittedFieldsFromRequestedSourceVersion() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),