mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 00:45:17 -05:00
fix(ec2): give RunInstances the private address it asks for (#6099)
RunInstances ignored the private address it was given, so every instance got the subnet's next free address. It now reads PrivateIpAddress, NetworkInterface.1.PrivateIpAddress (Terraform), the primary NetworkInterface.1.PrivateIpAddresses entry (AWS CLI) and a launch template's primary interface address. The address is validated (inside the subnet, not reserved, not in use, including by another account's instance, interface or NAT gateway on a shared default VPC network, single instance with its own interface, no instance-level address with network interfaces), leased on the VPC's Docker network, and assigned to the instance and its primary interface. A CloudFormation AWS::EC2::Instance now launches at its declared PrivateIpAddress too. Closes #5830
This commit is contained in:
1 parent
61a42591a9
commit
50e515f17a
13 files changed
+1381
-86
No files matched your search
+25
-16
@@ -17,7 +17,9 @@ import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -35,9 +37,10 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String INSTANCE = "AWS::EC2::Instance";
|
||||
|
||||
// Declared values of createOnly properties the launch does not apply to the instance, recorded
|
||||
// so a later update can tell a genuine change from the instance's auto-assigned value. The
|
||||
// __Floci prefix keeps them off the published Fn::GetAtt attributes.
|
||||
// Declared values of createOnly properties, recorded so a later update compares against what
|
||||
// the template declared rather than what the instance carries: the launch does not apply
|
||||
// AvailabilityZone, and an instance a stack launched before PrivateIpAddress was applied holds
|
||||
// an auto-assigned address. The __Floci prefix keeps them off the published Fn::GetAtt attributes.
|
||||
private static final String DECLARED_PRIVATE_IP_ATTR = "__FlociDeclaredPrivateIpAddress";
|
||||
private static final String DECLARED_AZ_ATTR = "__FlociDeclaredAvailabilityZone";
|
||||
// The instance profile the template declared last time, so an update that drops the property
|
||||
@@ -132,12 +135,12 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
// On update, keep the existing instance unless a createOnly property changed: a changed
|
||||
// ImageId, SubnetId or KeyName replaces it (compared against the instance, which carries
|
||||
// them), as does a changed PrivateIpAddress or AvailabilityZone (compared against the value
|
||||
// declared last time, since the launch does not apply those to the instance). A mutable-only
|
||||
// change (tags, and the like) reuses it. Launching unconditionally would leak the prior
|
||||
// instance every update. A changed LaunchTemplate reuses it too, where AWS replaces the
|
||||
// instance: the change-set preview and the template's own versioning would have to agree on
|
||||
// that property first. What the template declares is reconciled in place instead, unless
|
||||
// the ImageId or KeyName it supplies changed, which replaces the instance as above.
|
||||
// declared last time, see DECLARED_PRIVATE_IP_ATTR). A mutable-only change (tags, and the
|
||||
// like) reuses it. Launching unconditionally would leak the prior instance every update. A
|
||||
// changed LaunchTemplate reuses it too, where AWS replaces the instance: the change-set
|
||||
// preview and the template's own versioning would have to agree on that property first.
|
||||
// What the template declares is reconciled in place instead, unless the ImageId or KeyName
|
||||
// it supplies changed, which replaces the instance as above.
|
||||
Instance prior = ctx.isUpdate() ? findInstance(region, ctx.priorPhysicalId()) : null;
|
||||
if (prior != null && !createOnlyChanged(prior, imageId, subnetId, keyName)
|
||||
&& !declaredCreateOnlyChanged(attributesBefore, privateIpAddress, availabilityZone)) {
|
||||
@@ -190,9 +193,15 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (ctx.isUpdate()) {
|
||||
r.getAttributes().put(PRIOR_DECLARATIONS_ATTR, declarations(attributesBefore));
|
||||
}
|
||||
// The options a template cannot set keep the defaults the shorter runInstances overloads
|
||||
// give them. A replacement that keeps its PrivateIpAddress fails with InvalidIPAddress.InUse
|
||||
// while the prior instance still holds it, as on AWS, which creates the replacement first.
|
||||
String encodedUserData = userData == null ? null
|
||||
: Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8));
|
||||
Reservation reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName,
|
||||
securityGroupIds, subnetId, null, tags, userData, iamInstanceProfileArn,
|
||||
associatePublicIp, null, 0, null, metadataOptions);
|
||||
associatePublicIp, null, 0, null, metadataOptions, null, encodedUserData, false, null, null, null,
|
||||
false, privateIpAddress);
|
||||
Instance instance = reservation.getInstances().get(0);
|
||||
r.setPhysicalId(instance.getInstanceId());
|
||||
r.getAttributes().put("InstanceId", instance.getInstanceId());
|
||||
@@ -353,12 +362,12 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a createOnly property the launch does not apply to the instance (PrivateIpAddress,
|
||||
* AvailabilityZone) changed since the last provision. It is compared against the value declared
|
||||
* then and recorded on the resource, not the instance's auto-assigned value, which never matches
|
||||
* a declared one. A property with no recorded prior value is not treated as changed, so adopting
|
||||
* this behavior does not replace instances whose template did not actually change; the value is
|
||||
* recorded from this provision on, and a later change to it then forces replacement.
|
||||
* Whether a createOnly property recorded as declared (PrivateIpAddress, AvailabilityZone) changed
|
||||
* since the last provision. It is compared against the value declared then and recorded on the
|
||||
* resource, not the instance's own, for the reasons given at {@link #DECLARED_PRIVATE_IP_ATTR}.
|
||||
* A property with no recorded prior value is not treated as changed, so adopting this behavior
|
||||
* does not replace instances whose template did not actually change; the value is recorded from
|
||||
* this provision on, and a later change to it then forces replacement.
|
||||
*/
|
||||
private static boolean declaredCreateOnlyChanged(Map<String, String> priorAttributes,
|
||||
String privateIpAddress, String availabilityZone) {
|
||||
|
||||
@@ -770,6 +770,18 @@ public class Ec2QueryHandler {
|
||||
if (subnetId == null) {
|
||||
subnetId = p.getFirst("NetworkInterface.1.SubnetId");
|
||||
}
|
||||
// The primary private address arrives in three shapes. Terraform's aws_instance moves
|
||||
// private_ip onto the interface spec whenever it sends one, and the AWS CLI moves
|
||||
// --private-ip-address there too, as the primary PrivateIpAddresses entry, once an
|
||||
// interface-only option such as --associate-public-ip-address builds the spec. The
|
||||
// top-level form together with any interface spec is refused below.
|
||||
String privateIpAddress = p.getFirst("NetworkInterface.1.PrivateIpAddress");
|
||||
if (!isSet(privateIpAddress)) {
|
||||
privateIpAddress = primaryPrivateIpAddress(p, "NetworkInterface.1");
|
||||
}
|
||||
if (!isSet(privateIpAddress)) {
|
||||
privateIpAddress = p.getFirst("PrivateIpAddress");
|
||||
}
|
||||
// floci-kt9: override-default-eni hands RunInstances a pre-existing standalone ENI as
|
||||
// the instance's primary interface (network_interface { network_interface_id = ... }).
|
||||
String networkInterfaceId = p.getFirst("NetworkInterface.1.NetworkInterfaceId");
|
||||
@@ -804,11 +816,16 @@ public class Ec2QueryHandler {
|
||||
LaunchTemplateData launchTemplateData = resolveRunInstancesLaunchTemplateData(
|
||||
p, region, userDataEncoded == null || userDataEncoded.isBlank());
|
||||
boolean suppliedInterfaces = p.keySet().stream().anyMatch(name -> name.startsWith("NetworkInterface."));
|
||||
if (p.getFirst("SubnetId") != null && (suppliedInterfaces
|
||||
|| launchTemplateData != null && !launchTemplateData.getNetworkInterfaces().isEmpty())) {
|
||||
boolean anyInterfaces = suppliedInterfaces
|
||||
|| launchTemplateData != null && !launchTemplateData.getNetworkInterfaces().isEmpty();
|
||||
if (p.getFirst("SubnetId") != null && anyInterfaces) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Network interfaces and an instance-level subnet ID may not be specified on the same request", 400);
|
||||
}
|
||||
if (p.getFirst("PrivateIpAddress") != null && anyInterfaces) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"Network interfaces and an instance-level private IP address may not be specified on the same request", 400);
|
||||
}
|
||||
if (launchTemplateData != null) {
|
||||
if (marketType == null && launchTemplateData.getInstanceMarketOptions() != null) {
|
||||
marketType = launchTemplateData.getInstanceMarketOptions().getMarketType();
|
||||
@@ -816,11 +833,12 @@ public class Ec2QueryHandler {
|
||||
blockDeviceMappings = LaunchTemplateData.BlockDeviceMapping.merge(
|
||||
launchTemplateData.getBlockDeviceMappings(), blockDeviceMappings);
|
||||
if (!suppliedInterfaces) {
|
||||
// With neither request interfaces nor, after the check above, a request SubnetId,
|
||||
// the template's primary interface places the launch.
|
||||
// With neither request interfaces nor, after the checks above, a request SubnetId
|
||||
// or PrivateIpAddress, the template's primary interface places the launch.
|
||||
LaunchTemplateData.NetworkInterface primary = launchTemplateData.primaryNetworkInterface();
|
||||
if (primary != null) {
|
||||
subnetId = primary.getSubnetId();
|
||||
privateIpAddress = primary.getPrivateIpAddress();
|
||||
if (associatePublicIp == null) {
|
||||
associatePublicIp = primary.getAssociatePublicIpAddress();
|
||||
}
|
||||
@@ -866,7 +884,7 @@ public class Ec2QueryHandler {
|
||||
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions,
|
||||
creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")),
|
||||
p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings,
|
||||
"spot".equals(marketType));
|
||||
"spot".equals(marketType), privateIpAddress);
|
||||
|
||||
if (!networkInterfaceTags.isEmpty()) {
|
||||
List<String> eniIds = new ArrayList<>();
|
||||
@@ -909,6 +927,23 @@ public class Ec2QueryHandler {
|
||||
throw new AwsException("InvalidParameterValue", name + " must be a positive integer", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The address of the {@code PrivateIpAddresses} entry an interface spec marks {@code Primary},
|
||||
* or null when it marks none. Secondary entries are not applied.
|
||||
*/
|
||||
private static String primaryPrivateIpAddress(MultivaluedMap<String, String> p, String interfacePrefix) {
|
||||
for (int i = 1; ; i++) {
|
||||
String entry = interfacePrefix + ".PrivateIpAddresses." + i;
|
||||
String address = p.getFirst(entry + ".PrivateIpAddress");
|
||||
if (address == null) {
|
||||
return null;
|
||||
}
|
||||
if (Boolean.parseBoolean(p.getFirst(entry + ".Primary"))) {
|
||||
return address;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private LaunchTemplateData resolveRunInstancesLaunchTemplateData(MultivaluedMap<String, String> p, String region,
|
||||
boolean decodeUserData) {
|
||||
String id = p.getFirst("LaunchTemplate.LaunchTemplateId");
|
||||
|
||||
@@ -3539,7 +3539,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
|
||||
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone,
|
||||
metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy,
|
||||
blockDeviceMappings, false);
|
||||
blockDeviceMappings, false, null);
|
||||
}
|
||||
|
||||
Reservation runInstances(String region, String imageId, String instanceType,
|
||||
@@ -3553,6 +3553,35 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun,
|
||||
String hostId, String tenancy,
|
||||
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings, boolean spot) {
|
||||
return runInstances(region, imageId, instanceType, minCount, maxCount, keyName,
|
||||
securityGroupIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn,
|
||||
associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, availabilityZone,
|
||||
metadataOptions, creditSpecificationCpuCredits, encodedUserData, dryRun, hostId, tenancy,
|
||||
blockDeviceMappings, spot, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param privateIpAddress PrivateIpAddress: the primary private address of the interface the
|
||||
* launch creates, or null to let the subnet pick one. It must be an
|
||||
* assignable address of the subnet that no other resource holds, and
|
||||
* AWS accepts it only for a single instance launched without an
|
||||
* existing network interface.
|
||||
*/
|
||||
public Reservation runInstances(String region, String imageId, String instanceType,
|
||||
int minCount, int maxCount, String keyName,
|
||||
List<String> securityGroupIds, String subnetId,
|
||||
String clientToken, List<Tag> instanceTags,
|
||||
String userData, String iamInstanceProfileArn,
|
||||
Boolean associatePublicIp, String networkInterfaceId,
|
||||
int networkInterfaceDeviceIndex, String availabilityZone,
|
||||
LaunchTemplateData.MetadataOptions metadataOptions,
|
||||
String creditSpecificationCpuCredits, String encodedUserData, boolean dryRun,
|
||||
String hostId, String tenancy,
|
||||
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings, boolean spot,
|
||||
String privateIpAddress) {
|
||||
if (privateIpAddress != null && privateIpAddress.isBlank()) {
|
||||
privateIpAddress = null;
|
||||
}
|
||||
if (hostId != null && !hostId.isBlank()) {
|
||||
Host host = getRequiredAvailableHost(region, hostId);
|
||||
if ((availabilityZone == null || availabilityZone.isBlank())
|
||||
@@ -3649,6 +3678,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
validateArchitectureCompatibility(region, imageId, effectiveInstanceType);
|
||||
int count = Math.min(maxCount, Math.max(minCount, 1));
|
||||
if (privateIpAddress != null) {
|
||||
privateIpAddress = validateRequestedPrivateIp(privateIpAddress, subnet, suppliedEni, maxCount);
|
||||
}
|
||||
String architecture = architectureFor(region, imageId, effectiveInstanceType);
|
||||
// An entry with NoDevice set removes its device whatever else it names, as on AWS.
|
||||
List<LaunchTemplateData.BlockDeviceMapping> mappedDevices = blockDeviceMappings == null ? List.of()
|
||||
@@ -3699,7 +3731,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// since the unlocked check above.
|
||||
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
|
||||
}
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni, admitted);
|
||||
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
|
||||
privateIpAddress, admitted);
|
||||
for (int i = 0; i < admitted; i++) {
|
||||
String instanceId = "i-" + randomHex(17);
|
||||
String privateIp = privateIps.get(i);
|
||||
@@ -4060,9 +4093,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
* Every private address a launch needs, allocated before any of its instances is stored, so
|
||||
* a subnet without room for the whole launch fails it without leaving the instances that did
|
||||
* fit behind. Callers must hold {@link #privateIpAllocationLock}.
|
||||
*
|
||||
* @param requestedPrivateIp the launch's PrivateIpAddress, already checked by
|
||||
* {@link #validateRequestedPrivateIp}, or null
|
||||
*/
|
||||
private List<String> allocateLaunchAddresses(String region, String subnetId, NetworkInterface suppliedEni,
|
||||
int count) {
|
||||
String requestedPrivateIp, int count) {
|
||||
List<String> addresses = new ArrayList<>(count);
|
||||
if (suppliedEni != null) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
@@ -4070,6 +4106,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
if (requestedPrivateIp != null) {
|
||||
claimRequestedPrivateIp(region, subnetId, requestedPrivateIp);
|
||||
addresses.add(requestedPrivateIp);
|
||||
return addresses;
|
||||
}
|
||||
try {
|
||||
for (int i = 0; i < count; i++) {
|
||||
addresses.add(assignPrivateIp(region, subnetId, addresses));
|
||||
@@ -4117,12 +4158,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
synchronized (privateIpAllocationLock) {
|
||||
// The addresses persisted resources already hold, so a restart, which forgets the
|
||||
// cursor, never hands out an address that is still in use.
|
||||
Set<String> persistedInUse = privateIpsInUse(region, subnetId);
|
||||
Set<String> inUse = new HashSet<>(persistedInUse);
|
||||
// Interface endpoint interfaces are derived, not stored, so the scan above misses them.
|
||||
if (subnetId != null) {
|
||||
inUse.addAll(endpointPrivateIpsIn(region, subnetId, persistedInUse));
|
||||
}
|
||||
Set<String> inUse = privateIpsTaken(region, subnetId);
|
||||
inUse.addAll(pending);
|
||||
long start = Math.clamp(subnetIpCursors.getOrDefault(cursorKey, SYNTHETIC_FIRST_OFFSET), first, last);
|
||||
long span = last - first + 1;
|
||||
@@ -4138,6 +4174,91 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
throw insufficientFreeAddresses(subnetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a launch's PrivateIpAddress before anything is stored. AWS applies it to the primary
|
||||
* interface the launch creates, so it cannot be combined with an existing interface or with
|
||||
* more than one instance, and it has to be an address the subnet can assign. Whether another
|
||||
* resource holds it is checked under the allocation lock, by {@link #claimRequestedPrivateIp}.
|
||||
*
|
||||
* @param subnet the launch's subnet, or null when the region has no default subnet to place
|
||||
* it in, in which case there is no range to check the address against
|
||||
* @param maxCount the launch's MaxCount. A request that may launch more than one instance is
|
||||
* refused even when fewer would be launched.
|
||||
* @return the address in its canonical dotted form. The in-use check, the VPC network's lease
|
||||
* table and Docker all compare addresses as text, so a zero-padded octet must not make
|
||||
* one address look like two.
|
||||
*/
|
||||
private static String validateRequestedPrivateIp(String privateIpAddress, Subnet subnet,
|
||||
NetworkInterface suppliedEni, int maxCount) {
|
||||
if (suppliedEni != null) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"A private IP address may not be specified with an existing network interface.", 400);
|
||||
}
|
||||
if (maxCount > 1) {
|
||||
throw new AwsException("InvalidParameterCombination",
|
||||
"A private IP address may only be specified for a single instance.", 400);
|
||||
}
|
||||
String address = canonicalIpv4(privateIpAddress)
|
||||
.orElseThrow(() -> new AwsException("InvalidParameterValue",
|
||||
"Invalid IPv4 address: " + privateIpAddress, 400));
|
||||
if (subnet != null) {
|
||||
requireAssignableSubnetAddress(subnet, address);
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
/**
|
||||
* Claims the address a launch named, which {@link #validateRequestedPrivateIp} has already
|
||||
* placed inside the subnet. Callers must hold {@link #privateIpAllocationLock}.
|
||||
*
|
||||
* <p>The caller's stored resources decide whether the address is in use. A Docker-backed
|
||||
* subnet also leases it, so the network's own allocator never hands it to a later launch.
|
||||
*
|
||||
* <p>Inside a Docker-backed range, what every account holds counts as well. Default VPC and
|
||||
* subnet ids are the same in every account, so their Docker network is shared, and another
|
||||
* account's instance, network interface or NAT gateway there may hold the address with no
|
||||
* lease to show for it: an interface created with its own address never takes one, and a
|
||||
* restart re-leases only instances. Any other subnet id belongs to one account, so for it the
|
||||
* wider scan finds nothing more. A lease with nothing in any account behind it is stale
|
||||
* (DeleteNetworkInterface and DeleteNatGateway never return theirs) and does not fail the
|
||||
* launch, and an address outside a substituted subnet's effective range is never leased at
|
||||
* all, in which case the instance keeps it the way it keeps a synthesised address.
|
||||
*/
|
||||
private void claimRequestedPrivateIp(String region, String subnetId, String address) {
|
||||
if (privateIpsTaken(region, subnetId).contains(address)) {
|
||||
throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400);
|
||||
}
|
||||
if (vpcNetworkManager == null || subnetId == null) {
|
||||
return;
|
||||
}
|
||||
boolean leasable = vpcNetworkManager.effectiveSubnetCidr(region, subnetId)
|
||||
.filter(cidr -> Ipv4Cidrs.contains(cidr, address + "/32"))
|
||||
.isPresent();
|
||||
if (!leasable) {
|
||||
return;
|
||||
}
|
||||
if (privateIpsInUseInEveryAccount(region, subnetId).contains(address)) {
|
||||
throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400);
|
||||
}
|
||||
vpcNetworkManager.claimPrivateIp(region, subnetId, address);
|
||||
}
|
||||
|
||||
/** {@link #privateIpsInUse}, across every account rather than only the caller's. */
|
||||
private Set<String> privateIpsInUseInEveryAccount(String region, String subnetId) {
|
||||
String regionPrefix = region + "::";
|
||||
return privateIpsBySubnet(valuesOfEveryAccount(networkInterfaces, regionPrefix),
|
||||
valuesOfEveryAccount(instances, regionPrefix),
|
||||
valuesOfEveryAccount(natGateways, regionPrefix))
|
||||
.getOrDefault(subnetId, Set.of());
|
||||
}
|
||||
|
||||
private static <T> List<T> valuesOfEveryAccount(StorageBackend<String, T> store, String keyPrefix) {
|
||||
return entriesOfEveryAccount(store).stream()
|
||||
.filter(entry -> entry.key().startsWith(keyPrefix))
|
||||
.map(AccountAwareStorageBackend.AccountEntry::value)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static AwsException insufficientFreeAddresses(String subnetId) {
|
||||
return new AwsException("InsufficientFreeAddressesInSubnet",
|
||||
"There are not enough free addresses in subnet '" + subnetId + "' to satisfy the requested number of instances.",
|
||||
@@ -4149,17 +4270,36 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
return new HashSet<>(privateIpsBySubnet(region).getOrDefault(subnetId, Set.of()));
|
||||
}
|
||||
|
||||
/** {@link #privateIpsInUse}, plus the addresses of the subnet's interface endpoint interfaces. */
|
||||
private Set<String> privateIpsTaken(String region, String subnetId) {
|
||||
Set<String> persistedInUse = privateIpsInUse(region, subnetId);
|
||||
Set<String> taken = new HashSet<>(persistedInUse);
|
||||
// Interface endpoint interfaces are derived, not stored, so the scan above misses them.
|
||||
if (subnetId != null) {
|
||||
taken.addAll(endpointPrivateIpsIn(region, subnetId, persistedInUse));
|
||||
}
|
||||
return taken;
|
||||
}
|
||||
|
||||
private Map<String, Set<String>> privateIpsBySubnet(String region) {
|
||||
String regionPrefix = region + "::";
|
||||
return privateIpsBySubnet(networkInterfaces.scan(k -> k.startsWith(regionPrefix)),
|
||||
instances.scan(k -> k.startsWith(regionPrefix)),
|
||||
natGateways.scan(k -> k.startsWith(regionPrefix)));
|
||||
}
|
||||
|
||||
private static Map<String, Set<String>> privateIpsBySubnet(List<NetworkInterface> regionInterfaces,
|
||||
List<Instance> regionInstances,
|
||||
List<NatGateway> regionNatGateways) {
|
||||
Map<String, Set<String>> bySubnet = new HashMap<>();
|
||||
for (NetworkInterface ni : networkInterfaces.scan(k -> k.startsWith(regionPrefix))) {
|
||||
for (NetworkInterface ni : regionInterfaces) {
|
||||
Set<String> inUse = bySubnet.computeIfAbsent(ni.getSubnetId(), ignored -> new HashSet<>());
|
||||
addIfSet(inUse, ni.getPrivateIpAddress());
|
||||
for (NetworkInterfacePrivateIpAddress ip : nullToEmpty(ni.getPrivateIpAddresses())) {
|
||||
addIfSet(inUse, ip.getPrivateIpAddress());
|
||||
}
|
||||
}
|
||||
for (Instance instance : instances.scan(k -> k.startsWith(regionPrefix))) {
|
||||
for (Instance instance : regionInstances) {
|
||||
String state = instance.getState() == null ? null : instance.getState().getName();
|
||||
if ("terminated".equals(state)) {
|
||||
continue;
|
||||
@@ -4171,7 +4311,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
ni.getPrivateIpAddress());
|
||||
}
|
||||
}
|
||||
for (NatGateway natGateway : natGateways.scan(k -> k.startsWith(regionPrefix))) {
|
||||
for (NatGateway natGateway : regionNatGateways) {
|
||||
if ("deleted".equals(natGateway.getState())) {
|
||||
continue;
|
||||
}
|
||||
@@ -4189,10 +4329,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
private static void addIfSet(Set<String> addresses, String address) {
|
||||
if (address != null && !address.isBlank()) {
|
||||
addresses.add(address);
|
||||
// CreateNetworkInterface keeps its address as given, so a zero-padded octet has to be
|
||||
// folded here for the in-use checks to see one address rather than two.
|
||||
addresses.add(canonicalIpv4(address).orElse(address));
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code address} in canonical dotted form, or empty when it is not an IPv4 address. */
|
||||
private static Optional<String> canonicalIpv4(String address) {
|
||||
return Cidr4.parse(address + "/32").map(host -> Cidr4.format(host.network()));
|
||||
}
|
||||
|
||||
public List<Reservation> describeInstances(String region, List<String> instanceIds, Map<String, List<String>> filters) {
|
||||
ensureDefaultResources(region);
|
||||
if (!instanceIds.isEmpty()) {
|
||||
@@ -6019,21 +6166,30 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
if (ipv4 == null || ipv4.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String host = ipv4 + "/32";
|
||||
if (!Ipv4Cidrs.isIpv4(host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Invalid IPv4 address: " + ipv4, 400);
|
||||
}
|
||||
if (subnet.getCidrBlock() == null || !Ipv4Cidrs.contains(subnet.getCidrBlock(), host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Address " + ipv4 + " does not fall within the address range of subnet "
|
||||
+ subnet.getSubnetId(), 400);
|
||||
}
|
||||
if (Ipv4Cidrs.isSubnetReserved(subnet.getCidrBlock(), host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Address " + ipv4 + " is reserved by AWS in subnet " + subnet.getSubnetId()
|
||||
+ " and cannot be assigned", 400);
|
||||
}
|
||||
requireAssignableSubnetAddress(subnet, ipv4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects an IPv4 address an interface in {@code subnet} could not take: one that does not
|
||||
* parse, one outside the subnet's CIDR, or one of the five addresses AWS reserves in every
|
||||
* subnet (see {@link Ipv4Cidrs#isSubnetReserved}).
|
||||
*/
|
||||
private static void requireAssignableSubnetAddress(Subnet subnet, String ipv4) {
|
||||
String host = ipv4 + "/32";
|
||||
if (!Ipv4Cidrs.isIpv4(host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Invalid IPv4 address: " + ipv4, 400);
|
||||
}
|
||||
if (subnet.getCidrBlock() == null || !Ipv4Cidrs.contains(subnet.getCidrBlock(), host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Address " + ipv4 + " does not fall within the address range of subnet "
|
||||
+ subnet.getSubnetId(), 400);
|
||||
}
|
||||
if (Ipv4Cidrs.isSubnetReserved(subnet.getCidrBlock(), host)) {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Address " + ipv4 + " is reserved by AWS in subnet " + subnet.getSubnetId()
|
||||
+ " and cannot be assigned", 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -467,6 +467,29 @@ public class VpcNetworkManager {
|
||||
* range, the address is unparseable or outside that range, or it is already leased
|
||||
*/
|
||||
public boolean reservePrivateIp(String region, String subnetId, String address) {
|
||||
return lease(region, subnetId, address, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leases the address a launch named for itself (RunInstances {@code PrivateIpAddress}), so
|
||||
* the next {@link #allocatePrivateIp} never hands it to another instance.
|
||||
*
|
||||
* <p>Unlike {@link #reservePrivateIp}, it leaves the allocation cursor where it is, so the
|
||||
* addresses the subnet picks on its own keep their order, and it logs no refusal: the caller
|
||||
* has already found the address free, so a lease it meets is one its holder never returned.
|
||||
*
|
||||
* @return true when the address is now leased; false when the subnet has no Docker-backed
|
||||
* range, the address is unparseable or outside that range, or it is already leased
|
||||
*/
|
||||
public boolean claimPrivateIp(String region, String subnetId, String address) {
|
||||
return lease(region, subnetId, address, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param restoring whether a restart is re-reserving an address a persisted instance holds,
|
||||
* which warns on refusal and moves the cursor past the address
|
||||
*/
|
||||
private boolean lease(String region, String subnetId, String address, boolean restoring) {
|
||||
if (!enabled() || subnetId == null || address == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -476,20 +499,24 @@ public class VpcNetworkManager {
|
||||
}
|
||||
Optional<Cidr4> parsed = Cidr4.parse(address + "/32");
|
||||
if (parsed.isEmpty() || !subnet.effective.containsAddress(parsed.get().network())) {
|
||||
LOG.warnv("Cannot reserve {0} in subnet {1}: it is outside the subnet''s effective range {2}. "
|
||||
+ "Its holder keeps it, and this manager will not hand it out either, since "
|
||||
+ "it is not an address it allocates from.",
|
||||
String.valueOf(address), subnetId, String.valueOf(subnet.effective));
|
||||
if (restoring) {
|
||||
LOG.warnv("Cannot reserve {0} in subnet {1}: it is outside the subnet''s effective range {2}. "
|
||||
+ "Its holder keeps it, and this manager will not hand it out either, since "
|
||||
+ "it is not an address it allocates from.",
|
||||
String.valueOf(address), subnetId, String.valueOf(subnet.effective));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
synchronized (subnet) {
|
||||
if (!subnet.leased.add(address)) {
|
||||
LOG.warnv("Address {0} in subnet {1} is claimed by more than one instance; the later "
|
||||
+ "claim is ignored.", address, subnetId);
|
||||
if (restoring) {
|
||||
LOG.warnv("Address {0} in subnet {1} is claimed by more than one instance; the later "
|
||||
+ "claim is ignored.", address, subnetId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
long offset = parsed.get().network() - subnet.effective.network();
|
||||
if (offset >= subnet.nextOffset) {
|
||||
if (restoring && offset >= subnet.nextOffset) {
|
||||
subnet.nextOffset = offset + 1;
|
||||
}
|
||||
return true;
|
||||
|
||||
Reference in new issue
Block a user