mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): replace changed launch configurations safely (#8599)
* fix(cloudformation): replace changed launch configurations safely * fix(autoscaling): guard launch configuration replacement races * fix(cloudformation): reuse replacement decisions and valid fixtures
This commit is contained in:
1 parent
43363c0f8d
commit
8ad3e2b419
9 files changed
+794
-136
No files matched your search
+14
-3
@@ -62,16 +62,27 @@ class AutoScalingCapacityAccountLockIntegrationTest {
|
||||
workers.shutdownNow();
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
try {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> service.deleteAutoScalingGroup(REGION, name, true));
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> delete(REGION, name));
|
||||
} finally {
|
||||
RequestScopes.runAs(otherAccount, otherRegion,
|
||||
() -> service.deleteAutoScalingGroup(otherRegion, name, true));
|
||||
() -> delete(otherRegion, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void delete(String region, String name) {
|
||||
if (!service.describeAutoScalingGroups(region, List.of(name)).isEmpty()) {
|
||||
service.deleteAutoScalingGroup(region, name, true);
|
||||
}
|
||||
if (!service.describeLaunchConfigurations(region, List.of(name)).isEmpty()) {
|
||||
service.deleteLaunchConfiguration(region, name);
|
||||
}
|
||||
}
|
||||
|
||||
private AutoScalingGroup create(String region, String name) {
|
||||
service.createAutoScalingGroup(region, name, "unused-capacity-lock-source", null, null, null, null,
|
||||
service.createLaunchConfiguration(region, name, null, "ami-12345678", "t3.micro",
|
||||
null, List.of(), null, null, null);
|
||||
service.createAutoScalingGroup(region, name, name, null, null, null, null,
|
||||
0, 1, 0, 300, List.of(region + "a"), List.of(), List.of(), List.of(), "EC2", 0,
|
||||
List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
return service.describeAutoScalingGroups(region, List.of(name)).getFirst();
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package io.floci.aws.services.autoscaling;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.autoscaling.model.AsgOptionalFields;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Subnet;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AutoScalingLaunchConfigurationAttachmentTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private AutoScalingService service;
|
||||
private Ec2Service ec2;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AutoScalingService();
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
service.createAutoScalingGroup(REGION, "existing", null, "lt-original", null, "1", null,
|
||||
0, 0, 0, 300, List.of(), List.of(), List.of(), List.of(),
|
||||
"EC2", 0, List.of(), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
service.createLaunchConfiguration(REGION, "configuration", null, "ami-test", "t3.micro",
|
||||
null, List.of(), null, null, null);
|
||||
ec2 = mock(Ec2Service.class);
|
||||
service.ec2Service = ec2;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void deletionWaitsForAttachmentAlreadyPastValidation(boolean update) throws Exception {
|
||||
CountDownLatch validated = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
AtomicReference<Thread> deletingThread = new AtomicReference<>();
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-test");
|
||||
subnet.setAvailabilityZone(REGION + "a");
|
||||
when(ec2.describeSubnets(eq(REGION), eq(List.of("subnet-test")), isNull())).thenAnswer(invocation -> {
|
||||
validated.countDown();
|
||||
assertTrue(release.await(10, TimeUnit.SECONDS), "Attachment was not released");
|
||||
return List.of(subnet);
|
||||
});
|
||||
ExecutorService workers = Executors.newFixedThreadPool(3);
|
||||
try {
|
||||
Future<?> attachment = workers.submit(() -> attachConfiguration(update));
|
||||
assertTrue(validated.await(5, TimeUnit.SECONDS));
|
||||
Future<AwsException> deletion = workers.submit(() -> {
|
||||
deletingThread.set(Thread.currentThread());
|
||||
return assertThrows(AwsException.class,
|
||||
() -> service.deleteLaunchConfiguration(REGION, "configuration"));
|
||||
});
|
||||
ThreadStates.awaitBlockedOrDone(deletingThread, deletion);
|
||||
assertEquals(Thread.State.BLOCKED, deletingThread.get().getState());
|
||||
assertFalse(deletion.isDone(), "Deletion must wait for the attachment it raced");
|
||||
workers.submit(() -> {
|
||||
service.createLaunchConfiguration("us-west-2", "configuration", null, "ami-test", "t3.micro",
|
||||
null, List.of(), null, null, null);
|
||||
service.deleteLaunchConfiguration("us-west-2", "configuration");
|
||||
}).get(5, TimeUnit.SECONDS);
|
||||
release.countDown();
|
||||
attachment.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("ResourceInUse", deletion.get(5, TimeUnit.SECONDS).getErrorCode());
|
||||
assertEquals(1, service.describeLaunchConfigurations(REGION, List.of("configuration")).size());
|
||||
String groupName = update ? "existing" : "created";
|
||||
assertEquals("configuration", service.describeAutoScalingGroups(REGION, List.of(groupName))
|
||||
.getFirst().getLaunchConfigurationName());
|
||||
} finally {
|
||||
release.countDown();
|
||||
workers.shutdownNow();
|
||||
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void attachmentRejectsAConfigurationDeletedBeforeValidation(boolean update) {
|
||||
service.deleteLaunchConfiguration(REGION, "configuration");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> attachConfiguration(update));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("configuration"));
|
||||
assertTrue(service.describeAutoScalingGroups(REGION, List.of("created")).isEmpty());
|
||||
assertNull(service.describeAutoScalingGroups(REGION, List.of("existing"))
|
||||
.getFirst().getLaunchConfigurationName());
|
||||
verifyNoInteractions(ec2);
|
||||
}
|
||||
|
||||
private void attachConfiguration(boolean update) {
|
||||
if (update) {
|
||||
service.updateAutoScalingGroup(REGION, "existing", "configuration", null, null, null, null,
|
||||
null, null, null, null, List.of(), List.of("subnet-test"),
|
||||
null, null, null, AsgOptionalFields.none());
|
||||
} else {
|
||||
service.createAutoScalingGroup(REGION, "created", "configuration", null, null, null, null,
|
||||
0, 0, 0, 300, List.of(), List.of("subnet-test"), List.of(), List.of(),
|
||||
"EC2", 0, List.of(), Map.of(), Map.of(), AsgOptionalFields.none());
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -192,10 +192,12 @@ class AutoScalingTagPropagationIntegrationTest {
|
||||
void sparseTagsRetainCreateDefaultsUpdateAndDeleteSemantics() {
|
||||
String name = "sparse-tags-" + UUID.randomUUID();
|
||||
try (AutoScalingClient client = AwsTestClients.create(AutoScalingClient.builder(), ACCOUNT, Region.of(REGION))) {
|
||||
client.createLaunchConfiguration(request -> request.launchConfigurationName(name)
|
||||
.imageId("ami-12345678").instanceType("t3.micro"));
|
||||
try {
|
||||
request(ACCOUNT, "autoscaling", "CreateAutoScalingGroup")
|
||||
.formParam("AutoScalingGroupName", name)
|
||||
.formParam("LaunchConfigurationName", "sparse-configuration")
|
||||
.formParam("LaunchConfigurationName", name)
|
||||
.formParam("MinSize", 0).formParam("MaxSize", 1).formParam("DesiredCapacity", 0)
|
||||
.formParam("AvailabilityZones.member.1", REGION + "a")
|
||||
.formParam("Tags.member.3.Key", "existing")
|
||||
@@ -219,8 +221,13 @@ class AutoScalingTagPropagationIntegrationTest {
|
||||
.post("/").then().statusCode(200);
|
||||
assertTrue(describeGroupTags(client, name).isEmpty());
|
||||
} finally {
|
||||
if (!client.describeAutoScalingGroups(r -> r.autoScalingGroupNames(name)).autoScalingGroups().isEmpty()) {
|
||||
client.deleteAutoScalingGroup(r -> r.autoScalingGroupName(name).forceDelete(true));
|
||||
try {
|
||||
if (!client.describeAutoScalingGroups(r -> r.autoScalingGroupNames(name))
|
||||
.autoScalingGroups().isEmpty()) {
|
||||
client.deleteAutoScalingGroup(r -> r.autoScalingGroupName(name).forceDelete(true));
|
||||
}
|
||||
} finally {
|
||||
client.deleteLaunchConfiguration(r -> r.launchConfigurationName(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
|
||||
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
|
||||
import software.amazon.awssdk.services.autoscaling.model.LaunchConfiguration;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationLaunchConfigurationReplacementSdkIntegrationTest {
|
||||
@Test
|
||||
void changedConfigurationReplacesAndReattachesGroupWhileUnchangedConfigurationKeepsIdentity() {
|
||||
try (Scenario scenario = new Scenario()) {
|
||||
scenario.create(template(null, "t3.micro", 1));
|
||||
String original = scenario.physical("Launch");
|
||||
LaunchConfiguration launch = scenario.launch(original);
|
||||
AutoScalingException inUse = assertThrows(AutoScalingException.class, () ->
|
||||
scenario.scaling.deleteLaunchConfiguration(request -> request.launchConfigurationName(original)));
|
||||
assertEquals("ResourceInUse", inUse.awsErrorDetails().errorCode());
|
||||
assertEquals(original, scenario.launch(original).launchConfigurationName());
|
||||
assertEquals("required", launch.metadataOptions().httpTokensAsString());
|
||||
assertEquals("/dev/xvda", launch.blockDeviceMappings().getFirst().deviceName());
|
||||
assertEquals(150, launch.blockDeviceMappings().getFirst().ebs().volumeSize());
|
||||
assertEquals("gp3", launch.blockDeviceMappings().getFirst().ebs().volumeType());
|
||||
assertTrue(launch.blockDeviceMappings().getFirst().ebs().encrypted());
|
||||
assertTrue(launch.blockDeviceMappings().getFirst().ebs().deleteOnTermination());
|
||||
|
||||
scenario.update(template(null, "t3.micro", 2), "UPDATE_COMPLETE");
|
||||
assertEquals(original, scenario.physical("Launch"));
|
||||
scenario.update(template(null, "t3.small", 2), "UPDATE_COMPLETE");
|
||||
String replacement = scenario.physical("Launch");
|
||||
assertNotEquals(original, replacement);
|
||||
assertEquals("t3.small", scenario.launch(replacement).instanceType());
|
||||
assertFalse(scenario.scaling.describeLaunchConfigurations().launchConfigurations().stream()
|
||||
.anyMatch(item -> original.equals(item.launchConfigurationName())));
|
||||
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
|
||||
request.autoScalingGroupNames(scenario.physical("Group")))
|
||||
.autoScalingGroups().getFirst().launchConfigurationName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitNameReplacementRequiresNewNameAndPreservesOriginalOnRefusal() {
|
||||
try (Scenario scenario = new Scenario()) {
|
||||
String original = scenario.name + "-named";
|
||||
scenario.create(template(original, "t3.micro", 1));
|
||||
scenario.update(template(original, "t3.small", 1), "UPDATE_ROLLBACK_COMPLETE");
|
||||
assertEquals(original, scenario.physical("Launch"));
|
||||
assertEquals("t3.micro", scenario.launch(original).instanceType());
|
||||
assertEquals(original, scenario.scaling.describeAutoScalingGroups(request ->
|
||||
request.autoScalingGroupNames(scenario.physical("Group")))
|
||||
.autoScalingGroups().getFirst().launchConfigurationName());
|
||||
String replacement = original + "-next";
|
||||
scenario.update(template(replacement, "t3.small", 1), "UPDATE_COMPLETE");
|
||||
assertEquals(replacement, scenario.physical("Launch"));
|
||||
assertEquals("t3.small", scenario.launch(replacement).instanceType());
|
||||
assertFalse(scenario.scaling.describeLaunchConfigurations().launchConfigurations().stream()
|
||||
.anyMatch(item -> original.equals(item.launchConfigurationName())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void parameterChangesReplaceConfigurationsUsingThePreviousStackValues() {
|
||||
try (Scenario scenario = new Scenario()) {
|
||||
String initial = parameterTemplate(1);
|
||||
scenario.create(initial);
|
||||
String original = scenario.physical("Launch");
|
||||
scenario.update(parameterTemplate(2), "UPDATE_COMPLETE");
|
||||
assertEquals(original, scenario.physical("Launch"));
|
||||
|
||||
scenario.cfn.updateStack(request -> request.stackName(scenario.name).templateBody(parameterTemplate(2))
|
||||
.parameters(parameter -> parameter.parameterKey("InstanceType").parameterValue("t3.small")));
|
||||
CfnStackWaits.awaitStatus(scenario.cfn, scenario.name, "UPDATE_COMPLETE");
|
||||
String replacement = scenario.physical("Launch");
|
||||
assertNotEquals(original, replacement);
|
||||
assertEquals("t3.small", scenario.launch(replacement).instanceType());
|
||||
assertTrue(scenario.scaling.describeLaunchConfigurations(request ->
|
||||
request.launchConfigurationNames(original)).launchConfigurations().isEmpty());
|
||||
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
|
||||
request.autoScalingGroupNames(scenario.physical("Group")))
|
||||
.autoScalingGroups().getFirst().launchConfigurationName());
|
||||
|
||||
scenario.cfn.updateStack(request -> request.stackName(scenario.name).templateBody(parameterTemplate(3))
|
||||
.parameters(parameter -> parameter.parameterKey("InstanceType").usePreviousValue(true)));
|
||||
CfnStackWaits.awaitStatus(scenario.cfn, scenario.name, "UPDATE_COMPLETE");
|
||||
assertEquals(replacement, scenario.physical("Launch"));
|
||||
assertEquals("t3.small", scenario.launch(replacement).instanceType());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addingUserDataReplacesAndReattachesTheGroup() {
|
||||
try (Scenario scenario = new Scenario()) {
|
||||
scenario.create(template(null, "t3.micro", 1));
|
||||
String original = scenario.physical("Launch");
|
||||
String userData = "IyEvYmluL3NoCmVjaG8gcmVhZHkK";
|
||||
String updated = template(null, "t3.micro", 2)
|
||||
.replace("\"ImageId\":", "\"UserData\": \"" + userData + "\",\n \"ImageId\":");
|
||||
|
||||
scenario.update(updated, "UPDATE_COMPLETE");
|
||||
|
||||
String replacement = scenario.physical("Launch");
|
||||
assertNotEquals(original, replacement);
|
||||
assertEquals(userData, scenario.launch(replacement).userData());
|
||||
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
|
||||
request.autoScalingGroupNames(scenario.physical("Group")))
|
||||
.autoScalingGroups().getFirst().launchConfigurationName());
|
||||
assertTrue(scenario.scaling.describeLaunchConfigurations(request ->
|
||||
request.launchConfigurationNames(original)).launchConfigurations().isEmpty());
|
||||
|
||||
scenario.update(updated.replace("\"MaxSize\": \"2\"", "\"MaxSize\": \"3\""), "UPDATE_COMPLETE");
|
||||
assertEquals(replacement, scenario.physical("Launch"));
|
||||
assertEquals(userData, scenario.launch(replacement).userData());
|
||||
}
|
||||
}
|
||||
|
||||
private static String parameterTemplate(int max) {
|
||||
return template(null, "t3.micro", max)
|
||||
.replace("\"Resources\": {", """
|
||||
"Parameters": {"InstanceType": {"Type": "String", "Default": "t3.micro"}},
|
||||
"Resources": {""")
|
||||
.replace("\"InstanceType\": \"t3.micro\"", "\"InstanceType\": {\"Ref\": \"InstanceType\"}");
|
||||
}
|
||||
|
||||
private static String template(String name, String instanceType, int max) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Launch": {
|
||||
"Type": "AWS::AutoScaling::LaunchConfiguration",
|
||||
"Properties": {
|
||||
%s
|
||||
"ImageId": "ami-12345678",
|
||||
"InstanceType": "%s",
|
||||
"MetadataOptions": {
|
||||
"HttpTokens": "required",
|
||||
"HttpEndpoint": "enabled"
|
||||
},
|
||||
"BlockDeviceMappings": [
|
||||
{
|
||||
"DeviceName": "/dev/xvda",
|
||||
"Ebs": {
|
||||
"VolumeSize": 150,
|
||||
"VolumeType": "gp3",
|
||||
"Encrypted": true,
|
||||
"DeleteOnTermination": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"Group": {
|
||||
"Type": "AWS::AutoScaling::AutoScalingGroup",
|
||||
"Properties": {
|
||||
"LaunchConfigurationName": {"Ref": "Launch"},
|
||||
"MinSize": "0",
|
||||
"MaxSize": "%s",
|
||||
"DesiredCapacity": "0",
|
||||
"AvailabilityZones": ["us-east-1a"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(name == null ? "" : "\"LaunchConfigurationName\": \"" + name + "\",", instanceType, max);
|
||||
}
|
||||
|
||||
private static final class Scenario implements AutoCloseable {
|
||||
private final String name = "lc-replacement-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
private final CloudFormationClient cfn;
|
||||
private final AutoScalingClient scaling;
|
||||
private boolean created;
|
||||
|
||||
private Scenario() {
|
||||
URI endpoint = URI.create("http://127.0.0.1:" + RestAssured.port);
|
||||
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create("846023460246", "test"));
|
||||
cfn = CloudFormationClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(credentials).httpClientBuilder(UrlConnectionHttpClient.builder()).build();
|
||||
scaling = AutoScalingClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(credentials).httpClientBuilder(UrlConnectionHttpClient.builder()).build();
|
||||
}
|
||||
|
||||
private void create(String template) {
|
||||
created = true;
|
||||
CfnStackWaits.createStack(cfn, name, template, "CREATE_COMPLETE");
|
||||
}
|
||||
|
||||
private void update(String template, String expected) {
|
||||
CfnStackWaits.updateStack(cfn, name, template, expected);
|
||||
}
|
||||
|
||||
private String physical(String logicalId) {
|
||||
return cfn.describeStackResource(request -> request.stackName(name).logicalResourceId(logicalId))
|
||||
.stackResourceDetail().physicalResourceId();
|
||||
}
|
||||
|
||||
private LaunchConfiguration launch(String physicalId) {
|
||||
return scaling.describeLaunchConfigurations(request -> request.launchConfigurationNames(physicalId))
|
||||
.launchConfigurations().getFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (created) {
|
||||
CfnStackWaits.deleteStack(cfn, name);
|
||||
assertTrue(scaling.describeAutoScalingGroups().autoScalingGroups().stream()
|
||||
.noneMatch(group -> group.autoScalingGroupName().startsWith(name + "-")));
|
||||
assertTrue(scaling.describeLaunchConfigurations().launchConfigurations().stream()
|
||||
.noneMatch(launch -> launch.launchConfigurationName().startsWith(name + "-")));
|
||||
}
|
||||
} finally {
|
||||
scaling.close();
|
||||
cfn.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+165
-3
@@ -15,14 +15,18 @@ import io.floci.aws.services.autoscaling.model.MixedInstancesPolicy;
|
||||
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
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.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -35,6 +39,8 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -345,11 +351,167 @@ class AutoScalingGroupCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationUpdateLeavesTheExistingOneAlone() {
|
||||
// Launch configurations have no update API on real AWS, so a same-named one already on file
|
||||
// must not be re-created.
|
||||
void launchConfigurationPropertyChangeReplacesAndDefersOldDeletion() {
|
||||
StackResource resource = launchConfigurationUpdate("old-lc", false);
|
||||
String replacement = resource.getPhysicalId();
|
||||
assertNotEquals("old-lc", replacement);
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
assertEquals("old-lc", provisioner.updateCleanupPhysicalId(resource));
|
||||
verify(autoScaling, never()).deleteLaunchConfiguration(REGION, "old-lc");
|
||||
provisioner.completeUpdate(resource);
|
||||
verify(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationCleanupRetainsInUseFailureAndRetriesAfterRepair() {
|
||||
StackResource resource = launchConfigurationUpdate("old-lc", false);
|
||||
doThrow(new AwsException("ResourceInUse", "Launch configuration is attached", 400))
|
||||
.when(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
|
||||
UpdateCleanupResult failure = provisioner.completeUpdate(resource);
|
||||
assertFalse(failure.complete());
|
||||
assertEquals("old-lc", failure.previousPhysicalId());
|
||||
assertEquals(1, failure.attempts());
|
||||
doNothing().when(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationDeleteDoesNotHideValidationErrorWhileResourceExists() {
|
||||
LaunchConfiguration existing = new LaunchConfiguration();
|
||||
when(autoScaling.describeLaunchConfigurations(REGION, List.of("existing"))).thenReturn(List.of(existing));
|
||||
doThrow(new AwsException("ValidationError", "Cannot delete an attached launch configuration", 400))
|
||||
.when(autoScaling).deleteLaunchConfiguration(REGION, "existing");
|
||||
assertThrows(AwsException.class, () -> provisioner.delete(LAUNCH_CONFIGURATION, "existing", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationReplacementRollbackRestoresPriorIdentity() {
|
||||
StackResource resource = launchConfigurationUpdate("old-lc", false);
|
||||
String replacement = resource.getPhysicalId();
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
assertEquals("old-lc", resource.getPhysicalId());
|
||||
verify(autoScaling).deleteLaunchConfiguration(REGION, replacement);
|
||||
verify(autoScaling, never()).deleteLaunchConfiguration(REGION, "old-lc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationReplacementRejectsUnchangedExplicitNameBeforeMutation() {
|
||||
AwsException failure = assertThrows(AwsException.class, () -> launchConfigurationUpdate("old-lc", true));
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("Rename old-lc"));
|
||||
verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyList(), any());
|
||||
verify(autoScaling, never()).deleteLaunchConfiguration(anyString(), anyString());
|
||||
}
|
||||
|
||||
private StackResource launchConfigurationUpdate(String oldName, boolean explicit) {
|
||||
ObjectNode before = mapper.createObjectNode().put("ImageId", "ami-1").put("InstanceType", "t3.micro");
|
||||
if (explicit) {
|
||||
before.put("LaunchConfigurationName", oldName);
|
||||
}
|
||||
ObjectNode after = before.deepCopy().put("InstanceType", "t3.small");
|
||||
StackResource resource = resource(LAUNCH_CONFIGURATION, "Lc", oldName);
|
||||
LaunchConfiguration old = new LaunchConfiguration();
|
||||
old.setLaunchConfigurationName(oldName);
|
||||
when(autoScaling.describeLaunchConfigurations(REGION, List.of(oldName))).thenReturn(List.of(old));
|
||||
when(autoScaling.createLaunchConfiguration(anyString(), anyString(), any(), any(), any(), any(),
|
||||
anyList(), any(), any(), any(), any(), anyList(), any())).thenAnswer(invocation -> {
|
||||
LaunchConfiguration created = new LaunchConfiguration();
|
||||
created.setLaunchConfigurationName(invocation.getArgument(1));
|
||||
created.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:new");
|
||||
return created;
|
||||
});
|
||||
ProvisionContext original = ctx(oldName);
|
||||
ProvisionContext update = new ProvisionContext(original.engine(), REGION, "000000000000",
|
||||
"my-stack", oldName, event -> {}, before);
|
||||
provisioner.provision(resource, after, update);
|
||||
return resource;
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationReusesUnchangedInstanceTemplateWithoutExtraSnapshot() {
|
||||
ObjectNode props = instanceProperties();
|
||||
StackResource resource = provisionExistingInstance(props, props.deepCopy(), null, false);
|
||||
assertEquals("my-lc", resource.getPhysicalId());
|
||||
assertTrue(resource.getAttributes().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationRejectsChangedInstanceBeforeMutation() {
|
||||
ObjectNode previous = instanceProperties();
|
||||
provisionExistingInstance(previous.deepCopy().put("InstanceId", "i-changed"), previous, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationRejectsOtherChangedInputsBeforeMutation() {
|
||||
ObjectNode previous = instanceProperties();
|
||||
provisionExistingInstance(previous.deepCopy().put("InstanceType", "t3.small"), previous, null, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationRejectsAddedCreateOnlyInputBeforeMutation() {
|
||||
ObjectNode previous = instanceProperties();
|
||||
ObjectNode current = previous.deepCopy().put("UserData", "IyEvYmluL3NoCmVjaG8gcmVhZHkK");
|
||||
PropertyChanges changes = PropertyChanges.between(LAUNCH_CONFIGURATION, true, previous, current,
|
||||
null, null, false);
|
||||
provisionExistingInstance(current, previous, changes, true);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void launchConfigurationUsesEngineDecisionForReferenceValues(boolean replacement) {
|
||||
ObjectNode previous = instanceProperties();
|
||||
previous.putObject("InstanceId").put("Ref", "SourceInstance");
|
||||
previous.putObject("InstanceType").put("Ref", "InstanceType");
|
||||
PropertyChanges changes = new PropertyChanges(Map.of(), replacement);
|
||||
provisionExistingInstance(instanceProperties(), previous, changes, replacement);
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationRejectsRemovalOfTheInstanceSource() {
|
||||
ObjectNode previous = instanceProperties().put("ImageId", "ami-original");
|
||||
ObjectNode current = previous.deepCopy();
|
||||
current.remove("InstanceId");
|
||||
provisionExistingInstance(current, previous, null, true);
|
||||
}
|
||||
|
||||
private ObjectNode instanceProperties() {
|
||||
return mapper.createObjectNode().put("LaunchConfigurationName", "my-lc")
|
||||
.put("InstanceId", "i-original").put("InstanceType", "t3.micro");
|
||||
}
|
||||
|
||||
private StackResource provisionExistingInstance(ObjectNode current, JsonNode previous,
|
||||
PropertyChanges changes, boolean rejected) {
|
||||
LaunchConfiguration lc = new LaunchConfiguration();
|
||||
lc.setLaunchConfigurationName("my-lc");
|
||||
lc.setImageId("ami-original");
|
||||
lc.setInstanceType("t3.micro");
|
||||
when(autoScaling.describeLaunchConfigurations(REGION, List.of("my-lc"))).thenReturn(List.of(lc));
|
||||
StackResource resource = resource(LAUNCH_CONFIGURATION, "Lc", "my-lc");
|
||||
ProvisionContext original = ctx("my-lc");
|
||||
ProvisionContext context = new ProvisionContext(original.engine(), REGION, "000000000000",
|
||||
"my-stack", "my-lc", event -> {}, previous, changes);
|
||||
if (rejected) {
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource, current, context));
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("Rename my-lc"));
|
||||
assertTrue(resource.getAttributes().isEmpty());
|
||||
} else {
|
||||
provisioner.provision(resource, current, context);
|
||||
}
|
||||
verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
|
||||
any(), any(), anyList(), any(), any(), any(), any(), anyList(), any());
|
||||
verify(autoScaling, never()).deleteLaunchConfiguration(anyString(), anyString());
|
||||
return resource;
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchConfigurationUpdateLeavesTheExistingOneAlone() {
|
||||
// An unchanged legacy configuration keeps its physical identity.
|
||||
LaunchConfiguration lc = new LaunchConfiguration();
|
||||
lc.setLaunchConfigurationName("my-lc");
|
||||
lc.setImageId("ami-2");
|
||||
lc.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:my-lc");
|
||||
when(autoScaling.describeLaunchConfigurations(REGION, List.of("my-lc"))).thenReturn(List.of(lc));
|
||||
StackResource r = resource(LAUNCH_CONFIGURATION, "Lc", "my-lc");
|
||||
|
||||
Reference in new issue
Block a user