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:
Allen Sanborn authored and GitHub committed 2026-11-03 14:15:02 -04:00
1 parent eb65ad88d2
commit fbfe9048a1
11 files changed
+1068 -146

No files matched your search

@@ -184,6 +184,14 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
ec2Service.createTags(region, List.of(entityId), toTagList(priorTags));
}
}
if (prior.has("natSecondaries")) {
JsonNode before = prior.get("natSecondaries");
List<String> eips = new ArrayList<>();
List<String> ips = new ArrayList<>();
before.path("allocationIds").forEach(id -> eips.add(id.asText()));
before.path("privateIps").forEach(ip -> ips.add(ip.asText()));
ec2Service.updateNatGatewaySecondaryAddresses(region, entityId, eips, ips, null);
}
if (prior.has("mapPublicIpOnLaunch")) {
ec2Service.modifySubnetAttribute(region, entityId, "mapPublicIpOnLaunch", prior.get("mapPublicIpOnLaunch").asText());
}
@@ -386,6 +394,46 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
.anyMatch(ip -> CidrCanonicalizer.sameBlock(ip + "/32", privateIpAddress + "/32"));
}
/**
* Whether the gateway's secondary addresses are the ones the template asks for: the same
* Elastic IPs in order, each listed private address at its position, and as many in all.
*/
private static boolean holdsSecondaries(NatGateway nat, List<String> allocationIds, List<String> privateIps,
int count) {
List<NatGatewayAddress> secondaries = nat.getNatGatewayAddresses().stream()
.filter(a -> !a.isPrimary())
.toList();
if (secondaries.size() != Math.max(allocationIds.size(), privateIps.size()) + count
|| !secondaries.stream().map(NatGatewayAddress::getAllocationId).filter(Objects::nonNull).toList()
.equals(allocationIds)) {
return false;
}
for (int i = 0; i < privateIps.size(); i++) {
String held = secondaries.get(i).getPrivateIp();
if (held == null || !CidrCanonicalizer.sameBlock(held + "/32", privateIps.get(i) + "/32")) {
return false;
}
}
return true;
}
/**
* The gateway's secondary addresses as the request that sets them back: the Elastic IPs in
* order (they come first, see {@link Ec2Service#createNatGateway}) and every private address.
*/
private static ObjectNode natSecondaries(NatGateway nat) {
ObjectNode node = MAPPER.createObjectNode();
ArrayNode eips = node.putArray("allocationIds");
ArrayNode ips = node.putArray("privateIps");
nat.getNatGatewayAddresses().stream().filter(a -> !a.isPrimary()).forEach(a -> {
if (a.getAllocationId() != null) {
eips.add(a.getAllocationId());
}
ips.add(a.getPrivateIp());
});
return node;
}
private ManagedPrefixList findPrefixList(String prefixListId, String region) {
return tolerateNotFound(() -> ec2Service.describeManagedPrefixLists(region, List.of(prefixListId), Map.of())
.stream().findFirst().orElse(null), "InvalidPrefixListID.NotFound", prefixListId);
@@ -603,9 +651,9 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
private void provisionNatGateway(StackResource r, JsonNode props, ProvisionContext ctx) {
Ec2Service.requireZonalNatGateway(ctx.resolveOptional(props, "AvailabilityMode"));
Ec2Service.requireNoSecondaryNatGatewayAddresses(ctx.resolveStringList(props, "SecondaryAllocationIds"),
ctx.resolveStringList(props, "SecondaryPrivateIpAddresses"),
ctx.resolveOptional(props, "SecondaryPrivateIpAddressCount"));
List<String> secondaryAllocationIds = ctx.resolveStringList(props, "SecondaryAllocationIds");
List<String> secondaryPrivateIps = ctx.resolveStringList(props, "SecondaryPrivateIpAddresses");
String secondaryCount = ctx.resolveOptional(props, "SecondaryPrivateIpAddressCount");
String subnetId = ctx.resolveOptional(props, "SubnetId");
String allocationId = ctx.resolveOptional(props, "AllocationId");
String privateIpAddress = ctx.resolveOrDefault(props, "PrivateIpAddress", null);
@@ -622,7 +670,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
// SubnetId, AllocationId, ConnectivityType and PrivateIpAddress are createOnly: the same
// values keep the gateway, a change replaces it. With no PrivateIpAddress the gateway keeps
// the address it was given.
// the address it was given. The Secondary* properties are not createOnly: the gateway is
// kept and its secondary addresses are changed in place.
NatGateway existing = ctx.isUpdate() ? findNatGateway(ctx.priorPhysicalId(), ctx.region()) : null;
boolean reuse = existing != null && Objects.equals(subnetId, existing.getSubnetId())
&& Objects.equals(allocationId, existing.getAllocationId())
@@ -630,14 +679,27 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
&& (privateIpAddress == null || holdsPrivateIp(existing, privateIpAddress));
NatGateway nat = reuse ? existing
: ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, privateIpAddress,
tagList(props, ctx));
secondaryAllocationIds, secondaryPrivateIps, secondaryCount, tagList(props, ctx));
if ("failed".equals(nat.getState())) {
// The resource fails and its failed gateway is not left behind.
ec2Service.deleteNatGateway(ctx.region(), nat.getNatGatewayId());
throw new AwsException(nat.getFailureCode(), nat.getFailureMessage(), 400);
}
NatGateway[] current = {nat};
int secondaryCountValue = Ec2Service.secondaryPrivateIpCount(secondaryCount, "private".equals(connectivityType));
if (reuse) {
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx));
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
if (!holdsSecondaries(existing, secondaryAllocationIds, secondaryPrivateIps, secondaryCountValue)) {
ObjectNode prior = inPlacePrior(r, existing.getNatGatewayId(), ctx);
if (!prior.has("natSecondaries")) {
prior.set("natSecondaries", natSecondaries(existing));
writeInPlacePrior(r, prior);
}
current[0] = ec2Service.updateNatGatewaySecondaryAddresses(ctx.region(), existing.getNatGatewayId(),
secondaryAllocationIds, secondaryPrivateIps, secondaryCount);
}
applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx);
});
}
r.setPhysicalId(nat.getNatGatewayId());
r.getAttributes().put("NatGatewayId", nat.getNatGatewayId());
@@ -652,6 +714,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
if (nat.getSubnetId() != null) {
r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "SubnetId", nat.getSubnetId());
}
// Each secondary Elastic IP is held as the primary one is.
r.getAttributes().keySet().removeIf(k -> k.startsWith(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp."));
List<String> secondaryPublicIps = current[0].getNatGatewayAddresses().stream()
.filter(a -> !a.isPrimary() && a.getPublicIp() != null)
.map(NatGatewayAddress::getPublicIp)
.toList();
for (int i = 0; i < secondaryPublicIps.size(); i++) {
r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "SecondaryPublicIp." + i, secondaryPublicIps.get(i));
}
Address eip = allocationId == null || allocationId.isBlank() ? null : findAddress(allocationId, null, ctx.region());
if (eip != null && eip.getPublicIp() != null) {
r.getAttributes().put(CfnRollback.USES_ATTR_PREFIX + "PublicIp", eip.getPublicIp());
@@ -4481,14 +4481,15 @@ public class Ec2QueryHandler {
private Response handleCreateNatGateway(MultivaluedMap<String, String> p, String region) {
Ec2Service.requireZonalNatGateway(p.getFirst("AvailabilityMode"));
Ec2Service.requireNoSecondaryNatGatewayAddresses(getList(p, "SecondaryAllocationId"),
getList(p, "SecondaryPrivateIpAddress"), p.getFirst("SecondaryPrivateIpAddressCount"));
NatGateway natGateway = service.createNatGateway(
region,
p.getFirst("SubnetId"),
p.getFirst("AllocationId"),
p.getFirst("ConnectivityType"),
p.getFirst("PrivateIpAddress"),
getList(p, "SecondaryAllocationId"),
getList(p, "SecondaryPrivateIpAddress"),
p.getFirst("SecondaryPrivateIpAddressCount"),
parseTagsForResource(p, "natgateway"));
XmlBuilder xml = new XmlBuilder()
.start("CreateNatGatewayResponse", AwsNamespaces.EC2)
@@ -4568,6 +4568,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// failed launch is still giving it back keeps it without one.
if (allocated.isPresent()) {
held = privateIpsHeldOnVpcNetwork(region, subnetId);
held.addAll(pending);
}
List<String> skipped = new ArrayList<>();
while (allocated.isPresent() && held.contains(allocated.get())) {
@@ -12377,49 +12378,58 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
/**
* Refuses the secondary-address parameters. Floci gives a NAT gateway its primary address only,
* so a gateway created with them would report fewer addresses than it was asked for.
*/
public static void requireNoSecondaryNatGatewayAddresses(List<String> secondaryAllocationIds,
List<String> secondaryPrivateIpAddresses,
String secondaryPrivateIpAddressCount) {
if (!secondaryAllocationIds.isEmpty() || !secondaryPrivateIpAddresses.isEmpty()
|| isSet(secondaryPrivateIpAddressCount)) {
throw new AwsException("UnsupportedOperation",
"NAT gateways with secondary addresses are not supported.", 400);
}
}
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
String connectivityType, List<Tag> natGatewayTags) {
return createNatGateway(region, subnetId, allocationId, connectivityType, null, natGatewayTags);
}
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
String connectivityType, String privateIpAddress,
List<Tag> natGatewayTags) {
return createNatGateway(region, subnetId, allocationId, connectivityType, privateIpAddress,
List.of(), List.of(), null, natGatewayTags);
}
/**
* @param privateIpAddress PrivateIpAddress: the private address of the gateway's interface, or
* null to let the subnet pick one. It is checked as RunInstances checks
* its own: an assignable address of the subnet that no other resource
* holds.
* @param secondaryAllocationIds SecondaryAllocationIds: extra Elastic IPs, public gateways only.
* Each is paired with the secondary private address at the same
* position, or one the subnet picks.
* @param secondaryPrivateIpAddresses SecondaryPrivateIpAddresses, checked as PrivateIpAddress is
* @param secondaryPrivateIpAddressCount SecondaryPrivateIpAddressCount, private gateways only,
* 1 to 31: that many more addresses the subnet picks
*/
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
String connectivityType, String privateIpAddress,
List<String> secondaryAllocationIds,
List<String> secondaryPrivateIpAddresses,
String secondaryPrivateIpAddressCount,
List<Tag> natGatewayTags) {
ensureDefaultResources(region);
Subnet subnet = requireSubnet(region, subnetId);
boolean privateGateway = "private".equalsIgnoreCase(connectivityType);
if (privateGateway && isSet(allocationId)) {
List<String> secondaryEips = secondaryAllocationIds == null ? List.of() : secondaryAllocationIds;
if (privateGateway && (isSet(allocationId) || !secondaryEips.isEmpty())) {
// A private NAT gateway has no route to the internet and so nothing to attach an
// Elastic IP to. Accepting the pair would have the response report a public address
// on a gateway that cannot have one.
throw new AwsException("InvalidParameterCombination",
"Elastic IP addresses cannot be associated with private NAT gateways.", 400);
}
int secondaryCount = secondaryPrivateIpCount(secondaryPrivateIpAddressCount, privateGateway);
if (isSet(allocationId)) {
getRequiredAddress(region, allocationId);
}
secondaryEips.forEach(id -> getRequiredAddress(region, id));
String requestedPrivateIp = isSet(privateIpAddress)
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
List<String> requestedSecondaryIps = (secondaryPrivateIpAddresses == null ? List.<String>of()
: secondaryPrivateIpAddresses).stream()
.map(ip -> validateRequestedPrivateIp(ip, subnet, null, 1))
.toList();
NatGateway natGateway = new NatGateway();
natGateway.setNatGatewayId("nat-" + randomHex(17));
@@ -12434,31 +12444,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// cannot both see the allocation free. As on AWS, an allocation already held by an
// instance or another gateway does not fail the call: the gateway is created in state
// failed, with no interface, and the allocation is left with its holder.
List<String> eips = new ArrayList<>();
if (isSet(allocationId)) {
Address held = getRequiredAddress(region, allocationId);
// The gateway scan covers gateways persisted before the Address record was marked.
if (isSet(held.getAssociationId()) || isSet(held.getInstanceId())
|| isHeldByNatGateway(region, allocationId)) {
eips.add(allocationId);
}
eips.addAll(secondaryEips);
Set<String> seen = new HashSet<>();
for (String eipId : eips) {
if (!seen.add(eipId) || isElasticIpTaken(region, eipId)) {
natGateway.setState("failed");
natGateway.setFailureCode("Resource.AlreadyAssociated");
natGateway.setFailureMessage("Elastic IP address " + allocationId + " is already associated");
natGateway.setFailureMessage("Elastic IP address " + eipId + " is already associated");
break;
}
}
if (!"failed".equals(natGateway.getState())) {
NatGatewayAddress gatewayAddress = natGatewayAddress(region, natGateway.getNatGatewayId(),
subnetId, allocationId, requestedPrivateIp);
natGateway.getNatGatewayAddresses().add(gatewayAddress);
// The Elastic IP is now held by the gateway's interface, so DescribeAddresses has to
// say so: an allocation that looks free is one Terraform and the console would offer
// to reuse. No instanceId, a NAT gateway is not an instance.
if (isSet(allocationId)) {
addresses.get(key(region, allocationId)).ifPresent(eip -> {
eip.setAssociationId(gatewayAddress.getAssociationId());
eip.setNetworkInterfaceId(gatewayAddress.getNetworkInterfaceId());
eip.setPrivateIpAddress(gatewayAddress.getPrivateIp());
addresses.put(key(region, allocationId), eip);
});
}
natGateway.getNatGatewayAddresses().addAll(natGatewayAddresses(region, natGateway.getNatGatewayId(),
subnetId, allocationId, requestedPrivateIp, secondaryEips, requestedSecondaryIps, secondaryCount));
natGateway.getNatGatewayAddresses().forEach(a -> holdNatGatewayEip(region, a));
}
if (natGatewayTags != null && !natGatewayTags.isEmpty()) {
natGateway.setTags(new ArrayList<>(natGatewayTags));
@@ -12469,28 +12472,115 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return natGateway;
}
/**
* SecondaryPrivateIpAddressCount as a number, 0 when absent. The EC2 API reference marks it
* "[Private NAT gateway only]" with a valid range of 1 to 31.
*/
public static int secondaryPrivateIpCount(String value, boolean privateGateway) {
if (!isSet(value)) {
return 0;
}
if (!privateGateway) {
throw new AwsException("InvalidParameterCombination",
"SecondaryPrivateIpAddressCount is only valid for private NAT gateways.", 400);
}
int count;
try {
count = Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
count = 0;
}
if (count < 1 || count > 31) {
throw new AwsException("InvalidParameterValue",
"Value (" + value + ") for parameter SecondaryPrivateIpAddressCount is invalid. "
+ "It must be between 1 and 31.", 400);
}
return count;
}
/**
* The primary address, then each secondary one, all on the gateway's one interface. Every
* requested address is checked free before any is assigned, so a request that fails leaves no
* lease behind. Callers must hold {@link #privateIpAllocationLock}.
*/
private List<NatGatewayAddress> natGatewayAddresses(String region, String natGatewayId, String subnetId,
String allocationId, String requestedPrivateIp,
List<String> secondaryEips, List<String> requestedSecondaryIps,
int secondaryCount) {
List<String> requested = new ArrayList<>(requestedSecondaryIps);
if (requestedPrivateIp != null) {
requested.add(requestedPrivateIp);
}
Set<String> pending = new HashSet<>();
for (String ip : requested) {
if (!pending.add(ip)) {
throw new AwsException("InvalidIPAddress.InUse", "Address " + ip + " is in use.", 400);
}
requireRequestedPrivateIpFree(region, subnetId, ip);
}
List<String> eips = new ArrayList<>();
eips.add(allocationId);
eips.addAll(secondaryEips);
List<String> ips = new ArrayList<>();
ips.add(requestedPrivateIp);
ips.addAll(requestedSecondaryIps);
NatGatewayAddress[] slots = new NatGatewayAddress[
1 + Math.max(secondaryEips.size(), requestedSecondaryIps.size()) + secondaryCount];
fillNatGatewaySlots(region, natGatewayId, subnetId, slots, eips, ips, pending);
slots[0].setPrimary(true);
return new ArrayList<>(List.of(slots));
}
/**
* Builds an address for every empty slot from the Elastic IP and private address at the same
* position of {@code eips} and {@code ips}, either of which may be shorter than {@code slots}
* or hold null. A slot with no private address takes the next free one; if any slot fails, the
* addresses taken here are given back. Every address built is secondary. Callers must hold
* {@link #privateIpAllocationLock} and have checked the requested addresses free.
*
* @param pending addresses already spoken for, which automatic assignment must not hand out
*/
private void fillNatGatewaySlots(String region, String natGatewayId, String subnetId, NatGatewayAddress[] slots,
List<String> eips, List<String> ips, Set<String> pending) {
List<String> assigned = new ArrayList<>();
try {
for (int i = 0; i < slots.length; i++) {
if (slots[i] != null) {
continue;
}
String ip = i < ips.size() ? ips.get(i) : null;
if (ip == null) {
ip = assignPrivateIp(region, subnetId, pending);
pending.add(ip);
assigned.add(ip);
}
slots[i] = natGatewayAddress(region, natGatewayId, i < eips.size() ? eips.get(i) : null, ip);
slots[i].setPrimary(false);
}
} catch (AwsException e) {
if (vpcNetworkManager != null) {
assigned.forEach(ip -> vpcNetworkManager.releasePrivateIp(region, subnetId, ip));
}
throw e;
}
}
/**
* The address a NAT gateway reports. AWS gives every gateway an interface in its subnet with a
* private address, and a public one additionally carries the Elastic IP it was created with,
* aws_nat_gateway exposes all three as resource outputs (public_ip, private_ip,
* network_interface_id), and Gruntwork's VPC modules re-export nat_gateway_public_ips, so an
* address carrying only an allocation id propagates empty values into dependent modules.
* Callers must hold {@link #privateIpAllocationLock}.
* Every address of one gateway shares its one interface.
*
* @param requestedPrivateIp the request's PrivateIpAddress, already checked by
* {@link #validateRequestedPrivateIp}, or null. It takes no lease on
* the VPC network (see {@link #requireRequestedPrivateIpFree}).
* @param privateIp the address, already checked free. A requested one takes no lease on the
* VPC network (see {@link #requireRequestedPrivateIpFree}).
*/
private NatGatewayAddress natGatewayAddress(String region, String natGatewayId, String subnetId,
String allocationId, String requestedPrivateIp) {
private NatGatewayAddress natGatewayAddress(String region, String natGatewayId, String allocationId,
String privateIp) {
NatGatewayAddress address = new NatGatewayAddress();
address.setNetworkInterfaceId(eniIdFromSeed("nat|" + natGatewayId));
if (requestedPrivateIp != null) {
requireRequestedPrivateIpFree(region, subnetId, requestedPrivateIp);
address.setPrivateIp(requestedPrivateIp);
} else {
address.setPrivateIp(assignPrivateIp(region, subnetId));
}
address.setPrivateIp(privateIp);
if (isSet(allocationId)) {
address.setAllocationId(allocationId);
address.setAssociationId("eipassoc-" + randomHex(17));
@@ -12515,11 +12605,28 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (subnet == null) {
return List.of();
}
List<NetworkInterface> result = new ArrayList<>();
Map<String, NetworkInterface> result = new LinkedHashMap<>();
for (NatGatewayAddress address : natGateway.getNatGatewayAddresses()) {
if (address.getNetworkInterfaceId() == null) {
continue;
}
NetworkInterfacePrivateIpAddress ip = new NetworkInterfacePrivateIpAddress();
ip.setPrivateIpAddress(address.getPrivateIp());
ip.setPrimary(address.isPrimary());
if (address.getPublicIp() != null) {
NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation();
assoc.setPublicIp(address.getPublicIp());
assoc.setAllocationId(address.getAllocationId());
assoc.setAssociationId(address.getAssociationId());
assoc.setIpOwnerId(ownerId);
ip.setAssociation(assoc);
}
// A secondary address sits on the primary address's interface.
NetworkInterface existing = result.get(address.getNetworkInterfaceId());
if (existing != null) {
existing.getPrivateIpAddresses().add(ip);
continue;
}
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId(address.getNetworkInterfaceId());
ni.setSubnetId(natGateway.getSubnetId());
@@ -12530,21 +12637,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
ni.setRequesterManaged(true);
ni.setOwnerId(ownerId);
ni.setPrivateIpAddress(address.getPrivateIp());
NetworkInterfacePrivateIpAddress primaryIp = new NetworkInterfacePrivateIpAddress();
primaryIp.setPrivateIpAddress(address.getPrivateIp());
primaryIp.setPrimary(true);
if (address.getPublicIp() != null) {
NetworkInterfaceAssociation assoc = new NetworkInterfaceAssociation();
assoc.setPublicIp(address.getPublicIp());
assoc.setAllocationId(address.getAllocationId());
assoc.setAssociationId(address.getAssociationId());
assoc.setIpOwnerId(ownerId);
primaryIp.setAssociation(assoc);
}
ni.getPrivateIpAddresses().add(primaryIp);
result.add(ni);
ni.getPrivateIpAddresses().add(ip);
result.put(address.getNetworkInterfaceId(), ni);
}
return result;
return new ArrayList<>(result.values());
}
public List<NatGateway> describeNatGateways(String region, List<String> natGatewayIds,
@@ -12575,20 +12671,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// the lock createNatGateway takes, so a concurrent create cannot have its association wiped.
synchronized (privateIpAllocationLock) {
natGateway.setState("deleted");
for (NatGatewayAddress gatewayAddress : natGateway.getNatGatewayAddresses()) {
if (!isSet(gatewayAddress.getAllocationId())) {
continue;
}
addresses.get(key(region, gatewayAddress.getAllocationId()))
.filter(eip -> gatewayAddress.getAssociationId() != null
&& gatewayAddress.getAssociationId().equals(eip.getAssociationId()))
.ifPresent(eip -> {
eip.setAssociationId(null);
eip.setNetworkInterfaceId(null);
eip.setPrivateIpAddress(null);
addresses.put(key(region, eip.getAllocationId()), eip);
});
}
natGateway.getNatGatewayAddresses().forEach(a -> releaseNatGatewayEip(region, a));
natGateways.delete(key(region, natGatewayId));
removeTags(region, natGatewayId);
natGateway.getNatGatewayAddresses().forEach(a -> removeTags(region, a.getNetworkInterfaceId()));
@@ -12596,6 +12679,160 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return natGateway;
}
/**
* Sets a gateway's secondary addresses to the ones given, as AssociateNatGatewayAddress,
* DisassociateNatGatewayAddress, AssignPrivateNatGatewayAddress and
* UnassignPrivateNatGatewayAddress together would, keeping the gateway and its id: a secondary
* the request still names is kept, one it no longer names is dropped and its Elastic IP handed
* back, and a new one is checked as {@link #createNatGateway} checks it. Every check runs before
* anything changes, so a refused request leaves the gateway as it was. The arguments mean what
* they mean to {@link #createNatGateway}.
*/
public NatGateway updateNatGatewaySecondaryAddresses(String region, String natGatewayId,
List<String> secondaryAllocationIds,
List<String> secondaryPrivateIpAddresses,
String secondaryPrivateIpAddressCount) {
ensureDefaultResources(region);
NatGateway requested = getRequiredNatGateway(region, natGatewayId);
String subnetId = requested.getSubnetId();
Subnet subnet = requireSubnet(region, subnetId);
boolean privateGateway = "private".equalsIgnoreCase(requested.getConnectivityType());
List<String> eips = nullToEmpty(secondaryAllocationIds);
if (privateGateway && !eips.isEmpty()) {
throw new AwsException("InvalidParameterCombination",
"Elastic IP addresses cannot be associated with private NAT gateways.", 400);
}
int count = secondaryPrivateIpCount(secondaryPrivateIpAddressCount, privateGateway);
eips.forEach(id -> getRequiredAddress(region, id));
List<String> ips = nullToEmpty(secondaryPrivateIpAddresses).stream()
.map(ip -> validateRequestedPrivateIp(ip, subnet, null, 1))
.toList();
if (new HashSet<>(ips).size() != ips.size()) {
throw new AwsException("InvalidIPAddress.InUse", "A secondary address is listed twice.", 400);
}
int slots = Math.max(eips.size(), ips.size()) + count;
synchronized (privateIpAllocationLock) {
// Read again under the lock DeleteNatGateway takes, so a gateway deleted since the read
// above is refused rather than written back holding its Elastic IPs again.
NatGateway natGateway = getRequiredNatGateway(region, natGatewayId);
if ("deleted".equals(natGateway.getState())) {
throw new AwsException("NatGatewayNotFound", "NatGateway " + natGatewayId + " was not found", 400);
}
List<NatGatewayAddress> dropped = new ArrayList<>(natGateway.getNatGatewayAddresses().stream()
.filter(a -> !a.isPrimary()).toList());
NatGatewayAddress[] result = new NatGatewayAddress[slots];
// A slot naming an Elastic IP or an address keeps the secondary that already matches it;
// the counted slots then keep the last of the other secondaries with neither. Slot
// position is the only record of where an address came from: counted addresses usually
// follow the listed ones, so the last are usually ones the subnet picked rather than
// listed ones the request dropped. Across updates an address once listed can move
// behind a picked one, and then it is the one kept.
for (int i = 0; i < slots; i++) {
String eip = i < eips.size() ? eips.get(i) : null;
String ip = i < ips.size() ? ips.get(i) : null;
if (eip != null || ip != null) {
result[i] = takeFirst(dropped, a -> Objects.equals(eip, a.getAllocationId())
&& (ip == null || ip.equals(a.getPrivateIp())));
}
}
int listed = Math.max(eips.size(), ips.size());
List<NatGatewayAddress> unlisted = dropped.stream()
.filter(a -> a.getAllocationId() == null && !ips.contains(a.getPrivateIp()))
.toList();
List<NatGatewayAddress> counted = unlisted.subList(Math.max(0, unlisted.size() - count), unlisted.size());
for (int i = 0; i < counted.size(); i++) {
result[listed + i] = counted.get(i);
dropped.remove(counted.get(i));
}
Set<String> droppedEips = new HashSet<>();
Set<String> droppedIps = new HashSet<>();
dropped.forEach(a -> {
addIfSet(droppedEips, a.getAllocationId());
addIfSet(droppedIps, a.getPrivateIp());
});
Set<String> seen = new HashSet<>();
for (int i = 0; i < slots; i++) {
if (result[i] != null) {
continue;
}
String eip = i < eips.size() ? eips.get(i) : null;
if (eip != null && (!seen.add(eip) || !droppedEips.contains(eip) && isElasticIpTaken(region, eip))) {
throw new AwsException("Resource.AlreadyAssociated",
"Elastic IP address " + eip + " is already associated", 400);
}
String ip = i < ips.size() ? ips.get(i) : null;
if (ip != null && !droppedIps.contains(ip)) {
requireRequestedPrivateIpFree(region, subnetId, ip);
}
}
fillNatGatewaySlots(region, natGatewayId, subnetId, result, eips, ips, new HashSet<>(ips));
dropped.forEach(a -> releaseNatGatewayEip(region, a));
List<NatGatewayAddress> addresses = new ArrayList<>(natGateway.getNatGatewayAddresses().stream()
.filter(NatGatewayAddress::isPrimary).toList());
addresses.addAll(List.of(result));
addresses.forEach(a -> holdNatGatewayEip(region, a));
natGateway.setNatGatewayAddresses(addresses);
natGateways.put(key(region, natGatewayId), natGateway);
return natGateway;
}
}
private static <T> T takeFirst(List<T> from, Predicate<T> matching) {
for (T item : from) {
if (matching.test(item)) {
from.remove(item);
return item;
}
}
return null;
}
/**
* Whether an instance or a NAT gateway already holds the Elastic IP. The gateway scan covers
* gateways persisted before the Address record was marked.
*/
private boolean isElasticIpTaken(String region, String allocationId) {
Address held = getRequiredAddress(region, allocationId);
return isSet(held.getAssociationId()) || isSet(held.getInstanceId()) || isHeldByNatGateway(region, allocationId);
}
/**
* Marks the address's Elastic IP held by the gateway's interface, so DescribeAddresses says so:
* an allocation that looks free is one Terraform and the console would offer to reuse. No
* instanceId, a NAT gateway is not an instance. Callers must hold {@link #privateIpAllocationLock}.
*/
private void holdNatGatewayEip(String region, NatGatewayAddress gatewayAddress) {
if (!isSet(gatewayAddress.getAllocationId())) {
return;
}
addresses.get(key(region, gatewayAddress.getAllocationId())).ifPresent(eip -> {
eip.setAssociationId(gatewayAddress.getAssociationId());
eip.setNetworkInterfaceId(gatewayAddress.getNetworkInterfaceId());
eip.setPrivateIpAddress(gatewayAddress.getPrivateIp());
addresses.put(key(region, eip.getAllocationId()), eip);
});
}
/**
* Hands the address's Elastic IP back, but only if the association is still the gateway's own.
* Callers must hold {@link #privateIpAllocationLock}, so a concurrent create cannot have its
* association wiped.
*/
private void releaseNatGatewayEip(String region, NatGatewayAddress gatewayAddress) {
if (!isSet(gatewayAddress.getAllocationId())) {
return;
}
addresses.get(key(region, gatewayAddress.getAllocationId()))
.filter(eip -> gatewayAddress.getAssociationId() != null
&& gatewayAddress.getAssociationId().equals(eip.getAssociationId()))
.ifPresent(eip -> {
eip.setAssociationId(null);
eip.setNetworkInterfaceId(null);
eip.setPrivateIpAddress(null);
addresses.put(key(region, eip.getAllocationId()), eip);
});
}
private NatGateway getRequiredNatGateway(String region, String natGatewayId) {
NatGateway natGateway = natGateways.get(key(region, natGatewayId)).orElse(null);
if (natGateway == null) {