mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): support NAT gateway secondary addresses (#7327)
* fix(ec2): support NAT gateway secondary addresses * fix(ec2): update a NAT gateway's secondary addresses in place A CloudFormation update that changed only a NAT gateway's Secondary* properties replaced the gateway. The replacement was created while the old gateway still held its Elastic IP or fixed private address, so it came back failed with Resource.AlreadyAssociated (or InvalidIPAddress.InUse) and the update failed. The schema does not mark the secondaries create-only, so AWS changes them in place and the gateway keeps its id. Ec2Service.updateNatGatewaySecondaryAddresses sets a gateway's secondaries to the requested ones: kept ones stay, dropped Elastic IPs are handed back, new ones are checked as CreateNatGateway checks them, and every check runs before anything changes. The provisioner calls it instead of replacing, and records the prior secondaries so a rolled-back update puts them back. * fix(ec2): keep a NAT gateway's picked secondary when listed ones change The counted slots of an in-place secondary update kept the first secondary with no Elastic IP and an address the request does not list. With SecondaryPrivateIpAddresses [A] and a count of 1 changed to [B] and 1, that was the dropped listed A, while the address the subnet had picked was given up. Counted addresses always follow the listed ones, so the counted slots now keep the last such secondaries, in order. Tests cover a count changed in place (an unrelated change keeps the same addresses; 1 to 2 keeps the first; 2 to 1 keeps one of them), the picked address surviving a listed change, and secondary Elastic IPs swapped between listed addresses or moved to a new one, with DescribeAddresses showing each held at its new address. * test(ec2): pin which counted NAT gateway secondary an update keeps The counted slots keep the last unlisted secondaries, so a count lowered from 2 to 1 keeps the second address; the test now asserts that, and that raising the count from 1 to 2 adds a new address in the subnet after the kept one. The comment no longer claims counted addresses always follow the listed ones: slot position is the only record of an address's origin, and across updates a once-listed address can move behind a picked one. * fix(ec2): read a NAT gateway under the allocation lock before updating its secondaries The secondary-address update read the gateway before taking the lock that DeleteNatGateway holds. A delete finishing in between left the update holding a stale copy, which it then wrote back, re-associating the Elastic IPs the delete had released and overwriting the association of a gateway that had since taken the primary one. The gateway is now read again under the lock, and one that is gone or deleted is refused with NatGatewayNotFound. * test(cloudformation): read NAT gateway addresses through XmlParser The secondary-address tests picked addresses out of DescribeNatGateways and DescribeAddresses with a regular expression and substring checks that depended on element order. They now select the non-primary items of natGatewayAddressSet through XmlParser. * test(ec2): cover a NAT gateway stored as deleted by a racing tag write CreateTags writes a NAT gateway back under the gateway's tag lock, which DeleteNatGateway does not take. A tag write that read the gateway before a delete therefore stores the very record the delete marked deleted, so the secondary-address update's deleted-state check is reachable. The test pauses the tag write's put, deletes the gateway, lets the put finish, and asserts the update refuses the record with NatGatewayNotFound and holds no Elastic IP for it. * refactor(ec2): fill a NAT gateway's address slots in one place CreateNatGateway and the secondary-address update each walked the gateway's slots the same way: take the listed Elastic IP and address at each position, assign a free address where none is listed, build the address, and give back what was assigned if a later slot fails. Both now call fillNatGatewaySlots. Create passes its primary address as slot 0 and marks it primary afterwards; the update passes the slots its kept secondaries already fill. The order addresses are assigned in, the error codes and the release on failure are unchanged. * test(ec2): cover NAT gateway lease release and reuse the shared test helpers No test covered the lease a NAT gateway gives back when its addresses run out part way, so the shared slot-filling walk could lose its release with every test green. Two tests now run a /28 subnet out of addresses, one through CreateNatGateway and one through a secondary-address update, and verify the lease taken on the VPC network is released and that the update leaves the gateway as it was. The concurrent-delete test now builds its service with mockModeService() and waits for the blocked update with ThreadStates.awaitBlockedOrDone. * test(ec2): build the small NAT subnet with privateSubnet
This commit is contained in:
1 parent
eb65ad88d2
commit
fbfe9048a1
11 files changed
+1068
-146
No files matched your search
+264
@@ -158,6 +158,270 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
assertFalse(ec2("DescribeNatGateways").contains(vpcId), "no gateway, failed or not, is left behind");
|
||||
}
|
||||
|
||||
/**
|
||||
* A NAT gateway in its own subnet with three Elastic IPs to choose from. {@code natProps} are
|
||||
* the gateway's properties after SubnetId; {@code failing} adds a resource that cannot be
|
||||
* created once the gateway is done.
|
||||
*/
|
||||
private static String secondaryNatTemplate(String vpcId, String cidr, String natProps, boolean failing) {
|
||||
String boom = failing
|
||||
? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\", \"DependsOn\": \"Nat\","
|
||||
+ " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}"
|
||||
: "";
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "%1$s", "CidrBlock": "%2$s"}},
|
||||
"Eip": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}},
|
||||
"Eip2": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}},
|
||||
"Eip3": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}},
|
||||
"Nat": {"Type": "AWS::EC2::NatGateway", "Properties": {"SubnetId": {"Ref": "Subnet"}%3$s}}%4$s
|
||||
},
|
||||
"Outputs": {
|
||||
"NatId": {"Value": {"Ref": "Nat"}},
|
||||
"SubnetId": {"Value": {"Ref": "Subnet"}},
|
||||
"Eip2Id": {"Value": {"Fn::GetAtt": ["Eip2", "AllocationId"]}},
|
||||
"Eip3Id": {"Value": {"Fn::GetAtt": ["Eip3", "AllocationId"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(vpcId, cidr, natProps, boom);
|
||||
}
|
||||
|
||||
private static final String PUBLIC_NAT = ", \"AllocationId\": {\"Fn::GetAtt\": [\"Eip\", \"AllocationId\"]}";
|
||||
|
||||
/**
|
||||
* A NAT gateway's secondary addresses are not create-only, so AWS changes them in place and the
|
||||
* gateway keeps its id. Replacing it instead would ask for the Elastic IP the old gateway still
|
||||
* holds and fail with Resource.AlreadyAssociated.
|
||||
*/
|
||||
@Test
|
||||
void aPublicNatGatewaysSecondaryElasticIpsChangeInPlace() {
|
||||
String stack = "ec2-nat-secondary-public-it";
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.45.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24",
|
||||
PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip2\", \"AllocationId\"]}]", false));
|
||||
Map<String, String> out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue");
|
||||
String natId = out.get("NatId");
|
||||
String eip2 = out.get("Eip2Id");
|
||||
String eip3 = out.get("Eip3Id");
|
||||
assertTrue(natXml(natId).contains("<allocationId>" + eip2 + "</allocationId>"), natXml(natId));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24",
|
||||
PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip3\", \"AllocationId\"]}]", false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"), "the gateway is kept");
|
||||
String nat = natXml(natId);
|
||||
assertTrue(nat.contains("<allocationId>" + eip3 + "</allocationId>") && !nat.contains(eip2), nat);
|
||||
assertFalse(ec2("DescribeAddresses", Map.of("AllocationId.1", eip2)).contains("<associationId>"),
|
||||
"the dropped Elastic IP is free");
|
||||
assertTrue(ec2("DescribeAddresses", Map.of("AllocationId.1", eip3)).contains("<associationId>"),
|
||||
"the added Elastic IP is held");
|
||||
|
||||
// An Elastic IP another gateway holds fails the update and leaves the gateway as it was.
|
||||
String held = between(ec2("AllocateAddress", Map.of("Domain", "vpc")), "<allocationId>", "</allocationId>");
|
||||
String otherNat = between(ec2("CreateNatGateway", Map.of("SubnetId", out.get("SubnetId"), "AllocationId", held)),
|
||||
"<natGatewayId>", "</natGatewayId>");
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24",
|
||||
PUBLIC_NAT + ", \"SecondaryAllocationIds\": [\"" + held + "\"]", false));
|
||||
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
String reason = CfnStackWaits.failedResourceReason(stack, CFN_AUTH);
|
||||
assertTrue(reason.contains(held), reason);
|
||||
nat = natXml(natId);
|
||||
assertTrue(nat.contains("<allocationId>" + eip3 + "</allocationId>") && !nat.contains(held), nat);
|
||||
assertTrue(natXml(otherNat).contains("<allocationId>" + held + "</allocationId>"));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.45.0.0/24", PUBLIC_NAT, false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
nat = natXml(natId);
|
||||
assertFalse(nat.contains(eip3) || !secondaryIps(nat).isEmpty(), "no secondary is left: " + nat);
|
||||
assertFalse(ec2("DescribeAddresses", Map.of("AllocationId.1", eip3)).contains("<associationId>"));
|
||||
|
||||
ec2("DeleteNatGateway", Map.of("NatGatewayId", otherNat));
|
||||
ec2("ReleaseAddress", Map.of("AllocationId", held));
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrivateNatGatewaysSecondaryAddressesChangeInPlace() {
|
||||
String stack = "ec2-nat-secondary-private-it";
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.46.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
String privateNat = ", \"ConnectivityType\": \"private\", \"PrivateIpAddress\": \"10.46.0.10\","
|
||||
+ " \"SecondaryPrivateIpAddresses\": [%s]";
|
||||
cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24",
|
||||
privateNat.formatted("\"10.46.0.20\""), false));
|
||||
Map<String, String> out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue");
|
||||
String natId = out.get("NatId");
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24",
|
||||
privateNat.formatted("\"10.46.0.21\", \"10.46.0.22\""), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"), "the gateway is kept");
|
||||
String nat = natXml(natId);
|
||||
assertTrue(nat.contains("<privateIp>10.46.0.10</privateIp>") && nat.contains("<privateIp>10.46.0.21</privateIp>")
|
||||
&& nat.contains("<privateIp>10.46.0.22</privateIp>") && !nat.contains("<privateIp>10.46.0.20</privateIp>"), nat);
|
||||
|
||||
// A change next to a resource that fails is put back.
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24",
|
||||
privateNat.formatted("\"10.46.0.23\""), true));
|
||||
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
nat = natXml(natId);
|
||||
assertTrue(nat.contains("<privateIp>10.46.0.21</privateIp>") && nat.contains("<privateIp>10.46.0.22</privateIp>")
|
||||
&& !nat.contains("<privateIp>10.46.0.23</privateIp>"), "the prior secondaries must be back: " + nat);
|
||||
|
||||
// An address another resource holds fails the update and leaves the gateway as it was.
|
||||
String eni = between(ec2("CreateNetworkInterface", Map.of("SubnetId", out.get("SubnetId"),
|
||||
"PrivateIpAddress", "10.46.0.30")), "<networkInterfaceId>", "</networkInterfaceId>");
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24",
|
||||
privateNat.formatted("\"10.46.0.30\""), false));
|
||||
describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
|
||||
String reason = CfnStackWaits.failedResourceReason(stack, CFN_AUTH);
|
||||
assertTrue(reason.contains("10.46.0.30"), reason);
|
||||
nat = natXml(natId);
|
||||
assertTrue(nat.contains("<privateIp>10.46.0.21</privateIp>") && nat.contains("<privateIp>10.46.0.22</privateIp>")
|
||||
&& !nat.contains("<privateIp>10.46.0.30</privateIp>"), nat);
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.46.0.0/24",
|
||||
", \"ConnectivityType\": \"private\", \"PrivateIpAddress\": \"10.46.0.10\"", false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
nat = natXml(natId);
|
||||
assertTrue(nat.contains("<privateIp>10.46.0.10</privateIp>") && secondaryIps(nat).isEmpty(),
|
||||
"only the primary address is left: " + nat);
|
||||
|
||||
ec2("DeleteNetworkInterface", Map.of("NetworkInterfaceId", eni));
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
/** A counted secondary survives a count change and an unrelated update, and the gateway is kept. */
|
||||
@Test
|
||||
void aPrivateNatGatewaysCountedSecondariesChangeInPlace() {
|
||||
String stack = "ec2-nat-secondary-count-it";
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.47.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
String counted = ", \"ConnectivityType\": \"private\", \"SecondaryPrivateIpAddressCount\": %d%s";
|
||||
cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(1, ""), false));
|
||||
String natId = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId");
|
||||
List<String> first = secondaryIps(natXml(natId));
|
||||
assertEquals(1, first.size(), natXml(natId));
|
||||
|
||||
// The count unchanged next to another change: the same address.
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24",
|
||||
counted.formatted(1, ", \"Tags\": [{\"Key\": \"k\", \"Value\": \"v\"}]"), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
assertEquals(first, secondaryIps(natXml(natId)));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(2, ""), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
List<String> two = secondaryIps(natXml(natId));
|
||||
assertEquals(2, two.size(), natXml(natId));
|
||||
assertEquals(first.get(0), two.get(0), "the counted address is kept: " + two);
|
||||
assertTrue(!two.get(1).equals(two.get(0)) && two.get(1).startsWith("10.47.0."), "a new address in the subnet: " + two);
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.47.0.0/24", counted.formatted(1, ""), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
List<String> one = secondaryIps(natXml(natId));
|
||||
assertEquals(1, one.size(), natXml(natId));
|
||||
assertEquals(List.of(two.get(1)), one, "the last counted address is kept");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Listed addresses changing next to a count keep the address the subnet picked, not a listed
|
||||
* one that the template dropped.
|
||||
*/
|
||||
@Test
|
||||
void aCountedSecondaryKeepsItsAddressWhenTheListedOnesChange() {
|
||||
String stack = "ec2-nat-secondary-mixed-it";
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.48.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
String mixed = ", \"ConnectivityType\": \"private\", \"SecondaryPrivateIpAddresses\": [\"%s\"],"
|
||||
+ " \"SecondaryPrivateIpAddressCount\": 1";
|
||||
cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.48.0.0/24", mixed.formatted("10.48.0.40"), false));
|
||||
String natId = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId");
|
||||
List<String> before = secondaryIps(natXml(natId));
|
||||
assertEquals("10.48.0.40", before.get(0), before.toString());
|
||||
String picked = before.get(1);
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.48.0.0/24", mixed.formatted("10.48.0.41"), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
assertEquals(List.of("10.48.0.41", picked), secondaryIps(natXml(natId)),
|
||||
"the listed address is swapped and the picked one kept");
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
/** Secondary Elastic IPs moved between listed addresses, and one moved to a new address, in one update each. */
|
||||
@Test
|
||||
void aSecondaryElasticIpMovesToAnotherAddressInPlace() {
|
||||
String stack = "ec2-nat-secondary-move-it";
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.49.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
String moved = PUBLIC_NAT + ", \"SecondaryAllocationIds\": [{\"Fn::GetAtt\": [\"Eip2\", \"AllocationId\"]},"
|
||||
+ " {\"Fn::GetAtt\": [\"Eip3\", \"AllocationId\"]}], \"SecondaryPrivateIpAddresses\": [\"%s\", \"%s\"]";
|
||||
cloudFormation(stack, "CreateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24",
|
||||
moved.formatted("10.49.0.50", "10.49.0.51"), false));
|
||||
Map<String, String> out = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue");
|
||||
String natId = out.get("NatId");
|
||||
String eip2 = out.get("Eip2Id");
|
||||
String eip3 = out.get("Eip3Id");
|
||||
assertEquals("10.49.0.50", eipPrivateIp(eip2));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24",
|
||||
moved.formatted("10.49.0.51", "10.49.0.50"), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
assertEquals(List.of("10.49.0.51", "10.49.0.50"), secondaryIps(natXml(natId)));
|
||||
assertEquals("10.49.0.51", eipPrivateIp(eip2), "the swapped Elastic IP is held at its new address");
|
||||
assertEquals("10.49.0.50", eipPrivateIp(eip3));
|
||||
|
||||
cloudFormation(stack, "UpdateStack", secondaryNatTemplate(vpcId, "10.49.0.0/24",
|
||||
moved.formatted("10.49.0.52", "10.49.0.50"), false));
|
||||
assertEquals(natId, XmlParser.extractPairs(describeStacks(stack, "UPDATE_COMPLETE"),
|
||||
"Outputs", "OutputKey", "OutputValue").get("NatId"));
|
||||
assertEquals(List.of("10.49.0.52", "10.49.0.50"), secondaryIps(natXml(natId)), "10.49.0.51 is given up");
|
||||
assertEquals("10.49.0.52", eipPrivateIp(eip2), "the same Elastic IP is held at the new address");
|
||||
assertEquals("10.49.0.50", eipPrivateIp(eip3));
|
||||
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
/** The gateway's secondary private addresses, in the order DescribeNatGateways lists them. */
|
||||
private static List<String> secondaryIps(String natXml) {
|
||||
return XmlParser.extractElementTree(natXml, "natGatewayAddressSet").children().stream()
|
||||
.filter(item -> "false".equals(item.child("isPrimary").text()))
|
||||
.map(item -> item.child("privateIp").text())
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The private address an associated Elastic IP is held at. */
|
||||
private static String eipPrivateIp(String allocationId) {
|
||||
String xml = ec2("DescribeAddresses", Map.of("AllocationId.1", allocationId));
|
||||
assertTrue(XmlParser.extractFirst(xml, "associationId", null) != null, "the Elastic IP is held: " + xml);
|
||||
return XmlParser.extractFirst(xml, "privateIpAddress", null);
|
||||
}
|
||||
|
||||
private static String natXml(String natGatewayId) {
|
||||
return ec2("DescribeNatGateways", Map.of("NatGatewayId.1", natGatewayId));
|
||||
}
|
||||
|
||||
private static String subnetXml(String subnetId) {
|
||||
return ec2("DescribeSubnets", Map.of("SubnetId.1", subnetId));
|
||||
}
|
||||
|
||||
+72
-27
@@ -219,7 +219,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
@Test
|
||||
void natGatewayIsCreatedPublicWithNoTags() {
|
||||
NatGateway nat = natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.10");
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of())).thenReturn(nat);
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(), List.of(), null, List.of())).thenReturn(nat);
|
||||
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx());
|
||||
@@ -238,7 +238,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
void natGatewayRecordsTheSubnetAndElasticIpItUsesUnderHiddenKeys() {
|
||||
NatGateway nat = natGateway(NAT_ID);
|
||||
nat.setSubnetId(SUBNET_ID);
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of())).thenReturn(nat);
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(), List.of(), null, List.of())).thenReturn(nat);
|
||||
Address addr = new Address();
|
||||
addr.setAllocationId(ALLOC_ID);
|
||||
addr.setPublicIp(PUBLIC_IP);
|
||||
@@ -484,11 +484,11 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
|
||||
StackResource same = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
|
||||
provisioner.provision(same, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx(NAT_ID));
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals(NAT_ID, same.getPhysicalId());
|
||||
|
||||
NatGateway replacement = natGateway("nat-replacement");
|
||||
when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", null, List.of())).thenReturn(replacement);
|
||||
when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", null, List.of(), List.of(), null, List.of())).thenReturn(replacement);
|
||||
StackResource moved = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
|
||||
provisioner.provision(moved, mapper.createObjectNode().put("SubnetId", "subnet-other").put("AllocationId", ALLOC_ID), ctx(NAT_ID));
|
||||
assertEquals("nat-replacement", moved.getPhysicalId());
|
||||
@@ -622,7 +622,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
@Test
|
||||
void aPrivateNatGatewayNeedsNoAllocationAndAPublicOneRequiresIt() {
|
||||
NatGateway nat = natGateway(NAT_ID);
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), any())).thenReturn(nat);
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), eq(List.of()), eq(List.of()), isNull(), any())).thenReturn(nat);
|
||||
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx());
|
||||
@@ -653,35 +653,80 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
mapper.createObjectNode().put("AvailabilityMode", "Regional").put("SubnetId", SUBNET_ID)
|
||||
.put("ConnectivityType", "private"), ctx()));
|
||||
assertEquals("InvalidParameterValue", invalid.getErrorCode());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* The three secondary-address properties reach CreateNatGateway, each secondary Elastic IP is
|
||||
* recorded as held, and the gateway is kept whether or not they change.
|
||||
*/
|
||||
@Test
|
||||
void aNatGatewayIsCreatedWithItsSecondaryAddressesAndChangedOnesUpdateItInPlace() {
|
||||
String secondaryAlloc = "eipalloc-0fedcba9876543210";
|
||||
NatGateway nat = natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50");
|
||||
nat.setSubnetId(SUBNET_ID);
|
||||
nat.setAllocationId(ALLOC_ID);
|
||||
nat.setConnectivityType("public");
|
||||
nat.getNatGatewayAddresses().get(0).setAllocationId(ALLOC_ID);
|
||||
NatGatewayAddress secondary = new NatGatewayAddress();
|
||||
secondary.setPrimary(false);
|
||||
secondary.setNetworkInterfaceId("eni-0123456789abcdef0");
|
||||
secondary.setPrivateIp("10.0.1.70");
|
||||
secondary.setAllocationId(secondaryAlloc);
|
||||
secondary.setPublicIp("203.0.113.70");
|
||||
nat.getNatGatewayAddresses().add(secondary);
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", null, List.of(secondaryAlloc),
|
||||
List.of("10.0.1.70"), null, List.of())).thenReturn(nat);
|
||||
ObjectNode props = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID);
|
||||
props.putArray("SecondaryAllocationIds").add(secondaryAlloc);
|
||||
props.putArray("SecondaryPrivateIpAddresses").add("10.0.1.70");
|
||||
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
assertEquals(NAT_ID, r.getPhysicalId());
|
||||
assertEquals("203.0.113.70", r.getAttributes().get(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp.0"));
|
||||
|
||||
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
|
||||
StackResource kept = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
|
||||
provisioner.provision(kept, props, ctx(NAT_ID));
|
||||
assertEquals(NAT_ID, kept.getPhysicalId());
|
||||
|
||||
verify(ec2, never()).updateNatGatewaySecondaryAddresses(any(), any(), any(), any(), any());
|
||||
|
||||
when(ec2.updateNatGatewaySecondaryAddresses(REGION, NAT_ID, List.of(), List.of(), null))
|
||||
.thenReturn(natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50"));
|
||||
StackResource changed = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
|
||||
provisioner.provision(changed, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID),
|
||||
ctx(NAT_ID));
|
||||
verify(ec2).updateNatGatewaySecondaryAddresses(REGION, NAT_ID, List.of(), List.of(), null);
|
||||
verify(ec2).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
assertEquals(NAT_ID, changed.getPhysicalId(), "changed secondaries keep the gateway");
|
||||
assertFalse(changed.getAttributes().containsKey(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp.0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNatGatewayWithSecondaryAddressesIsRefusedRatherThanCreatedWithoutThem() {
|
||||
ObjectNode withAllocations = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID);
|
||||
withAllocations.putArray("SecondaryAllocationIds").add("eipalloc-0fedcba9876543210");
|
||||
ObjectNode withAddresses = mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private");
|
||||
withAddresses.putArray("SecondaryPrivateIpAddresses").add("10.0.1.70");
|
||||
for (ObjectNode props : List.of(withAllocations, withAddresses,
|
||||
mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private")
|
||||
.put("SecondaryPrivateIpAddressCount", 2))) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"), props, ctx()));
|
||||
assertEquals("UnsupportedOperation", e.getErrorCode());
|
||||
}
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
|
||||
void aPrivateNatGatewayPassesItsSecondaryAddressCount() {
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", null, List.of(), List.of(), "2", List.of()))
|
||||
.thenReturn(natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50"));
|
||||
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private")
|
||||
.put("SecondaryPrivateIpAddressCount", 2), ctx());
|
||||
|
||||
assertEquals(NAT_ID, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNatGatewayIsCreatedWithThePrivateIpAddressTheTemplateNames() {
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of()))
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of(), List.of(), null, List.of()))
|
||||
.thenReturn(natGateway(NAT_ID, "eni-0123456789abcdef0", "10.0.1.50"));
|
||||
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private")
|
||||
.put("PrivateIpAddress", "10.0.1.50"), ctx());
|
||||
|
||||
verify(ec2).createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of());
|
||||
verify(ec2).createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.50", List.of(), List.of(), null, List.of());
|
||||
assertEquals(NAT_ID, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@@ -702,9 +747,9 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
provisioner.provision(kept, props, ctx(NAT_ID));
|
||||
assertEquals(NAT_ID, kept.getPhysicalId());
|
||||
}
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.60", List.of()))
|
||||
when(ec2.createNatGateway(REGION, SUBNET_ID, null, "private", "10.0.1.60", List.of(), List.of(), null, List.of()))
|
||||
.thenReturn(natGateway("nat-replacement", "eni-0fedcba9876543210", "10.0.1.60"));
|
||||
StackResource moved = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
|
||||
provisioner.provision(moved, privateNat.deepCopy().put("PrivateIpAddress", "10.0.1.60"), ctx(NAT_ID));
|
||||
@@ -720,7 +765,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
nat.setConnectivityType("public");
|
||||
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
|
||||
NatGateway replacement = natGateway("nat-private", "eni-0fedcba9876543210", "10.0.1.11");
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), any())).thenReturn(replacement);
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), isNull(), eq(List.of()), eq(List.of()), isNull(), any())).thenReturn(replacement);
|
||||
StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID,
|
||||
Map.of("NatGatewayId", NAT_ID, "EniId", "eni-0123456789abcdef0"));
|
||||
|
||||
@@ -735,14 +780,14 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
@Test
|
||||
void natGatewayTagsGoThroughItsCreateCall() {
|
||||
NatGateway nat = natGateway(NAT_ID);
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), any())).thenReturn(nat);
|
||||
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), eq(List.of()), eq(List.of()), isNull(), any())).thenReturn(nat);
|
||||
|
||||
provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"),
|
||||
withTags(mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), "Name", "nat"), ctx());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
|
||||
verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), tags.capture());
|
||||
verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), isNull(), eq(List.of()), eq(List.of()), isNull(), tags.capture());
|
||||
assertEquals(List.of("Name=nat"), pairs(tags.getValue()));
|
||||
verify(ec2, never()).createTags(any(), any(), any());
|
||||
}
|
||||
@@ -987,7 +1032,7 @@ class Ec2NetworkCfnProvisionerTest {
|
||||
verify(ec2, never()).createRouteTable(any(), any());
|
||||
verify(ec2, never()).associateRouteTable(any(), any(), any());
|
||||
verify(ec2, never()).createRoute(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+126
-9
@@ -8,11 +8,13 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesRegex;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A NAT gateway's natGatewayAddressSet carried only an allocation id. aws_nat_gateway exposes
|
||||
@@ -240,23 +242,138 @@ class Ec2NatGatewayAddressIntegrationTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway gets its primary address only, so the secondary-address parameters are refused
|
||||
* rather than answered with a gateway that has fewer addresses than it was asked for.
|
||||
* A public gateway's secondary Elastic IP is reported after the primary address, on the same
|
||||
* interface, with the private address it was paired with. DescribeAddresses and
|
||||
* DescribeNetworkInterfaces show it held, it cannot be released while the gateway holds it,
|
||||
* and deleting the gateway hands it back.
|
||||
*/
|
||||
@Test
|
||||
void theSecondaryAddressParametersAreRefused() {
|
||||
void aPublicGatewayHoldsItsSecondaryElasticIpUntilDeleted() {
|
||||
String subnetId = subnetId();
|
||||
for (Map<String, String> request : List.of(
|
||||
Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryAllocationId.1", allocate()),
|
||||
Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddress.1", "10.94.1.70"),
|
||||
Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "2"))) {
|
||||
createNat(request).then()
|
||||
String primary = allocate();
|
||||
Response secondaryAllocation = allocation();
|
||||
String secondary = secondaryAllocation.path("AllocateAddressResponse.allocationId");
|
||||
String secondaryPublicIp = secondaryAllocation.path("AllocateAddressResponse.publicIp");
|
||||
|
||||
String natGatewayId = createNat(Map.of("SubnetId", subnetId, "AllocationId", primary,
|
||||
"SecondaryAllocationId.1", secondary, "SecondaryPrivateIpAddress.1", "10.94.1.71")).then()
|
||||
.statusCode(200)
|
||||
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
|
||||
|
||||
Response described = ec2("DescribeNatGateways", ACCOUNT_ID, REGION)
|
||||
.formParam("NatGatewayId.1", natGatewayId).post("/")
|
||||
.then().statusCode(200)
|
||||
.body(ADDRESSES + ".size()", equalTo(2))
|
||||
.body(ADDRESSES + "[0].allocationId", equalTo(primary))
|
||||
.body(ADDRESSES + "[0].isPrimary", equalTo("true"))
|
||||
.body(ADDRESSES + "[1].allocationId", equalTo(secondary))
|
||||
.body(ADDRESSES + "[1].publicIp", equalTo(secondaryPublicIp))
|
||||
.body(ADDRESSES + "[1].privateIp", equalTo("10.94.1.71"))
|
||||
.body(ADDRESSES + "[1].associationId", startsWith("eipassoc-"))
|
||||
.body(ADDRESSES + "[1].isPrimary", equalTo("false"))
|
||||
.body(ADDRESSES + "[1].status", equalTo("succeeded"))
|
||||
.extract().response();
|
||||
String eniId = described.path(ADDRESSES + "[0].networkInterfaceId");
|
||||
String associationId = described.path(ADDRESSES + "[1].associationId");
|
||||
String secondaryEniId = described.path(ADDRESSES + "[1].networkInterfaceId");
|
||||
assertEquals(eniId, secondaryEniId);
|
||||
|
||||
ec2("DescribeNetworkInterfaces", ACCOUNT_ID, REGION).formParam("NetworkInterfaceId.1", eniId).post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.size()", equalTo(1))
|
||||
.body(ENI_IPS + ".size()", equalTo(2))
|
||||
.body(ENI_IPS + "[1].privateIpAddress", equalTo("10.94.1.71"))
|
||||
.body(ENI_IPS + "[1].primary", equalTo("false"))
|
||||
.body(ENI_IPS + "[1].association.allocationId", equalTo(secondary));
|
||||
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", secondary).post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId))
|
||||
.body("DescribeAddressesResponse.addressesSet.item.networkInterfaceId", equalTo(eniId))
|
||||
.body("DescribeAddressesResponse.addressesSet.item.privateIpAddress", equalTo("10.94.1.71"));
|
||||
ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", secondary).post("/")
|
||||
.then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"));
|
||||
// A second gateway cannot take the secondary Elastic IP either.
|
||||
createNat(Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryAllocationId.1", secondary))
|
||||
.then().statusCode(200)
|
||||
.body("CreateNatGatewayResponse.natGateway.state", equalTo("failed"))
|
||||
.body("CreateNatGatewayResponse.natGateway.failureCode", equalTo("Resource.AlreadyAssociated"));
|
||||
|
||||
ec2("DeleteNatGateway", ACCOUNT_ID, REGION).formParam("NatGatewayId", natGatewayId).post("/")
|
||||
.then().statusCode(200);
|
||||
ec2("DescribeAddresses", ACCOUNT_ID, REGION).formParam("AllocationId.1", secondary).post("/")
|
||||
.then().statusCode(200)
|
||||
.body(not(containsString("<associationId>")))
|
||||
.body(not(containsString("<networkInterfaceId>")));
|
||||
ec2("ReleaseAddress", ACCOUNT_ID, REGION).formParam("AllocationId", secondary).post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A private gateway takes listed secondary private addresses and SecondaryPrivateIpAddressCount
|
||||
* more that the subnet picks, every one distinct and none public.
|
||||
*/
|
||||
@Test
|
||||
void aPrivateGatewayTakesListedAndCountedSecondaryAddresses() {
|
||||
String subnetId = subnetId();
|
||||
String natGatewayId = createNat(Map.of("SubnetId", subnetId, "ConnectivityType", "private",
|
||||
"SecondaryPrivateIpAddress.1", "10.94.1.80", "SecondaryPrivateIpAddressCount", "2")).then()
|
||||
.statusCode(200)
|
||||
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
|
||||
|
||||
Response described = ec2("DescribeNatGateways", ACCOUNT_ID, REGION)
|
||||
.formParam("NatGatewayId.1", natGatewayId).post("/")
|
||||
.then().statusCode(200)
|
||||
.body(ADDRESSES + ".size()", equalTo(4))
|
||||
.body(ADDRESSES + ".isPrimary.list()", equalTo(List.of("true", "false", "false", "false")))
|
||||
.body(ADDRESSES + "[1].privateIp", equalTo("10.94.1.80"))
|
||||
.body(not(containsString("<publicIp>")))
|
||||
.extract().response();
|
||||
List<String> privateIps = described.path(ADDRESSES + ".privateIp.list()");
|
||||
assertEquals(4, privateIps.stream().distinct().count(), privateIps.toString());
|
||||
privateIps.forEach(ip -> assertThat(ip, matchesRegex("10\\.94\\.1\\.\\d+")));
|
||||
List<String> enis = described.path(ADDRESSES + ".networkInterfaceId.list()");
|
||||
assertEquals(1, enis.stream().distinct().count(), enis.toString());
|
||||
|
||||
// The subnet now holds them: a later request for one of them fails.
|
||||
createNat(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "PrivateIpAddress", privateIps.get(3)))
|
||||
.then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The EC2 API reference marks SecondaryPrivateIpAddressCount "[Private NAT gateway only]" with
|
||||
* a valid range of 1 to 31, and a private gateway takes no Elastic IP. A refused request
|
||||
* creates nothing.
|
||||
*/
|
||||
@Test
|
||||
void secondaryAddressesOutsideTheirRulesAreRefused() {
|
||||
String subnetId = subnetId();
|
||||
for (Map.Entry<Map<String, String>, String> c : List.of(
|
||||
Map.entry(Map.of("SubnetId", subnetId, "AllocationId", allocate(), "SecondaryPrivateIpAddressCount", "1"),
|
||||
"InvalidParameterCombination"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryAllocationId.1", allocate()),
|
||||
"InvalidParameterCombination"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "0"),
|
||||
"InvalidParameterValue"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddressCount", "32"),
|
||||
"InvalidParameterValue"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "SecondaryPrivateIpAddress.1", "10.94.2.9"),
|
||||
"InvalidParameterValue"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "ConnectivityType", "private", "PrivateIpAddress", "10.94.1.90",
|
||||
"SecondaryPrivateIpAddress.1", "10.94.1.90"), "InvalidIPAddress.InUse"),
|
||||
Map.entry(Map.of("SubnetId", subnetId, "AllocationId", allocate(),
|
||||
"SecondaryAllocationId.1", "eipalloc-0fedcba9876543210"), "InvalidAllocationID.NotFound"))) {
|
||||
createNat(c.getKey()).then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("UnsupportedOperation"));
|
||||
.body("Response.Errors.Error.Code", equalTo(c.getValue()));
|
||||
}
|
||||
assertNatGatewaysIn(subnetId, 0);
|
||||
}
|
||||
|
||||
private static final String ADDRESSES = "DescribeNatGatewaysResponse.natGatewaySet.item.natGatewayAddressSet.item";
|
||||
private static final String ENI_IPS = "DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddressesSet.item";
|
||||
|
||||
private static Response allocation() {
|
||||
return ec2("AllocateAddress", ACCOUNT_ID, REGION).formParam("Domain", "vpc").post("/")
|
||||
.then().statusCode(200).extract().response();
|
||||
|
||||
@@ -123,6 +123,7 @@ import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519
|
||||
import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_FINGERPRINT;
|
||||
import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_KEY;
|
||||
import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.TRUNCATED_RSA_KEY;
|
||||
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -2622,6 +2623,154 @@ class Ec2ServiceTest {
|
||||
.getFirst().getAssociationId(), "delete must still release the gateway's Elastic IP");
|
||||
}
|
||||
|
||||
/**
|
||||
* A secondary-address update that read the gateway before a delete finished must not write it
|
||||
* back: the delete runs while the update waits for the allocation lock, and another gateway
|
||||
* takes the released primary Elastic IP meanwhile.
|
||||
*/
|
||||
@Test
|
||||
void aSecondaryAddressUpdateDoesNotBringBackAGatewayDeletedUnderIt() throws Exception {
|
||||
Ec2Service service = mockModeService();
|
||||
String region = "us-east-1";
|
||||
String subnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String primary = service.allocateAddress(region).getAllocationId();
|
||||
String secondary = service.allocateAddress(region).getAllocationId();
|
||||
String added = service.allocateAddress(region).getAllocationId();
|
||||
String natId = service.createNatGateway(region, subnetId, primary, "public", null, List.of(secondary),
|
||||
List.of(), null, List.of()).getNatGatewayId();
|
||||
Field lockField = Ec2Service.class.getDeclaredField("privateIpAllocationLock");
|
||||
lockField.setAccessible(true);
|
||||
Object lock = lockField.get(service);
|
||||
AtomicReference<Thread> updater = new AtomicReference<>();
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
Future<?> updating;
|
||||
String other;
|
||||
synchronized (lock) {
|
||||
updating = worker.submit(() -> {
|
||||
updater.set(Thread.currentThread());
|
||||
service.updateNatGatewaySecondaryAddresses(region, natId, List.of(added), List.of(), null);
|
||||
});
|
||||
awaitBlockedOrDone(updater, updating);
|
||||
assertFalse(updating.isDone(), "the update must wait for the allocation lock");
|
||||
service.deleteNatGateway(region, natId);
|
||||
other = service.createNatGateway(region, subnetId, primary, "public", List.of()).getNatGatewayId();
|
||||
}
|
||||
ExecutionException e = assertThrows(ExecutionException.class, () -> updating.get(5, TimeUnit.SECONDS));
|
||||
assertEquals("NatGatewayNotFound", ((AwsException) e.getCause()).getErrorCode());
|
||||
|
||||
assertTrue(service.describeNatGateways(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(g -> natId.equals(g.getNatGatewayId())), "the deleted gateway stays deleted");
|
||||
NatGateway taker = service.describeNatGateways(region, List.of(other), Map.of()).getFirst();
|
||||
assertEquals(taker.getNatGatewayAddresses().getFirst().getAssociationId(),
|
||||
service.describeAddresses(region, List.of(primary), Map.of()).getFirst().getAssociationId(),
|
||||
"the primary Elastic IP stays with the gateway that took it");
|
||||
for (String free : List.of(secondary, added)) {
|
||||
assertNull(service.describeAddresses(region, List.of(free), Map.of()).getFirst().getAssociationId(),
|
||||
free + " is not held again");
|
||||
}
|
||||
} finally {
|
||||
worker.shutdownNow();
|
||||
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A NAT gateway whose addresses run out part way gives back the lease it took on the VPC
|
||||
* network. The subnet is a /28, eleven assignable addresses, and 31 more are asked for.
|
||||
*/
|
||||
@Test
|
||||
void aNatGatewayCreateThatRunsOutOfAddressesGivesBackTheLeaseItTook() {
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
|
||||
String subnetId = privateSubnet(service, "us-east-1", "10.60.0.0/28");
|
||||
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
|
||||
.thenReturn(Optional.of("10.60.0.5"), Optional.empty());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.createNatGateway("us-east-1", subnetId,
|
||||
null, "private", null, List.of(), List.of(), "31", List.of()));
|
||||
assertEquals("InsufficientFreeAddressesInSubnet", e.getErrorCode());
|
||||
verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "10.60.0.5");
|
||||
assertTrue(service.describeNatGateways("us-east-1", List.of(), Map.of()).isEmpty());
|
||||
}
|
||||
|
||||
/** The same on a secondary-address update, which also leaves the gateway as it was. */
|
||||
@Test
|
||||
void aNatGatewayUpdateThatRunsOutOfAddressesGivesBackTheLeaseItTook() {
|
||||
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
|
||||
Ec2Service service = mockedVpcNetworkService(vpcNetworks);
|
||||
String subnetId = privateSubnet(service, "us-east-1", "10.60.0.0/28");
|
||||
when(vpcNetworks.allocatePrivateIp("us-east-1", subnetId))
|
||||
.thenReturn(Optional.of("10.60.0.6"), Optional.of("10.60.0.7"), Optional.empty());
|
||||
NatGateway nat = service.createNatGateway("us-east-1", subnetId, null, "private", List.of());
|
||||
assertEquals("10.60.0.6", nat.getNatGatewayAddresses().getFirst().getPrivateIp());
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.updateNatGatewaySecondaryAddresses(
|
||||
"us-east-1", nat.getNatGatewayId(), List.of(), List.of(), "31"));
|
||||
assertEquals("InsufficientFreeAddressesInSubnet", e.getErrorCode());
|
||||
verify(vpcNetworks).releasePrivateIp("us-east-1", subnetId, "10.60.0.7");
|
||||
assertEquals(List.of("10.60.0.6"), service.describeNatGateways("us-east-1", List.of(nat.getNatGatewayId()),
|
||||
Map.of()).getFirst().getNatGatewayAddresses().stream().map(NatGatewayAddress::getPrivateIp).toList(),
|
||||
"the gateway keeps only its primary address");
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateTags writes a NAT gateway back under the gateway's tag lock, which DeleteNatGateway
|
||||
* does not take, so a tag write that read the gateway before a delete stores the record the
|
||||
* delete marked deleted. A secondary-address update must refuse that record rather than hold
|
||||
* Elastic IPs for it.
|
||||
*/
|
||||
@Test
|
||||
void aSecondaryAddressUpdateRefusesAGatewayStoredAsDeleted() throws Exception {
|
||||
CountDownLatch putReached = new CountDownLatch(1);
|
||||
CountDownLatch deleteDone = new CountDownLatch(1);
|
||||
AtomicReference<Boolean> pausePut = new AtomicReference<>(false);
|
||||
InMemoryStorage<String, NatGateway> rawGateways = new InMemoryStorage<>() {
|
||||
@Override
|
||||
public void put(String key, NatGateway value) {
|
||||
if (pausePut.getAndSet(false)) {
|
||||
putReached.countDown();
|
||||
try {
|
||||
assertTrue(deleteDone.await(5, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
};
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-nat-gateways.json",
|
||||
new AccountAwareStorageBackend<>(rawGateways, null, "000000000000"))));
|
||||
String region = "us-east-1";
|
||||
String subnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String primary = service.allocateAddress(region).getAllocationId();
|
||||
String added = service.allocateAddress(region).getAllocationId();
|
||||
String natId = service.createNatGateway(region, subnetId, primary, "public", List.of()).getNatGatewayId();
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
pausePut.set(true);
|
||||
Future<?> tagging = worker.submit(() -> service.createTags(region, List.of(natId),
|
||||
List.of(new Tag("k", "v"))));
|
||||
assertTrue(putReached.await(5, TimeUnit.SECONDS), "the tag write reaches its put");
|
||||
service.deleteNatGateway(region, natId);
|
||||
deleteDone.countDown();
|
||||
tagging.get(5, TimeUnit.SECONDS);
|
||||
assertEquals("deleted", rawGateways.scan(k -> true).getFirst().getState(),
|
||||
"the tag write stored the deleted gateway");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.updateNatGatewaySecondaryAddresses(
|
||||
region, natId, List.of(added), List.of(), null));
|
||||
assertEquals("NatGatewayNotFound", e.getErrorCode());
|
||||
assertNull(service.describeAddresses(region, List.of(added), Map.of()).getFirst().getAssociationId(),
|
||||
"the requested Elastic IP is not held for the deleted gateway");
|
||||
} finally {
|
||||
worker.shutdownNow();
|
||||
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway persisted before account isolation (unprefixed key) still holds its Elastic IP:
|
||||
* a second gateway is created failed, and ReleaseAddress answers InvalidIPAddress.InUse.
|
||||
|
||||
Reference in new issue
Block a user