mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types (#5503)
* fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types A CidrBlock change, or a tenancy change other than dedicated to default, replaces the VPC, but the provisioner never recorded the displaced one and had no delete arm, so the old VPC was left behind; in-place Tags, EnableDnsSupport and EnableDnsHostnames changes were not snapshotted, so a later failing resource left the VPC changed and reported rollback as not implemented. Ec2VpcCfnProvisioner now follows Ec2NetworkCfnProvisioner: ReplacementCleanup records the displaced VPC and deletes it after the update commits or restores it on rollback; a prior-state snapshot restores DNS attributes, tags and a dedicated-to-default tenancy change on rollback, eagerly when provision itself fails; and a delete arm through CfnDeletes.safeDelete removes the VPC on stack teardown, tolerating only InvalidVpcID.NotFound so stack-external dependents fail the delete with DependencyViolation, as on AWS. * refactor(cloudformation): use the shared CfnRollback.guarded in the VPC provisioner * fix(ec2): count instances and NAT gateways as subnet and VPC dependents DeleteSubnet and DeleteVpc checked subnets, security groups, route tables, ACLs, gateways and endpoints but not the instances and NAT gateways living in a subnet, so a stack teardown could remove a subnet and its VPC out from under an instance launched into it out of band. Both now fail with DependencyViolation while an instance that is not terminated (shutting-down still holds its interface) or a NAT gateway that is not deleted sits in the subnet, as on AWS. The rollback integration test also pins Boom after the VPC with DependsOn so the scenario cannot pass by ordering alone. * fix(cloudformation): keep the VPC and subnet rollback snapshot until the restore succeeds rollbackUpdate removed the in-place snapshot before restoring; a restore that threw left the resource persisted as UPDATE_FAILED with no prior state for a ContinueUpdateRollback retry. Ec2VpcCfnProvisioner and the pre-existing Ec2NetworkCfnProvisioner now restore first and remove after, as the AgentCore provisioner already did. The describeTags loop shared by Ec2Tags.reconcile and the VPC snapshot moves to Ec2Tags.current. * fix(ec2): count standalone network interfaces and interface endpoints as subnet dependents A subnet is pinned by any network interface in it, not only the ones an instance or NAT gateway owns: a standalone interface from CreateNetworkInterface and an interface or Gateway Load Balancer endpoint keep DeleteSubnet at DependencyViolation on AWS too. The endpoint test that deleted a subnet out from under a live endpoint relied on that state being reachable; it now asserts the refusal and that the published interface ids are unchanged. * fix(cloudformation): wait for terminated on instance delete and resolve VPC properties before creating With real containers an instance is still shutting-down when the stack's instance delete returns, so the subnet delete that follows was refused by the new resident check and the stack ended DELETE_FAILED. The instance provisioner now polls until the instance is terminated or gone, as CloudFormation does. The VPC provisioner created the VPC before EnableDnsSupport, EnableDnsHostnames and Tags were resolved, so a resolution failure left it untracked; the resolves now run first, as the subnet provisioner does. Ec2Tags.current drops reserved aws: keys so a rollback snapshot never tries to write one, and the replacement integration test waits in the stack's own region.
This commit is contained in:
1 parent
a318dc7b90
commit
fa682b2d62
14 files changed
+907
-69
No files matched your search
+222
@@ -0,0 +1,222 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The lifecycle of {@code AWS::EC2::VPC} beyond its first create: a changed CidrBlock replaces the
|
||||
* VPC and the displaced one (with the subnet it held) is removed once the update commits, an
|
||||
* in-place tag and DNS change next to a resource that fails the update is rolled back, DeleteStack
|
||||
* removes the VPC together with its subnet, and an instance launched into the subnet out of band
|
||||
* fails that delete with {@code DependencyViolation} until it is terminated.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationVpcReplacementIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/cloudformation/aws4_request";
|
||||
private static final String EC2_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/ec2/aws4_request";
|
||||
|
||||
/** A VPC and a subnet inside it; the subnet's CIDR follows the VPC's second octet. */
|
||||
private static String template(String octet, String name) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Vpc": {
|
||||
"Type": "AWS::EC2::VPC",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.%1$s.0.0/16",
|
||||
"Tags": [{"Key": "Name", "Value": "%2$s"}]
|
||||
}
|
||||
},
|
||||
"Subnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.%1$s.1.0/24"}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"VpcId": {"Value": {"Ref": "Vpc"}},
|
||||
"SubnetId": {"Value": {"Ref": "Subnet"}}
|
||||
}
|
||||
}
|
||||
""".formatted(octet, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* A VPC alone; the second form flips the mutable properties and adds a resource that cannot be
|
||||
* created. Boom depends on the VPC so its failure lands after the in-place change was written.
|
||||
*/
|
||||
private static String rollbackTemplate(boolean changed) {
|
||||
String failing = changed
|
||||
? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\", \"DependsOn\": \"Vpc\","
|
||||
+ " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}"
|
||||
: "";
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Vpc": {
|
||||
"Type": "AWS::EC2::VPC",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.47.0.0/16",
|
||||
"EnableDnsHostnames": %1$s,
|
||||
"Tags": [{"Key": "Name", "Value": "%2$s"}]
|
||||
}
|
||||
}%3$s
|
||||
},
|
||||
"Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}}
|
||||
}
|
||||
""".formatted(changed ? "false" : "true", changed ? "after" : "before", failing);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangedCidrBlockReplacesTheVpcAndTheDisplacedOneIsRemovedOnceTheUpdateCommits() {
|
||||
String stack = "cfn-vpc-replace-" + Long.toString(System.nanoTime(), 36);
|
||||
cloudFormation(stack, "CreateStack", template("45", "first"));
|
||||
Map<String, String> before = outputs(stack, "CREATE_COMPLETE");
|
||||
|
||||
cloudFormation(stack, "UpdateStack", template("46", "second"));
|
||||
|
||||
Map<String, String> after = outputs(stack, "UPDATE_COMPLETE");
|
||||
assertFalse(before.get("VpcId").equals(after.get("VpcId")), "a changed CidrBlock must replace the VPC");
|
||||
assertFalse(before.get("SubnetId").equals(after.get("SubnetId")), "the subnet follows its VPC");
|
||||
String vpcs = ec2("DescribeVpcs");
|
||||
assertFalse(vpcs.contains(before.get("VpcId")), "the displaced VPC must be gone: " + vpcs);
|
||||
assertTrue(vpcs.contains(after.get("VpcId")));
|
||||
String replacement = ec2("DescribeVpcs", Map.of("VpcId.1", after.get("VpcId")));
|
||||
assertTrue(replacement.contains("<cidrBlock>10.46.0.0/16</cidrBlock>"), replacement);
|
||||
assertTrue(replacement.contains("<key>Name</key>") && replacement.contains("<value>second</value>"),
|
||||
"the replacement carries the stack's tags: " + replacement);
|
||||
assertFalse(ec2("DescribeSubnets").contains(before.get("SubnetId")), "the displaced subnet must be gone");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
|
||||
assertFalse(ec2("DescribeVpcs").contains(after.get("VpcId")), "stack delete must remove the VPC");
|
||||
assertFalse(ec2("DescribeSubnets").contains(after.get("SubnetId")), "stack delete must remove the subnet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInPlaceChangeNextToAFailingResourceIsRolledBack() {
|
||||
String stack = "cfn-vpc-rollback-" + Long.toString(System.nanoTime(), 36);
|
||||
cloudFormation(stack, "CreateStack", rollbackTemplate(false));
|
||||
String vpcId = outputs(stack, "CREATE_COMPLETE").get("VpcId");
|
||||
assertTrue(describeVpc(vpcId).contains("<value>before</value>"));
|
||||
assertEquals("true", dnsHostnames(vpcId));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", rollbackTemplate(true));
|
||||
|
||||
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
String vpc = describeVpc(vpcId);
|
||||
assertTrue(vpc.contains("<value>before</value>") && !vpc.contains("<value>after</value>"),
|
||||
"the VPC's prior tag must be back: " + vpc);
|
||||
assertEquals("true", dnsHostnames(vpcId), "the VPC's prior EnableDnsHostnames must be back");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
|
||||
assertFalse(ec2("DescribeVpcs").contains(vpcId), "stack delete must remove the VPC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceLaunchedIntoTheSubnetOutOfBandFailsTheDeleteUntilItIsTerminated() {
|
||||
String stack = "cfn-vpc-resident-" + Long.toString(System.nanoTime(), 36);
|
||||
cloudFormation(stack, "CreateStack", template("48", "resident"));
|
||||
Map<String, String> created = outputs(stack, "CREATE_COMPLETE");
|
||||
String subnetId = created.get("SubnetId");
|
||||
String instanceId = XmlPath.from(ec2("RunInstances", Map.of(
|
||||
"ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro",
|
||||
"MinCount", "1", "MaxCount", "1", "SubnetId", subnetId)))
|
||||
.getString("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
|
||||
CfnStackWaits.StackState failed = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);
|
||||
assertEquals("DELETE_FAILED", failed.status(), failed.reason());
|
||||
// The event carries the EC2 DependencyViolation message; the engine records the message, not the code.
|
||||
String subnetFailure = XmlPath.from(cloudFormationQuery(stack, "DescribeStackEvents"))
|
||||
.getString("DescribeStackEventsResponse.DescribeStackEventsResult.StackEvents.member"
|
||||
+ ".find { it.LogicalResourceId == 'Subnet' && it.ResourceStatus == 'DELETE_FAILED' }"
|
||||
+ ".ResourceStatusReason");
|
||||
assertEquals("The subnet '" + subnetId + "' has dependencies and cannot be deleted.", subnetFailure,
|
||||
"the subnet's delete must report the resident instance");
|
||||
assertTrue(ec2("DescribeSubnets").contains(subnetId), "the pinned subnet must still exist");
|
||||
assertTrue(ec2("DescribeVpcs").contains(created.get("VpcId")), "the VPC behind it must still exist");
|
||||
|
||||
ec2("TerminateInstances", Map.of("InstanceId.1", instanceId));
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
|
||||
CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);
|
||||
assertFalse(ec2("DescribeSubnets").contains(subnetId), "stack delete must remove the subnet");
|
||||
assertFalse(ec2("DescribeVpcs").contains(created.get("VpcId")), "stack delete must remove the VPC");
|
||||
}
|
||||
|
||||
private static String describeVpc(String vpcId) {
|
||||
return ec2("DescribeVpcs", Map.of("VpcId.1", vpcId));
|
||||
}
|
||||
|
||||
private static String dnsHostnames(String vpcId) {
|
||||
return XmlPath.from(ec2("DescribeVpcAttribute", Map.of("VpcId", vpcId, "Attribute", "enableDnsHostnames")))
|
||||
.getString("DescribeVpcAttributeResponse.enableDnsHostnames.value");
|
||||
}
|
||||
|
||||
private static Map<String, String> outputs(String stack, String expectedStatus) {
|
||||
return XmlParser.extractPairs(describeStacks(stack, expectedStatus), "Outputs", "OutputKey", "OutputValue");
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String templateBody) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack);
|
||||
if (templateBody != null) {
|
||||
request.formParam("TemplateBody", templateBody);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stack, String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String cloudFormationQuery(String stack, String action) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String ec2(String action) {
|
||||
return ec2(action, Map.of());
|
||||
}
|
||||
|
||||
private static String ec2(String action, Map<String, String> params) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", EC2_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2016-11-15");
|
||||
params.forEach(request::formParam);
|
||||
return request.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
}
|
||||
+44
@@ -208,6 +208,50 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
assertEquals("DependencyViolation", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWaitsUntilTheInstanceIsTerminated() {
|
||||
provisioner.terminatePollMillis = 1L;
|
||||
Instance shuttingDown = new Instance();
|
||||
shuttingDown.setInstanceId("i-1");
|
||||
shuttingDown.setState(InstanceState.shuttingDown());
|
||||
Instance terminated = new Instance();
|
||||
terminated.setInstanceId("i-1");
|
||||
terminated.setState(InstanceState.terminated());
|
||||
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
|
||||
.thenReturn(List.of(reservationOf(shuttingDown)))
|
||||
.thenReturn(List.of(reservationOf(shuttingDown)))
|
||||
.thenReturn(List.of(reservationOf(terminated)));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "i-1", "us-east-1"));
|
||||
|
||||
InOrder order = inOrder(ec2);
|
||||
order.verify(ec2).terminateInstances("us-east-1", List.of("i-1"));
|
||||
order.verify(ec2, times(3)).describeInstances("us-east-1", List.of("i-1"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTreatsAnInstanceGoneAfterTerminateAsTerminated() {
|
||||
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
|
||||
.thenThrow(new AwsException("InvalidInstanceID.NotFound", "gone", 400));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, "i-1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFailsWhenTheInstanceNeverReachesTerminated() {
|
||||
provisioner.terminateTimeoutMillis = 20L;
|
||||
provisioner.terminatePollMillis = 1L;
|
||||
Instance shuttingDown = new Instance();
|
||||
shuttingDown.setInstanceId("i-1");
|
||||
shuttingDown.setState(InstanceState.shuttingDown());
|
||||
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
|
||||
.thenReturn(List.of(reservationOf(shuttingDown)));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(TYPE, "i-1", "us-east-1"));
|
||||
assertTrue(failure.getMessage().contains("Instance i-1 did not reach terminated"), failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithoutACreateOnlyChangeReusesTheInstance() throws Exception {
|
||||
Instance i1 = new Instance();
|
||||
|
||||
+19
@@ -296,6 +296,25 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatThrowsKeepsTheSnapshotForTheRetry() {
|
||||
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(subnet()));
|
||||
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID, "VpcId", VPC_ID, "AvailabilityZone", "us-east-1a"));
|
||||
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24")
|
||||
.put("AvailabilityZone", "us-east-1a").put("MapPublicIpOnLaunch", true);
|
||||
provisioner.provision(r, props, ctx(SUBNET_ID));
|
||||
String snapshot = r.getAttributes().get(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR);
|
||||
assertTrue(snapshot != null, "the prior MapPublicIpOnLaunch is snapshotted");
|
||||
doThrow(new AwsException("InternalError", "ec2 is down", 500))
|
||||
.when(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
|
||||
|
||||
assertEquals("InternalError", failure.getErrorCode());
|
||||
assertEquals(snapshot, r.getAttributes().get(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR),
|
||||
"a failed restore keeps the snapshot for a ContinueUpdateRollback retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedSubnetWhoseTemplateCidrHasHostBitsIsKept() {
|
||||
Subnet current = subnet();
|
||||
|
||||
+206
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
@@ -19,14 +20,20 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
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.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -89,10 +96,19 @@ class Ec2VpcCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private StackResource provision(String contextPriorId, String resourcePhysicalId, String json) {
|
||||
return provision(contextPriorId, resourcePhysicalId, Map.of(), json);
|
||||
}
|
||||
|
||||
private StackResource provision(String priorPhysicalId, Map<String, String> priorAttributes, String json) {
|
||||
return provision(priorPhysicalId, priorPhysicalId, priorAttributes, json);
|
||||
}
|
||||
|
||||
private StackResource provision(String contextPriorId, String resourcePhysicalId, Map<String, String> priorAttributes, String json) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Vpc");
|
||||
r.setResourceType("AWS::EC2::VPC");
|
||||
r.setPhysicalId(resourcePhysicalId);
|
||||
r.getAttributes().putAll(priorAttributes);
|
||||
ProvisionContext ctx =
|
||||
new ProvisionContext(engine, REGION, "000000000000", "my-stack", contextPriorId);
|
||||
provisioner.provision(r, props(json), ctx);
|
||||
@@ -215,7 +231,7 @@ class Ec2VpcCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangedCidrBlockCreatesAReplacement() {
|
||||
void aChangedCidrBlockCreatesAReplacementAndTheDisplacedVpcIsDeletedOnceTheUpdateCommits() {
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
|
||||
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
|
||||
stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));
|
||||
@@ -225,6 +241,13 @@ class Ec2VpcCfnProvisionerTest {
|
||||
|
||||
verify(ec2).createVpc(REGION, "10.1.0.0/16", false, false, "default");
|
||||
assertEquals("vpc-replaced", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r), "the stack enters UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
|
||||
assertEquals("vpc-existing", provisioner.updateCleanupPhysicalId(r));
|
||||
|
||||
assertTrue(provisioner.completeUpdate(r).complete());
|
||||
verify(ec2).deleteVpc(REGION, "vpc-existing");
|
||||
provisioner.clearUpdate(r);
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -237,6 +260,7 @@ class Ec2VpcCfnProvisionerTest {
|
||||
{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default"}""");
|
||||
assertEquals("vpc-existing", kept.getPhysicalId());
|
||||
verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "default");
|
||||
assertFalse(provisioner.hasReplacementUpdate(kept));
|
||||
|
||||
// Now a default VPC asked to become dedicated: the only in-place direction is dedicated->default.
|
||||
dedicated.setInstanceTenancy("default");
|
||||
@@ -245,6 +269,187 @@ class Ec2VpcCfnProvisionerTest {
|
||||
{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "dedicated"}""");
|
||||
assertEquals("vpc-replaced", replaced.getPhysicalId());
|
||||
verify(ec2).createVpc(eq(REGION), eq("10.0.0.0/16"), eq(false), eq(false), eq("dedicated"));
|
||||
assertEquals("vpc-existing", provisioner.updateCleanupPhysicalId(replaced), "the displaced VPC is owed a delete");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRolledBackReplacementDeletesTheNewVpcAndNamesThePriorOneAgain() {
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
|
||||
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
|
||||
stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));
|
||||
StackResource r = provision("vpc-existing", Map.of("VpcId", "vpc-existing", "CidrBlock", "10.0.0.0/16"), """
|
||||
{"CidrBlock": "10.1.0.0/16"}""");
|
||||
assertEquals("10.1.0.0/16", r.getAttributes().get("CidrBlock"));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2).deleteVpc(REGION, "vpc-replaced");
|
||||
verify(ec2, never()).deleteVpc(REGION, "vpc-existing");
|
||||
assertEquals("vpc-existing", r.getPhysicalId());
|
||||
assertEquals("vpc-existing", r.getAttributes().get("VpcId"));
|
||||
assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock"), "Fn::GetAtt answers the prior VPC again");
|
||||
assertFalse(provisioner.hasReplacementUpdate(r), "nothing is owed a delete once the prior VPC stands again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInPlaceChangeIsRolledBackToThePriorDnsAttributesTagsAndTenancy() {
|
||||
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
|
||||
existing.setInstanceTenancy("dedicated");
|
||||
existing.setEnableDnsSupport(true);
|
||||
existing.setEnableDnsHostnames(false);
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
|
||||
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))
|
||||
.thenReturn(List.of(Map.of("key", "Name", "value", "old"), Map.of("key", "team", "value", "net")))
|
||||
// The snapshot reads the prior set once; every later read sees what the update wrote.
|
||||
.thenReturn(List.of(Map.of("key", "Name", "value", "new"), Map.of("key", "env", "value", "test")));
|
||||
|
||||
StackResource r = provision("vpc-existing", """
|
||||
{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default", "EnableDnsHostnames": true,
|
||||
"Tags": [{"Key": "Name", "Value": "new"}, {"Key": "env", "Value": "test"}]}""");
|
||||
assertTrue(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR), "the prior state is snapshotted");
|
||||
verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "true");
|
||||
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new", "env=test")));
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");
|
||||
verify(ec2, times(2)).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsSupport", "true");
|
||||
verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("env=test")));
|
||||
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=old", "team=net")));
|
||||
verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "dedicated");
|
||||
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestoreThatThrowsKeepsTheSnapshotForTheRetry() {
|
||||
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
|
||||
existing.setEnableDnsSupport(true);
|
||||
existing.setEnableDnsHostnames(false);
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
|
||||
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of());
|
||||
StackResource r = provision("vpc-existing", """
|
||||
{"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true}""");
|
||||
String snapshot = r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR);
|
||||
assertTrue(snapshot != null, "the prior state is snapshotted");
|
||||
doThrow(new AwsException("InternalError", "ec2 is down", 500))
|
||||
.when(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
|
||||
|
||||
assertEquals("InternalError", failure.getErrorCode());
|
||||
assertEquals(snapshot, r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR),
|
||||
"a failed restore keeps the snapshot for a ContinueUpdateRollback retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnchangedReuseLeavesNoSnapshotAndRollsBackAsComplete() {
|
||||
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
|
||||
existing.setEnableDnsSupport(true);
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
|
||||
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))
|
||||
.thenReturn(List.of(Map.of("key", "Name", "value", "same")));
|
||||
|
||||
StackResource r = provision("vpc-existing", """
|
||||
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "same"}]}""");
|
||||
|
||||
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
verify(ec2, never()).deleteTags(any(), any(), any());
|
||||
verify(ec2, never()).modifyVpcTenancy(any(), any(), any());
|
||||
verify(ec2, never()).deleteVpc(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completingOrClearingAnUpdateDropsTheSnapshot() {
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::EC2::VPC");
|
||||
r.getAttributes().put(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}");
|
||||
provisioner.completeUpdate(r);
|
||||
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
|
||||
r.getAttributes().put(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}");
|
||||
provisioner.clearUpdate(r);
|
||||
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedStepOnAReusedVpcRestoresTheSnapshotBeforeTheFailurePropagates() {
|
||||
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
|
||||
existing.setEnableDnsSupport(true);
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
|
||||
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provision("vpc-existing", """
|
||||
{"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true, "Tags": [{"Key": "k", "Value": "v"}]}"""));
|
||||
|
||||
assertEquals("TagLimitExceeded", e.getErrorCode());
|
||||
verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");
|
||||
verify(ec2, never()).deleteVpc(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedStepAfterACreateDeletesTheVpcAgain() {
|
||||
stubCreate(vpc("vpc-new", "10.0.0.0/16"));
|
||||
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
|
||||
|
||||
assertThrows(AwsException.class, () -> provision(null, """
|
||||
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "k", "Value": "v"}]}"""));
|
||||
|
||||
verify(ec2).deleteVpc(REGION, "vpc-new");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagResolutionFailureHappensBeforeTheVpcIsCreated() {
|
||||
// A missing Fn::ImportValue fails resolution; the VPC must not exist by then, or it would
|
||||
// sit outside the rollback guard and leak.
|
||||
when(engine.resolveNode(argThat(node -> node != null && node.isArray())))
|
||||
.thenThrow(new AwsException("ValidationError", "No export named Shared-Tag found", 400));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> provision(null, """
|
||||
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "k", "Value": {"Fn::ImportValue": "Shared-Tag"}}]}"""));
|
||||
|
||||
assertEquals("ValidationError", e.getErrorCode());
|
||||
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), anyString());
|
||||
verify(ec2, never()).deleteVpc(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservedAwsTagsAreNeverSnapshottedNorWrittenBack() {
|
||||
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
|
||||
existing.setEnableDnsSupport(true);
|
||||
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
|
||||
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of(
|
||||
Map.of("key", "aws:cloudformation:stack-name", "value", "my-stack"),
|
||||
Map.of("key", "Name", "value", "old")));
|
||||
|
||||
StackResource r = provision("vpc-existing", """
|
||||
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "new"}]}""");
|
||||
|
||||
String snapshot = r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR);
|
||||
assertTrue(snapshot.contains("\"Name\":\"old\""), snapshot);
|
||||
assertFalse(snapshot.contains("aws:cloudformation"), snapshot);
|
||||
verify(ec2, never()).deleteTags(any(), any(), any());
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(r));
|
||||
|
||||
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new")));
|
||||
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=old")));
|
||||
verify(ec2, never()).createTags(eq(REGION), any(), argThat(actual -> actual != null
|
||||
&& actual.stream().anyMatch(t -> t.getKey().startsWith("aws:"))));
|
||||
verify(ec2, never()).deleteTags(eq(REGION), any(), argThat(actual -> actual != null
|
||||
&& actual.stream().anyMatch(t -> t.getKey().startsWith("aws:"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesOnlyAVpcThatIsAlreadyGone() {
|
||||
doThrow(new AwsException("InvalidVpcID.NotFound", "does not exist", 400)).when(ec2).deleteVpc(REGION, "vpc-gone");
|
||||
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::VPC", "vpc-gone", REGION));
|
||||
|
||||
doThrow(new AwsException("DependencyViolation", "has dependencies", 400)).when(ec2).deleteVpc(REGION, "vpc-busy");
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisioner.delete("AWS::EC2::VPC", "vpc-busy", REGION));
|
||||
assertEquals("DependencyViolation", e.getErrorCode(), "a VPC with dependents outside the stack fails the delete, as on AWS");
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::VPC", null, REGION));
|
||||
verify(ec2, times(2)).deleteVpc(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ec2.model.KeyPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceAssociation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceListResult;
|
||||
@@ -410,6 +411,123 @@ class Ec2ServiceTest {
|
||||
service.deleteVpc(region, vpcId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetFailsUntilItsInstanceIsTerminated() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.81.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId();
|
||||
Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), subnetId, null, List.of(), null, null).getInstances().getFirst();
|
||||
|
||||
AwsException running = assertThrows(AwsException.class, () -> service.deleteSubnet(region, subnetId));
|
||||
assertEquals("DependencyViolation", running.getErrorCode());
|
||||
assertEquals("The subnet '" + subnetId + "' has dependencies and cannot be deleted.", running.getMessage());
|
||||
|
||||
// Still holds its network interface while shutting down, so the subnet stays pinned.
|
||||
instance.setState(InstanceState.shuttingDown());
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
instance.setState(InstanceState.terminated());
|
||||
service.deleteSubnet(region, subnetId);
|
||||
assertTrue(service.describeSubnets(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetFailsUntilItsNatGatewayIsDeleted() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.82.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId();
|
||||
NatGateway natGateway = service.createNatGateway(region, subnetId, null, "private", List.of());
|
||||
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
// Still holds its address while deleting, so the subnet stays pinned.
|
||||
natGateway.setState("deleting");
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
service.deleteNatGateway(region, natGateway.getNatGatewayId());
|
||||
service.deleteSubnet(region, subnetId);
|
||||
assertTrue(service.describeSubnets(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetFailsUntilItsStandaloneNetworkInterfaceIsDeleted() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.83.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId();
|
||||
String eniId = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(), List.of())
|
||||
.getNetworkInterfaceId();
|
||||
|
||||
// An available interface is still an interface in the subnet, so the subnet stays pinned.
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
service.deleteNetworkInterface(region, eniId);
|
||||
service.deleteSubnet(region, subnetId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetFailsUntilItsInterfaceEndpointIsDeleted() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.84.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.84.1.0/24", "us-east-1a").getSubnetId();
|
||||
String endpointId = service.createVpcEndpoint(region, vpcId, "com.amazonaws.us-east-1.sqs", "Interface",
|
||||
List.of(), List.of(subnetId), List.of(), null, null, List.of()).getVpcEndpointId();
|
||||
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
service.deleteVpcEndpoints(region, List.of(endpointId));
|
||||
service.deleteSubnet(region, subnetId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteVpcFailsWhileAnInstanceSitsInOneOfItsSubnets() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String vpcId = service.createVpc(region, "10.83.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId();
|
||||
String instanceId = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",
|
||||
1, 1, null, List.of(), subnetId, null, List.of(), null, null)
|
||||
.getInstances().getFirst().getInstanceId();
|
||||
|
||||
AwsException pinned = assertThrows(AwsException.class, () -> service.deleteVpc(region, vpcId));
|
||||
assertEquals("DependencyViolation", pinned.getErrorCode());
|
||||
assertEquals("The vpc '" + vpcId + "' has dependencies and cannot be deleted.", pinned.getMessage());
|
||||
assertEquals("DependencyViolation", assertThrows(AwsException.class,
|
||||
() -> service.deleteSubnet(region, subnetId)).getErrorCode());
|
||||
|
||||
service.terminateInstances(region, List.of(instanceId));
|
||||
service.deleteSubnet(region, subnetId);
|
||||
service.deleteVpc(region, vpcId);
|
||||
assertTrue(service.describeVpcs(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(vpc -> vpcId.equals(vpc.getVpcId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachingAnInternetGatewayToAMissingVpcFails() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
+13
-20
@@ -12,6 +12,7 @@ import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.everyItem;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -121,16 +122,11 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void theWireIdsAreTheInterfacesFlowLogAttributionReads() {
|
||||
// THE PROPERTY THE DESIGN RESTS ON, and the one the other tests do not reach.
|
||||
// They pin count, shape, distinctness and stability -- all of which an
|
||||
// implementation deriving ids from the subnet id alone would satisfy while
|
||||
// reporting interfaces that endpointNetworkInterfaces() denies exist. That is
|
||||
// not hypothetical: an earlier version of endpointNetworkInterfaceIds called
|
||||
// endpointEniId itself, lacked this method's skip of a vanished subnet, and the
|
||||
// two were measured reporting different sets after a subnet was deleted out from
|
||||
// under a live endpoint. Flow-log attribution reads the service side; Terraform
|
||||
// reads the wire side; they have to be the same list.
|
||||
void aSubnetUnderALiveEndpointCannotBeDeletedAndTheWireIdsStayTheServiceIds() {
|
||||
// The interface an endpoint holds in a subnet pins that subnet, as on AWS: DeleteSubnet
|
||||
// answers DependencyViolation until the endpoint is gone. Flow-log attribution reads
|
||||
// the service side and Terraform reads the wire side, so after the refused delete both
|
||||
// must still report the same two interfaces, in the same order.
|
||||
String vpcId = createVpc("10.77.0.0/16");
|
||||
String subnetA = createSubnet(vpcId, "10.77.1.0/24", "us-east-1a");
|
||||
String subnetB = createSubnet(vpcId, "10.77.2.0/24", "us-east-1b");
|
||||
@@ -139,15 +135,12 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {
|
||||
"CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId",
|
||||
"VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2",
|
||||
"VpcEndpointType", "Interface", "SubnetId.1", subnetA, "SubnetId.2", subnetB);
|
||||
List<String> before = eniIdsOf(endpointId);
|
||||
|
||||
// DELETE A SUBNET OUT FROM UNDER THE LIVE ENDPOINT. Without this the test is
|
||||
// decorative: both derivations agree whenever every subnet still exists, so a
|
||||
// version that skipped the vanished-subnet filter passed this assertion happily.
|
||||
// Measured -- the first draft of this test did exactly that. Real AWS answers
|
||||
// DependencyViolation here and Terraform's graph destroys the endpoint first, so
|
||||
// the state is reachable only in an emulator; that is precisely why the emulator
|
||||
// has to stay self-consistent in it rather than report two different answers.
|
||||
ec2Value("DeleteSubnet", "DeleteSubnetResponse.return", "SubnetId", subnetB);
|
||||
given().formParam("Action", "DeleteSubnet").formParam("SubnetId", subnetB)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("DependencyViolation"));
|
||||
|
||||
List<String> onTheWire = eniIdsOf(endpointId);
|
||||
|
||||
@@ -160,11 +153,11 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(before, onTheWire, "a refused delete changes nothing about the endpoint");
|
||||
assertEquals(fromTheService, onTheWire,
|
||||
"the ids DescribeVpcEndpoints publishes must be the interfaces the "
|
||||
+ "service reports, in the same order");
|
||||
assertEquals(1, onTheWire.size(),
|
||||
"the endpoint has one surviving subnet, so it reports one interface");
|
||||
assertEquals(2, onTheWire.size(), "both subnets survive, so both interfaces are reported");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user