feat(ec2): support transit gateway VPC attachments (#2347)

* feat(ec2): support transit gateway VPC attachments

CreateTransitGatewayVpcAttachment, DescribeTransitGatewayVpcAttachments,
DescribeTransitGatewayAttachments, ModifyTransitGatewayVpcAttachment and
DeleteTransitGatewayVpcAttachment. Part two of #2308, on top of the
gateway itself.

The two describes are separate shapes rather than one being a superset:
the VPC-specific form carries the subnets and options, while the
resource-agnostic form drops both, types the VPC as a resource, and is
the only place the route table association appears.

Behaviour taken from a live account rather than the reference. The
attachment's option defaults are its own: dnsSupport and
securityGroupReferencingSupport enabled, ipv6Support and
applianceModeSupport disabled. The second of those is enabled here while
the gateway that owns the attachment defaults it to disabled, which is
not something the documentation calls out.

An attachment associates with the gateway's default route table only when
the gateway asks for it, and an association already made survives the
gateway later disabling that default: the association belongs to the
attachment from creation, and only later attachments are affected.

Rejections, all as observed: a VPC attached twice to one gateway is
DuplicateTransitGatewayAttachment, two subnets in one zone are
DuplicateSubnetsInSameZone, a subnet from another VPC is reported missing
rather than mismatched, removing a subnet that is not attached is
InvalidSubnetID.NotFound with its own wording, and removing the last one
is InsufficientSubnetsException. A malformed attachment id is rejected
before the lookup, with the terse message the real API uses.

Two changes reach outside the new surface, both deliberate:

DeleteTransitGateway now refuses while attachments exist, reporting
IncorrectState and naming them. Part one could not have hit this, since
nothing could attach then.

parseTagsForResource reads TagSpecifications as well as TagSpecification.
CreateTransitGatewayVpcAttachment declares no locationName on that member
and so serializes the plural, unlike its neighbours; every tag sent by
the AWS CLI was being dropped. The change only adds a spelling, so
actions using the singular are untouched.

State is reported settled rather than transitional, as for the gateway.
Ipv6Support is accepted without checking that the subnets carry IPv6
CIDRs, which real AWS rejects; Floci does not model subnet IPv6
allocation, and inventing that state to enforce it seemed worse than
documenting the gap.

* fix(ec2): make attachment uniqueness atomic and guard attached resources

Two defects in the VPC attachment work, both found in review.

The one-attachment-per-VPC rule scanned for an existing attachment and
then stored the new one without holding a lock between the two, so
concurrent creates for the same VPC could all find nothing and all
persist. Reproduced by disabling the fix: eight threads, eight
attachments, where the API promises one. The check and the write now
share the gateway's lock, and the test asserts one winner, the right
error for every loser, and one stored attachment, over forty trials.

Deleting a VPC or a subnet that an attachment uses left the attachment
naming resources that no longer existed, which surfaced later as a modify
failing on a subnet the caller never touched. Checked on a live account:
both refuse, with the same code and shape of message.

  DependencyViolation: The subnet 'subnet-…' has dependencies and cannot
  be deleted.
  DependencyViolation: The vpc 'vpc-…' has dependencies and cannot be
  deleted.

Both deletes now refuse the same way. A subnet of the attached VPC that
the attachment does not use still deletes, so the guard is no wider than
the dependency it protects.

* test(ec2): lighten the attachment concurrency harness

Forty trials of eight threads was heavier than the race needs — without
the lock it shows on the first trial — and the extra load disturbed two
thread-timing-sensitive tests elsewhere in the suite,
PostgresProtocolHandlerTest and ElbV2HealthCheckerTest, neither of which
this branch touches. Ten trials of six still reproduces it and leaves
those alone.

* fix(ec2): guard everything an attachment depends on under one lock

The previous fix locked the uniqueness check alone, which was too narrow
twice over. The gateway was resolved before the locked section, so a
concurrent DeleteTransitGateway could see no attachments, delete the
gateway, and let the create persist against the object it had already
read. The VPC and subnet checks were outside any shared lock at all, and
lockFor is striped, so a gateway's monitor never guarded a VPC or subnet
delete regardless.

Everything an attachment depends on now resolves and writes under one
region-scoped monitor: the gateway, the VPC, the subnets, and the
uniqueness rule. Deleting a gateway, a VPC or a subnet takes the same
monitor across its dependency check and its delete. Where a gateway lock
is also taken it is acquired inside this one, so the two cannot
interleave in opposite orders.

The test races a create against each delete and asserts the invariant
rather than a winner: whoever wins, the store must never hold an
attachment naming a gateway, VPC or subnet that is gone. It reproduces
both holes — with the create-side lock removed, "attachment outlived its
gateway" fails on the first trial.

* fix(ec2): stop a tag write restoring a deleted transit gateway resource

Tagging is a read-modify-write, so a tag call overlapping a delete could
read the record, lose the race, and put it back afterwards. A resurrected
attachment goes on blocking the VPC and subnets it names; a resurrected
gateway goes on refusing its own deletion. The gateway and route table
branches were as exposed as the attachment one, so all three moved
together rather than only the case reported.

Ordering matters as much as the lock here. The deletes take the topology
lock and then a striped resource lock, so the tag paths have to take them
the same way round; taking the topology lock further down the stack, with
the resource lock already held, deadlocks against a concurrent delete.
That is what the first attempt did, and the race test caught it as a pool
that never drained. createTags and deleteTags now take the topology lock
outermost for tgw- resources and updateResourceTags relies on its callers
for it.

The test races tagging against deletion for an attachment and for a
gateway, asserting neither comes back.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-18 07:05:24 -04:00
1 parent 96288c104a
commit 74e43a4632
8 files changed
+1377 -35

No files matched your search

@@ -89,6 +89,16 @@ public class Ec2QueryHandler {
case "DescribeTransitGateways" -> handleDescribeTransitGateways(params, region);
case "ModifyTransitGateway" -> handleModifyTransitGateway(params, region);
case "DeleteTransitGateway" -> handleDeleteTransitGateway(params, region);
case "CreateTransitGatewayVpcAttachment" ->
handleCreateTransitGatewayVpcAttachment(params, region);
case "DescribeTransitGatewayVpcAttachments" ->
handleDescribeTransitGatewayVpcAttachments(params, region);
case "DescribeTransitGatewayAttachments" ->
handleDescribeTransitGatewayAttachments(params, region);
case "ModifyTransitGatewayVpcAttachment" ->
handleModifyTransitGatewayVpcAttachment(params, region);
case "DeleteTransitGatewayVpcAttachment" ->
handleDeleteTransitGatewayVpcAttachment(params, region);
case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region);
case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region);
case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region);
@@ -404,17 +414,25 @@ public class Ec2QueryHandler {
return perms;
}
/**
* Reads a request's tag specifications. Most EC2 actions carry them under the wire name
* {@code TagSpecification}, but a handful — {@code CreateTransitGatewayVpcAttachment} among
* them — declare no {@code locationName} and so serialize as {@code TagSpecifications}. Both
* spellings are read, because an action that used the plural silently lost every tag.
*/
private List<Tag> parseTagsForResource(MultivaluedMap<String, String> p, String resourceType) {
List<Tag> tags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if (resourceType.equals(resType)) {
for (int j = 1; ; j++) {
String key = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (key == null) break;
String value = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
tags.add(new Tag(key, value));
for (String prefix : new String[] {"TagSpecification", "TagSpecifications"}) {
for (int i = 1; ; i++) {
String resType = p.getFirst(prefix + "." + i + ".ResourceType");
if (resType == null) break;
if (resourceType.equals(resType)) {
for (int j = 1; ; j++) {
String key = p.getFirst(prefix + "." + i + ".Tag." + j + ".Key");
if (key == null) break;
String value = p.getFirst(prefix + "." + i + ".Tag." + j + ".Value");
tags.add(new Tag(key, value));
}
}
}
}
@@ -1258,6 +1276,139 @@ public class Ec2QueryHandler {
return options;
}
private Response handleCreateTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {
TransitGatewayVpcAttachment attachment = service.createTransitGatewayVpcAttachment(
region,
p.getFirst("TransitGatewayId"),
p.getFirst("VpcId"),
getList(p, "SubnetIds"),
parseVpcAttachmentOptions(p),
parseTagsForResource(p, "transit-gateway-attachment"));
XmlBuilder xml = new XmlBuilder()
.start("CreateTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, true, true))
.end("transitGatewayVpcAttachment")
.end("CreateTransitGatewayVpcAttachmentResponse");
return xmlResponse(xml.build());
}
private Response handleDescribeTransitGatewayVpcAttachments(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(
region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayVpcAttachmentsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGatewayVpcAttachments");
for (TransitGatewayVpcAttachment attachment : attachments) {
xml.start("item").raw(vpcAttachmentXml(attachment, true, true)).end("item");
}
xml.end("transitGatewayVpcAttachments").end("DescribeTransitGatewayVpcAttachmentsResponse");
return xmlResponse(xml.build());
}
/**
* The resource-agnostic view of the same attachments. It is a different shape rather than a
* superset: the subnets and options are gone, the VPC appears as a typed resource, and the
* route table association shows up here and nowhere else.
*/
private Response handleDescribeTransitGatewayAttachments(MultivaluedMap<String, String> p, String region) {
List<TransitGatewayVpcAttachment> attachments = service.describeTransitGatewayVpcAttachments(
region, getList(p, "TransitGatewayAttachmentIds"), getFilters(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeTransitGatewayAttachmentsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("transitGatewayAttachments");
for (TransitGatewayVpcAttachment attachment : attachments) {
XmlBuilder item = new XmlBuilder()
.elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId())
.elem("transitGatewayId", attachment.getTransitGatewayId())
.elem("transitGatewayOwnerId", attachment.getTransitGatewayOwnerId())
.elem("resourceOwnerId", attachment.getVpcOwnerId())
.elem("resourceType", "vpc")
.elem("resourceId", attachment.getVpcId())
.elem("state", attachment.getState());
if (attachment.getAssociationRouteTableId() != null) {
item.start("association")
.elem("transitGatewayRouteTableId", attachment.getAssociationRouteTableId())
.elem("state", attachment.getAssociationState())
.end("association");
}
item.elem("creationTime", attachment.getCreationTime())
.raw(tagSetXml(attachment.getTags()));
xml.start("item").raw(item.build()).end("item");
}
xml.end("transitGatewayAttachments").end("DescribeTransitGatewayAttachmentsResponse");
return xmlResponse(xml.build());
}
private Response handleModifyTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {
TransitGatewayVpcAttachment attachment = service.modifyTransitGatewayVpcAttachment(
region,
p.getFirst("TransitGatewayAttachmentId"),
getList(p, "AddSubnetIds"),
getList(p, "RemoveSubnetIds"),
parseVpcAttachmentOptions(p));
XmlBuilder xml = new XmlBuilder()
.start("ModifyTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
// Verified live: modify echoes the attachment without its tagSet.
.start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, true, false))
.end("transitGatewayVpcAttachment")
.end("ModifyTransitGatewayVpcAttachmentResponse");
return xmlResponse(xml.build());
}
private Response handleDeleteTransitGatewayVpcAttachment(MultivaluedMap<String, String> p, String region) {
TransitGatewayVpcAttachment attachment = service.deleteTransitGatewayVpcAttachment(
region, p.getFirst("TransitGatewayAttachmentId"));
XmlBuilder xml = new XmlBuilder()
.start("DeleteTransitGatewayVpcAttachmentResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
// Verified live: delete drops the subnets and the tagSet from the echo.
.start("transitGatewayVpcAttachment").raw(vpcAttachmentXml(attachment, false, false))
.end("transitGatewayVpcAttachment")
.end("DeleteTransitGatewayVpcAttachmentResponse");
return xmlResponse(xml.build());
}
private TransitGatewayVpcAttachmentOptions parseVpcAttachmentOptions(MultivaluedMap<String, String> p) {
TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();
options.setDnsSupport(p.getFirst("Options.DnsSupport"));
options.setSecurityGroupReferencingSupport(p.getFirst("Options.SecurityGroupReferencingSupport"));
options.setIpv6Support(p.getFirst("Options.Ipv6Support"));
options.setApplianceModeSupport(p.getFirst("Options.ApplianceModeSupport"));
return options;
}
private String vpcAttachmentXml(TransitGatewayVpcAttachment attachment, boolean includeSubnets,
boolean includeTags) {
XmlBuilder xml = new XmlBuilder()
.elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId())
.elem("transitGatewayId", attachment.getTransitGatewayId())
.elem("vpcId", attachment.getVpcId())
.elem("vpcOwnerId", attachment.getVpcOwnerId())
.elem("state", attachment.getState());
if (includeSubnets) {
xml.start("subnetIds");
for (String subnetId : attachment.getSubnetIds()) {
xml.elem("item", subnetId);
}
xml.end("subnetIds");
}
xml.elem("creationTime", attachment.getCreationTime())
.start("options")
.elem("dnsSupport", attachment.getOptions().getDnsSupport())
.elem("securityGroupReferencingSupport", attachment.getOptions().getSecurityGroupReferencingSupport())
.elem("ipv6Support", attachment.getOptions().getIpv6Support())
.elem("applianceModeSupport", attachment.getOptions().getApplianceModeSupport())
.end("options");
if (includeTags) {
xml.raw(tagSetXml(attachment.getTags()));
}
return xml.build();
}
private String transitGatewayXml(TransitGateway gateway) {
return transitGatewayXml(gateway, true);
}
@@ -76,6 +76,8 @@ import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.TransitGateway;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment;
import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions;
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
import io.github.hectorvent.floci.services.ec2.model.Volume;
import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;
@@ -102,6 +104,8 @@ public class Ec2Service implements ContainerTeardown {
// The ASN AWS assigns when CreateTransitGateway omits Options.AmazonSideAsn.
private static final long DEFAULT_AMAZON_SIDE_ASN = 64512L;
private static final Pattern TRANSIT_GATEWAY_ID_PATTERN = Pattern.compile("^tgw-[0-9a-f]{8}([0-9a-f]{9})?$");
private static final Pattern TRANSIT_GATEWAY_ATTACHMENT_ID_PATTERN =
Pattern.compile("^tgw-attach-[0-9a-f]{8}([0-9a-f]{9})?$");
private final String accountId;
private final EmulatorConfig config;
@@ -134,6 +138,7 @@ public class Ec2Service implements ContainerTeardown {
private final StorageBackend<String, ManagedPrefixList> managedPrefixLists;
private final StorageBackend<String, TransitGateway> transitGateways;
private final StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables;
private final StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments;
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
@@ -167,7 +172,9 @@ public class Ec2Service implements ContainerTeardown {
storageFactory.create("ec2", "ec2-tags.json", new TypeReference<Map<String, List<Tag>>>() {}),
storageFactory.create("ec2", "ec2-transit-gateways.json", new TypeReference<Map<String, TransitGateway>>() {}),
storageFactory.create("ec2", "ec2-transit-gateway-route-tables.json",
new TypeReference<Map<String, TransitGatewayRouteTable>>() {}));
new TypeReference<Map<String, TransitGatewayRouteTable>>() {}),
storageFactory.create("ec2", "ec2-transit-gateway-vpc-attachments.json",
new TypeReference<Map<String, TransitGatewayVpcAttachment>>() {}));
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -198,7 +205,7 @@ public class Ec2Service implements ContainerTeardown {
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
new InMemoryStorage<>(), new InMemoryStorage<>());
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
}
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
@@ -227,7 +234,8 @@ public class Ec2Service implements ContainerTeardown {
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables) {
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments) {
this.accountId = config.defaultAccountId();
this.config = config;
this.containerManager = containerManager;
@@ -256,6 +264,7 @@ public class Ec2Service implements ContainerTeardown {
this.tags = tags;
this.transitGateways = transitGateways;
this.transitGatewayRouteTables = transitGatewayRouteTables;
this.transitGatewayVpcAttachments = transitGatewayVpcAttachments;
}
@PostConstruct
@@ -1211,8 +1220,21 @@ public class Ec2Service implements ContainerTeardown {
* the returned object carries the settled state for the same reason creation does.
*/
public TransitGateway deleteTransitGateway(String region, String transitGatewayId) {
// Outermost first: the attachment check below and a concurrent attachment create have to
// agree on who goes first.
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, transitGatewayId))) {
TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);
// AWS refuses while anything is still attached, naming the attachments in the message.
List<String> attached = transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(attachment -> region.equals(attachment.getRegion()))
.filter(attachment -> transitGatewayId.equals(attachment.getTransitGatewayId()))
.map(TransitGatewayVpcAttachment::getTransitGatewayAttachmentId)
.toList();
if (!attached.isEmpty()) {
throw new AwsException("IncorrectState", transitGatewayId
+ " has non-deleted VPC Attachments: " + String.join(", ", attached) + ".", 400);
}
transitGatewayRouteTables.scan(k -> true).stream()
.filter(routeTable -> region.equals(routeTable.getRegion()))
.filter(routeTable -> transitGatewayId.equals(routeTable.getTransitGatewayId()))
@@ -1224,6 +1246,7 @@ public class Ec2Service implements ContainerTeardown {
gateway.setState("deleted");
return gateway;
}
}
}
private TransitGateway getRequiredTransitGateway(String region, String transitGatewayId) {
@@ -1244,6 +1267,222 @@ public class Ec2Service implements ContainerTeardown {
}
}
// ─── Transit Gateway VPC Attachments ───────────────────────────────────────
/**
* Attaches a VPC to a transit gateway. The option defaults are the attachment's own and not
* the gateway's: verified against a live account, {@code securityGroupReferencingSupport} is
* enabled here where it is disabled on the gateway that owns the attachment.
*
* <p>An attachment is associated with the gateway's default route table only when the gateway
* asks for that, so a gateway created with {@code DefaultRouteTableAssociation} disabled
* produces an attachment carrying no association at all.
*/
public TransitGatewayVpcAttachment createTransitGatewayVpcAttachment(
String region, String transitGatewayId, String vpcId, List<String> subnetIds,
TransitGatewayVpcAttachmentOptions requested, List<Tag> attachmentTags) {
// Everything an attachment depends on is resolved and written under one lock: the gateway
// it hangs off, the VPC and subnets it names, and the uniqueness rule. Resolving any of
// them outside it lets a concurrent delete land in between, leaving an attachment that
// names a gateway, VPC or subnet which no longer exists.
synchronized (attachmentTopologyLock(region)) {
TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId);
getRequiredVpc(region, vpcId);
// SubnetIds is required on the request, and modify refuses to leave an attachment
// without any, so creation must not be a way to produce what modify forbids.
if (subnetIds == null || subnetIds.isEmpty()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter SubnetIds.", 400);
}
requireAttachableSubnets(region, vpcId, subnetIds, List.of());
boolean alreadyAttached = transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(existing -> region.equals(existing.getRegion()))
.filter(existing -> transitGatewayId.equals(existing.getTransitGatewayId()))
.anyMatch(existing -> vpcId.equals(existing.getVpcId()));
if (alreadyAttached) {
throw new AwsException("DuplicateTransitGatewayAttachment",
transitGatewayId + " has non-deleted Transit Gateway Attachments with same VPC ID.", 400);
}
return storeNewAttachment(region, gateway, vpcId, subnetIds, requested, attachmentTags);
}
}
private TransitGatewayVpcAttachment storeNewAttachment(
String region, TransitGateway gateway, String vpcId, List<String> subnetIds,
TransitGatewayVpcAttachmentOptions requested, List<Tag> attachmentTags) {
TransitGatewayVpcAttachment attachment = new TransitGatewayVpcAttachment();
String attachmentId = "tgw-attach-" + randomHex(17);
attachment.setTransitGatewayAttachmentId(attachmentId);
attachment.setTransitGatewayId(gateway.getTransitGatewayId());
attachment.setVpcId(vpcId);
attachment.setVpcOwnerId(accountId);
attachment.setTransitGatewayOwnerId(gateway.getOwnerId());
// AWS reports pending and settles on available; nothing is slow locally, the same
// compression createTransitGateway applies.
attachment.setState("available");
attachment.setSubnetIds(new ArrayList<>(subnetIds));
attachment.setCreationTime(ISO_FMT.format(Instant.now()));
attachment.setRegion(region);
attachment.setOptions(resolveAttachmentOptions(requested));
// Both halves together: an association state without a table would be a shape AWS never
// serves, and the gateway's own validation keeps the pair in step.
if ("enable".equals(gateway.getOptions().getDefaultRouteTableAssociation())
&& gateway.getOptions().getAssociationDefaultRouteTableId() != null) {
attachment.setAssociationRouteTableId(gateway.getOptions().getAssociationDefaultRouteTableId());
attachment.setAssociationState("associated");
}
if (attachmentTags != null && !attachmentTags.isEmpty()) {
attachment.setTags(new ArrayList<>(attachmentTags));
tags.put(attachmentId, new ArrayList<>(attachmentTags));
}
transitGatewayVpcAttachments.put(key(region, attachmentId), attachment);
return attachment;
}
/**
* One region-wide monitor for every operation that creates an attachment, removes one, or
* removes something an attachment depends on. Held outermost wherever a gateway lock is also
* taken, so the two never interleave in opposite orders. Per-resource striped locks cannot
* serve here: the dependency spans a gateway, a VPC and its subnets, which stripe separately.
*/
private Object attachmentTopologyLock(String region) {
return lockFor(key(region, "transit-gateway-attachments"));
}
private TransitGatewayVpcAttachmentOptions resolveAttachmentOptions(
TransitGatewayVpcAttachmentOptions requested) {
TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();
options.setDnsSupport("enable");
options.setSecurityGroupReferencingSupport("enable");
options.setIpv6Support("disable");
options.setApplianceModeSupport("disable");
applyAttachmentOptionChanges(options, requested);
return options;
}
/**
* Every subnet has to exist in the VPC being attached, and no two may share an availability
* zone. A subnet belonging to another VPC is reported missing rather than mismatched, which is
* what the live API does.
*/
private void requireAttachableSubnets(String region, String vpcId, List<String> subnetIds,
List<String> alreadyAttached) {
List<String> zones = new ArrayList<>();
for (String subnetId : alreadyAttached) {
subnets.get(key(region, subnetId)).ifPresent(subnet -> zones.add(subnet.getAvailabilityZone()));
}
for (String subnetId : subnetIds) {
Subnet subnet = subnets.get(key(region, subnetId)).orElse(null);
if (subnet == null || !vpcId.equals(subnet.getVpcId())) {
throw new AwsException("InvalidSubnetID.NotFound",
"Subnet " + subnetId + " was deleted or does not exist.", 400);
}
if (zones.contains(subnet.getAvailabilityZone())) {
throw new AwsException("DuplicateSubnetsInSameZone", "Duplicate Subnets for same AZ", 400);
}
zones.add(subnet.getAvailabilityZone());
}
}
public List<TransitGatewayVpcAttachment> describeTransitGatewayVpcAttachments(
String region, List<String> attachmentIds, Map<String, List<String>> filters) {
attachmentIds.forEach(Ec2Service::requireWellFormedAttachmentId);
List<TransitGatewayVpcAttachment> all = transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(attachment -> region.equals(attachment.getRegion()))
.collect(Collectors.toList());
for (String attachmentId : attachmentIds) {
if (all.stream().noneMatch(a -> a.getTransitGatewayAttachmentId().equals(attachmentId))) {
throw new AwsException("InvalidTransitGatewayAttachmentID.NotFound",
"Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400);
}
}
return all.stream()
.filter(a -> attachmentIds.isEmpty() || attachmentIds.contains(a.getTransitGatewayAttachmentId()))
.filter(a -> matchesFilters(a, filters, region))
.collect(Collectors.toList());
}
public TransitGatewayVpcAttachment modifyTransitGatewayVpcAttachment(
String region, String attachmentId, List<String> addSubnetIds, List<String> removeSubnetIds,
TransitGatewayVpcAttachmentOptions changes) {
synchronized (attachmentTopologyLock(region)) {
TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId);
List<String> subnetIds = new ArrayList<>(attachment.getSubnetIds());
if (removeSubnetIds != null) {
for (String subnetId : removeSubnetIds) {
if (!subnetIds.remove(subnetId)) {
throw new AwsException("InvalidSubnetID.NotFound",
subnetId + " is not attached but supplied in RemoveSubnets", 400);
}
}
}
if (addSubnetIds != null && !addSubnetIds.isEmpty()) {
requireAttachableSubnets(region, attachment.getVpcId(), addSubnetIds, subnetIds);
subnetIds.addAll(addSubnetIds);
}
// Removals are applied first, so an attachment cannot be left with nothing to attach
// through even when the same request adds subnets back.
if (subnetIds.isEmpty()) {
throw new AwsException("InsufficientSubnetsException", "Insufficient Subnets", 400);
}
attachment.setSubnetIds(subnetIds);
applyAttachmentOptionChanges(attachment.getOptions(), changes);
transitGatewayVpcAttachments.put(key(region, attachmentId), attachment);
return attachment;
}
}
private void applyAttachmentOptionChanges(TransitGatewayVpcAttachmentOptions options,
TransitGatewayVpcAttachmentOptions changes) {
if (changes == null) {
return;
}
if (changes.getDnsSupport() != null) {
options.setDnsSupport(changes.getDnsSupport());
}
if (changes.getSecurityGroupReferencingSupport() != null) {
options.setSecurityGroupReferencingSupport(changes.getSecurityGroupReferencingSupport());
}
if (changes.getIpv6Support() != null) {
options.setIpv6Support(changes.getIpv6Support());
}
if (changes.getApplianceModeSupport() != null) {
options.setApplianceModeSupport(changes.getApplianceModeSupport());
}
}
public TransitGatewayVpcAttachment deleteTransitGatewayVpcAttachment(String region, String attachmentId) {
synchronized (attachmentTopologyLock(region)) {
TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId);
transitGatewayVpcAttachments.delete(key(region, attachmentId));
tags.delete(attachmentId);
attachment.setState("deleted");
return attachment;
}
}
/**
* Verified live: an id of the wrong shape is rejected before any lookup, and the message does
* not echo it back, unlike the transit gateway's equivalent.
*/
private static void requireWellFormedAttachmentId(String attachmentId) {
if (!TRANSIT_GATEWAY_ATTACHMENT_ID_PATTERN.matcher(attachmentId).matches()) {
throw new AwsException("InvalidTransitGatewayAttachmentID.Malformed",
"Invalid Transit Gateway Attachment id.", 400);
}
}
private TransitGatewayVpcAttachment getRequiredVpcAttachment(String region, String attachmentId) {
if (attachmentId == null || attachmentId.isBlank()) {
throw new AwsException("MissingParameter",
"The request must contain the parameter TransitGatewayAttachmentId.", 400);
}
requireWellFormedAttachmentId(attachmentId);
return transitGatewayVpcAttachments.get(key(region, attachmentId))
.orElseThrow(() -> new AwsException("InvalidTransitGatewayAttachmentID.NotFound",
"Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400));
}
// ─── Instances ─────────────────────────────────────────────────────────────
public Reservation runInstances(String region, String imageId, String instanceType,
@@ -1788,8 +2027,12 @@ public class Ec2Service implements ContainerTeardown {
public void deleteVpc(String region, String vpcId) {
ensureDefaultResources(region);
getRequiredVpc(region, vpcId);
vpcs.delete(key(region, vpcId));
synchronized (attachmentTopologyLock(region)) {
requireNoTransitGatewayAttachment(region,
attachment -> vpcId.equals(attachment.getVpcId()),
"The vpc '" + vpcId + "' has dependencies and cannot be deleted.");
vpcs.delete(key(region, vpcId));
}
}
public void modifyVpcAttribute(String region, String vpcId, String attribute, String value) {
@@ -2014,7 +2257,27 @@ public class Ec2Service implements ContainerTeardown {
if (subnets.get(key(region, subnetId)).isEmpty()) {
throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400);
}
subnets.delete(key(region, subnetId));
synchronized (attachmentTopologyLock(region)) {
requireNoTransitGatewayAttachment(region,
attachment -> attachment.getSubnetIds().contains(subnetId),
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
subnets.delete(key(region, subnetId));
}
}
/**
* A VPC or subnet carrying a transit gateway attachment cannot be deleted out from under it.
* Verified on a live account: both report {@code DependencyViolation} with the same wording,
* rather than leaving the attachment pointing at something that no longer exists.
*/
private void requireNoTransitGatewayAttachment(
String region, java.util.function.Predicate<TransitGatewayVpcAttachment> dependsOnIt, String message) {
boolean attached = transitGatewayVpcAttachments.scan(k -> true).stream()
.filter(attachment -> region.equals(attachment.getRegion()))
.anyMatch(dependsOnIt);
if (attached) {
throw new AwsException("DependencyViolation", message, 400);
}
}
public void modifySubnetAttribute(String region, String subnetId, String attribute, String value) {
@@ -3152,22 +3415,41 @@ public class Ec2Service implements ContainerTeardown {
public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
synchronized (lockFor(key(region, resourceId))) {
List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElse(List.of()));
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey()));
existing.add(tag);
withTopologyLockIfNeeded(region, resourceId, () -> {
synchronized (lockFor(key(region, resourceId))) {
List<Tag> existing = new ArrayList<>(tags.get(resourceId).orElse(List.of()));
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey()));
existing.add(tag);
}
tags.put(resourceId, existing);
// Update resource objects
updateResourceTags(region, resourceId, existing);
}
tags.put(resourceId, existing);
// Update resource objects
updateResourceTags(region, resourceId, existing);
}
});
}
}
/**
* Runs a tag change with the topology lock already held when the resource is one a transit
* gateway delete can remove. Order matters as much as the lock does: the deletes take the
* topology lock and then a striped resource lock, so tagging has to take them the same way
* round or the two deadlock.
*/
private void withTopologyLockIfNeeded(String region, String resourceId, Runnable change) {
if (resourceId != null && resourceId.startsWith("tgw-")) {
synchronized (attachmentTopologyLock(region)) {
change.run();
}
return;
}
change.run();
}
public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
synchronized (lockFor(key(region, resourceId))) {
List<Tag> stored = tags.get(resourceId).orElse(null);
if (stored != null) {
@@ -3180,6 +3462,7 @@ public class Ec2Service implements ContainerTeardown {
updateResourceTags(region, resourceId, existing);
}
}
});
}
}
@@ -3217,16 +3500,26 @@ public class Ec2Service implements ContainerTeardown {
managedPrefixLists.put(storeKey, prefixList);
return;
}
TransitGateway gateway = transitGateways.get(storeKey).orElse(null);
if (gateway != null) {
gateway.setTags(new ArrayList<>(tagList));
transitGateways.put(storeKey, gateway);
return;
}
TransitGatewayRouteTable routeTable = transitGatewayRouteTables.get(storeKey).orElse(null);
if (routeTable != null) {
routeTable.setTags(new ArrayList<>(tagList));
transitGatewayRouteTables.put(storeKey, routeTable);
// Reached with the topology lock already held for tgw- resources, so the read-modify-write
// below cannot put back something a concurrent delete has just removed.
{
TransitGateway gateway = transitGateways.get(storeKey).orElse(null);
if (gateway != null) {
gateway.setTags(new ArrayList<>(tagList));
transitGateways.put(storeKey, gateway);
return;
}
TransitGatewayRouteTable routeTable = transitGatewayRouteTables.get(storeKey).orElse(null);
if (routeTable != null) {
routeTable.setTags(new ArrayList<>(tagList));
transitGatewayRouteTables.put(storeKey, routeTable);
return;
}
TransitGatewayVpcAttachment attachment = transitGatewayVpcAttachments.get(storeKey).orElse(null);
if (attachment != null) {
attachment.setTags(new ArrayList<>(tagList));
transitGatewayVpcAttachments.put(storeKey, attachment);
}
}
}
@@ -3305,7 +3598,10 @@ public class Ec2Service implements ContainerTeardown {
if (resourceId.startsWith("pl-")) {
return "prefix-list";
}
// Checked before the gateway prefix, which it starts with.
// Both checked before the gateway prefix, which they start with.
if (resourceId.startsWith("tgw-attach-")) {
return "transit-gateway-attachment";
}
if (resourceId.startsWith("tgw-rtb-")) {
return "transit-gateway-route-table";
}
@@ -3821,6 +4117,18 @@ public class Ec2Service implements ContainerTeardown {
default -> true;
};
}
if (resource instanceof TransitGatewayVpcAttachment attachment) {
return switch (filterName) {
case "transit-gateway-attachment-id" -> matchesValue(values, attachment.getTransitGatewayAttachmentId());
case "transit-gateway-id" -> matchesValue(values, attachment.getTransitGatewayId());
case "vpc-id" -> matchesValue(values, attachment.getVpcId());
case "vpc-owner-id" -> matchesValue(values, attachment.getVpcOwnerId());
case "state" -> matchesValue(values, attachment.getState());
case "resource-id" -> matchesValue(values, attachment.getVpcId());
case "resource-type" -> matchesValue(values, "vpc");
default -> true;
};
}
if (resource instanceof TransitGateway gateway) {
return switch (filterName) {
case "transit-gateway-id" -> matchesValue(values, gateway.getTransitGatewayId());
@@ -3969,6 +4277,7 @@ public class Ec2Service implements ContainerTeardown {
if (resource instanceof SpotInstanceRequest sir) return sir.getTags();
if (resource instanceof TransitGateway gateway) return gateway.getTags();
if (resource instanceof TransitGatewayRouteTable routeTable) return routeTable.getTags();
if (resource instanceof TransitGatewayVpcAttachment attachment) return attachment.getTags();
return Collections.emptyList();
}
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
/**
* A transit gateway's attachment to a VPC. {@code DescribeTransitGatewayVpcAttachments} serves
* this shape directly; {@code DescribeTransitGatewayAttachments} serves the resource-agnostic view
* of the same record, which is where the route table association appears.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransitGatewayVpcAttachment {
private String transitGatewayAttachmentId;
private String transitGatewayId;
private String vpcId;
private String vpcOwnerId;
/** The gateway's owner, which is a different field from the VPC's even when they agree. */
private String transitGatewayOwnerId;
private String state;
private List<String> subnetIds = new ArrayList<>();
private String creationTime;
private String region;
private TransitGatewayVpcAttachmentOptions options = new TransitGatewayVpcAttachmentOptions();
/** Set when the gateway associates attachments with its default route table. */
private String associationRouteTableId;
private String associationState;
private List<Tag> tags = new ArrayList<>();
public TransitGatewayVpcAttachment() {}
public String getTransitGatewayAttachmentId() { return transitGatewayAttachmentId; }
public void setTransitGatewayAttachmentId(String transitGatewayAttachmentId) {
this.transitGatewayAttachmentId = transitGatewayAttachmentId;
}
public String getTransitGatewayId() { return transitGatewayId; }
public void setTransitGatewayId(String transitGatewayId) { this.transitGatewayId = transitGatewayId; }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getVpcOwnerId() { return vpcOwnerId; }
public void setVpcOwnerId(String vpcOwnerId) { this.vpcOwnerId = vpcOwnerId; }
public String getTransitGatewayOwnerId() { return transitGatewayOwnerId; }
public void setTransitGatewayOwnerId(String transitGatewayOwnerId) {
this.transitGatewayOwnerId = transitGatewayOwnerId;
}
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public List<String> getSubnetIds() { return subnetIds; }
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
public String getCreationTime() { return creationTime; }
public void setCreationTime(String creationTime) { this.creationTime = creationTime; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public TransitGatewayVpcAttachmentOptions getOptions() { return options; }
public void setOptions(TransitGatewayVpcAttachmentOptions options) { this.options = options; }
public String getAssociationRouteTableId() { return associationRouteTableId; }
public void setAssociationRouteTableId(String associationRouteTableId) {
this.associationRouteTableId = associationRouteTableId;
}
public String getAssociationState() { return associationState; }
public void setAssociationState(String associationState) { this.associationState = associationState; }
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class TransitGatewayVpcAttachmentOptions {
private String dnsSupport;
private String securityGroupReferencingSupport;
private String ipv6Support;
private String applianceModeSupport;
public TransitGatewayVpcAttachmentOptions() {}
public String getDnsSupport() { return dnsSupport; }
public void setDnsSupport(String dnsSupport) { this.dnsSupport = dnsSupport; }
public String getSecurityGroupReferencingSupport() { return securityGroupReferencingSupport; }
public void setSecurityGroupReferencingSupport(String securityGroupReferencingSupport) {
this.securityGroupReferencingSupport = securityGroupReferencingSupport;
}
public String getIpv6Support() { return ipv6Support; }
public void setIpv6Support(String ipv6Support) { this.ipv6Support = ipv6Support; }
public String getApplianceModeSupport() { return applianceModeSupport; }
public void setApplianceModeSupport(String applianceModeSupport) {
this.applianceModeSupport = applianceModeSupport;
}
}