feat(ec2): retain IPv6 launch metadata and allocation properties (#9418)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-25 06:50:02 -04:00
1 parent 0f5d2c8886
commit 87ff8135a9
11 files changed
+841 -2

No files matched your search

@@ -5,6 +5,7 @@ import io.floci.aws.core.common.AvailabilityZoneIds;
import io.floci.aws.core.common.AwsRegions;
import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
import io.floci.aws.services.iam.IamService;
@@ -30,6 +31,7 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
@@ -38,6 +40,7 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* IMDS-compatible HTTP server bound to port 9169 on the Floci host.
@@ -200,6 +203,19 @@ public class Ec2MetadataServer {
router.get("/latest/meta-data/hostname").handler(ctx -> handleText(ctx, inst -> inst.getPrivateDnsName()));
router.get("/latest/meta-data/mac").handler(ctx -> handleMac(ctx));
router.get("/latest/meta-data/security-groups").handler(ctx -> handleSecurityGroups(ctx));
// IPv6: the primary interface's address, and per interface (keyed by MAC) its addresses and the IPv6
// blocks of its subnet and VPC. Each answers 404 for an interface without IPv6.
router.get("/latest/meta-data/ipv6")
.handler(ctx -> handleText(ctx, Ec2MetadataServer::primaryIpv6));
router.get("/latest/meta-data/network/interfaces/macs").handler(this::handleMacListing);
router.get("/latest/meta-data/network/interfaces/macs/").handler(this::handleMacListing);
router.get("/latest/meta-data/network/interfaces/macs/:mac/ipv6s")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getIpv6Addresses));
router.get("/latest/meta-data/network/interfaces/macs/:mac/subnet-ipv6-cidr-blocks")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getSubnetIpv6CidrBlocks));
router.get("/latest/meta-data/network/interfaces/macs/:mac/vpc-ipv6-cidr-blocks")
.handler(ctx -> handleInterfaceIpv6(ctx, InstanceNetworkInterface::getVpcIpv6CidrBlocks));
router.get("/latest/meta-data/placement/availability-zone").handler(ctx -> handleText(ctx,
this::availabilityZone));
router.get("/latest/meta-data/placement/availability-zone-id").handler(ctx -> handleText(ctx, inst ->
@@ -369,6 +385,61 @@ public class Ec2MetadataServer {
.end(mac != null ? mac : "02:42:ac:11:00:02");
}
private void handleMacListing(RoutingContext ctx) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
return;
}
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain").end(macListing(inst));
}
private void handleInterfaceIpv6(RoutingContext ctx,
Function<InstanceNetworkInterface, List<String>> values) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
return;
}
Optional<String> answer = interfaceValues(inst, ctx.pathParam("mac"), values);
if (answer.isEmpty()) {
ctx.response().setStatusCode(404).end("not-available");
return;
}
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain").end(answer.get());
}
/** The primary interface's first IPv6 address, the {@code meta-data/ipv6} answer; null without one. */
static String primaryIpv6(Instance inst) {
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getDeviceIndex() == 0 && !eni.getIpv6Addresses().isEmpty()) {
return eni.getIpv6Addresses().get(0);
}
}
return null;
}
/** {@code network/interfaces/macs/}: one {@code <mac>/} line per interface. */
static String macListing(Instance inst) {
StringBuilder sb = new StringBuilder();
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getMacAddress() != null) {
sb.append(sb.isEmpty() ? "" : "\n").append(eni.getMacAddress()).append('/');
}
}
return sb.toString();
}
/** One line per value of the interface with this MAC, or empty (404) when it has none, as IMDS answers. */
static Optional<String> interfaceValues(Instance inst, String mac,
Function<InstanceNetworkInterface, List<String>> values) {
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (mac != null && mac.equalsIgnoreCase(eni.getMacAddress())) {
List<String> found = values.apply(eni);
return found.isEmpty() ? Optional.empty() : Optional.of(String.join("\n", found));
}
}
return Optional.empty();
}
private void handleSecurityGroups(RoutingContext ctx) {
Instance inst = resolveInstance(ctx);
if (inst == null) {
@@ -5604,6 +5604,14 @@ public class Ec2QueryHandler {
ipv6Addresses.add(p.getFirst("Ipv6Addresses." + i + ".Ipv6Address"));
}
Integer ipv6AddressCount = parseOptionalInt(p.getFirst("Ipv6AddressCount"), "Ipv6AddressCount");
if (ipv6AddressCount != null) {
for (String other : List.of("Ipv6Addresses.1.Ipv6Address", "Ipv6Prefix.1.Ipv6Prefix", "Ipv6PrefixCount")) {
if (p.getFirst(other) != null) {
throw new AwsException("InvalidParameterCombination",
"Ipv6AddressCount cannot be combined with " + other.split("\\.", 2)[0] + ".", 400);
}
}
}
NetworkInterface ni = service.createNetworkInterface(region, subnetId, description,
privateIpAddress, privateIpAddresses, ipv6Addresses, ipv6AddressCount, securityGroupIds, tagList,
@@ -5860,6 +5868,12 @@ public class Ec2QueryHandler {
.end("item");
}
xml.end("networkInterfaceSet");
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
if (eni.getDeviceIndex() == 0 && !eni.getIpv6Addresses().isEmpty()) {
xml.elem("ipv6Address", eni.getIpv6Addresses().get(0));
break;
}
}
xml.elem("clientToken", inst.getClientToken());
if (inst.getStateReasonCode() != null || inst.getStateReasonMessage() != null) {
xml.start("stateReason")
@@ -4605,6 +4605,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// since the unlocked check above.
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
}
List<String> launchIpv6 = allocateLaunchIpv6(region, finalSubnetId, suppliedEni, admitted);
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
privateIpAddress, admitted);
for (int i = 0; i < admitted; i++) {
@@ -4672,13 +4673,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : randomMac());
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
if (suppliedEni != null) {
eni.setIpv6Addresses(new ArrayList<>(suppliedEni.getIpv6Addresses()));
} else if (!launchIpv6.isEmpty()) {
eni.setIpv6Addresses(new ArrayList<>(List.of(launchIpv6.get(i))));
}
carrySubnetIpv6Blocks(region, finalSubnetId, eni);
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
@@ -15839,6 +15843,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// every interface instead and the filter would read as doing nothing.
case "interface-type" -> matchesValue(values, ni.getInterfaceType());
case "requester-managed" -> matchesValue(values, String.valueOf(ni.isRequesterManaged()));
case "ipv6-addresses.ipv6-address" -> ni.getIpv6Addresses().stream()
.anyMatch(address -> matchesValue(values, address));
case "attachment.instance-id" -> ni.getAttachment() != null
&& matchesValue(values, ni.getAttachment().getInstanceId());
case "association.ip-owner-id" -> ni.getPrivateIpAddresses().stream()
@@ -17516,6 +17522,31 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
/** Plans all implicit interfaces' IPv6 addresses before the launch claims IPv4 leases or stores resources. */
private List<String> allocateLaunchIpv6(String region, String subnetId, NetworkInterface suppliedEni, int count) {
Subnet subnet = subnetId == null ? null : subnets.get(key(region, subnetId)).orElse(null);
if (suppliedEni != null || subnet == null || !subnet.isAssignIpv6AddressOnCreation()
|| associatedIpv6Blocks(subnet).isEmpty()) {
return List.of();
}
return allocateIpv6(region, subnet, count);
}
private void carrySubnetIpv6Blocks(String region, String subnetId, InstanceNetworkInterface eni) {
Subnet subnet = subnetId == null ? null : subnets.get(key(region, subnetId)).orElse(null);
if (subnet == null) {
return;
}
eni.setSubnetIpv6CidrBlocks(new ArrayList<>(associatedIpv6Blocks(subnet)));
Vpc vpc = vpcs.get(key(region, subnet.getVpcId())).orElse(null);
if (vpc != null) {
eni.setVpcIpv6CidrBlocks(new ArrayList<>(vpc.getIpv6CidrBlockAssociationSet().stream()
.filter(assoc -> "associated".equalsIgnoreCase(assoc.getIpv6CidrBlockState()))
.map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock)
.toList()));
}
}
private static List<String> associatedIpv6Blocks(Subnet subnet) {
if (subnet.getIpv6CidrBlockAssociationSet() == null) {
return List.of();
@@ -17777,6 +17808,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
attached.setPrivateDnsName(ni.getPrivateDnsName());
attached.setGroups(new ArrayList<>(ni.getGroups()));
attached.setIpv6Addresses(new ArrayList<>(ni.getIpv6Addresses()));
carrySubnetIpv6Blocks(region, ni.getSubnetId(), attached);
attached.setAttachmentId(attachment.getAttachmentId());
attached.setDeviceIndex(deviceIndex);
attached.setAttachTime(attachment.getAttachTime());
@@ -23,6 +23,8 @@ public class InstanceNetworkInterface {
private List<GroupIdentifier> groups = new ArrayList<>();
private List<String> ipv6Addresses = new ArrayList<>();
private List<String> ipv4Prefixes = new ArrayList<>();
private List<String> subnetIpv6CidrBlocks = new ArrayList<>();
private List<String> vpcIpv6CidrBlocks = new ArrayList<>();
private String attachmentId;
private int deviceIndex;
private String attachTime;
@@ -76,11 +78,23 @@ public class InstanceNetworkInterface {
public void setDeleteOnTermination(boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; }
public List<String> getIpv6Addresses() { return ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) { this.ipv6Addresses = ipv6Addresses; }
public void setIpv6Addresses(List<String> ipv6Addresses) {
this.ipv6Addresses = ipv6Addresses != null ? ipv6Addresses : new ArrayList<>();
}
public List<String> getIpv4Prefixes() { return ipv4Prefixes; }
public void setIpv4Prefixes(List<String> ipv4Prefixes) { this.ipv4Prefixes = ipv4Prefixes; }
public List<String> getSubnetIpv6CidrBlocks() { return subnetIpv6CidrBlocks; }
public void setSubnetIpv6CidrBlocks(List<String> subnetIpv6CidrBlocks) {
this.subnetIpv6CidrBlocks = subnetIpv6CidrBlocks != null ? subnetIpv6CidrBlocks : new ArrayList<>();
}
public List<String> getVpcIpv6CidrBlocks() { return vpcIpv6CidrBlocks; }
public void setVpcIpv6CidrBlocks(List<String> vpcIpv6CidrBlocks) {
this.vpcIpv6CidrBlocks = vpcIpv6CidrBlocks != null ? vpcIpv6CidrBlocks : new ArrayList<>();
}
/** A copy with lists of its own, so a change to the copy does not reach this interface. */
public InstanceNetworkInterface copy() {
InstanceNetworkInterface copy = new InstanceNetworkInterface();
@@ -97,6 +111,8 @@ public class InstanceNetworkInterface {
copy.groups = new ArrayList<>(groups);
copy.ipv6Addresses = new ArrayList<>(ipv6Addresses);
copy.ipv4Prefixes = new ArrayList<>(ipv4Prefixes);
copy.subnetIpv6CidrBlocks = new ArrayList<>(subnetIpv6CidrBlocks);
copy.vpcIpv6CidrBlocks = new ArrayList<>(vpcIpv6CidrBlocks);
copy.attachmentId = attachmentId;
copy.deviceIndex = deviceIndex;
copy.attachTime = attachTime;