fix(ec2): serialize concurrent mutations of shared resources per resource (#1786)

* fix(ec2): serialize concurrent mutations of shared resources per resource

The storage backend's get() returns the live stored object, so mutating
its collections in place raced under parallel clients. Terraform runs
10-wide by default, and concurrent AssociateRouteTable calls dropped
associations; describes could also observe a half-updated list.

Mutators of route tables, network ACLs, security groups, and tags now
take a per-resource lock and swap collections copy-on-write, so a
concurrent describe only ever sees a complete list. The lock is striped
by storage key, so unrelated resources never contend — replacing the
coarse `synchronized` methods on the NACL paths.

Refs #1464

* fix(ec2): make ReplaceNetworkAclAssociation atomic and bound the lock stripes

The unlocked membership scan let concurrent callers with the same
associationId each claim the association: the loser's remove() silently
no-opped, so every caller minted a distinct moved association and added it
to the target ACL, leaving one subnet associated several times.

Claim the association under lock, and hold the source and target locks for
the whole move so a describe never observes the subnet associated with
neither ACL. Losers now fall through to InvalidAssociationID.NotFound.

Replace the per-key lock map, which never evicted, with a fixed stripe
array. Two-lock callers order acquisition by stripe index rather than
storage key, since distinct keys may share a stripe and key order would
not be a total order over the monitors.

Drop the redundant pre-lock getRequiredRouteTable in createRoute; the
call inside the lock throws identically, matching deleteRoute.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-07-09 22:57:32 -05:00
1 parent 5cce73da45
commit 342bb52df4
2 files changed
+443 -76

No files matched your search

@@ -439,47 +439,76 @@ public class Ec2Service {
return true;
}
public synchronized void createNetworkAclEntry(String region, String networkAclId, int ruleNumber, String protocol,
public void createNetworkAclEntry(String region, String networkAclId, int ruleNumber, String protocol,
String ruleAction, boolean egress, String cidrBlock, Integer from, Integer to,
boolean replace) {
NetworkAcl acl = getRequiredNetworkAcl(region, networkAclId);
boolean exists = acl.getEntries().stream()
.anyMatch(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
if (!replace && exists) {
throw new AwsException("NetworkAclEntryAlreadyExists",
"The network acl entry identified by " + ruleNumber + " already exists.", 400);
synchronized (lockFor(key(region, networkAclId))) {
NetworkAcl acl = getRequiredNetworkAcl(region, networkAclId);
boolean exists = acl.getEntries().stream()
.anyMatch(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
if (!replace && exists) {
throw new AwsException("NetworkAclEntryAlreadyExists",
"The network acl entry identified by " + ruleNumber + " already exists.", 400);
}
List<NetworkAclEntry> next = new ArrayList<>(acl.getEntries());
next.removeIf(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
NetworkAclEntry entry = naclEntry(ruleNumber, protocol, ruleAction, egress, cidrBlock);
entry.setPortRangeFrom(from);
entry.setPortRangeTo(to);
next.add(entry);
acl.setEntries(next);
networkAcls.put(key(region, networkAclId), acl);
}
acl.getEntries().removeIf(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
NetworkAclEntry entry = naclEntry(ruleNumber, protocol, ruleAction, egress, cidrBlock);
entry.setPortRangeFrom(from);
entry.setPortRangeTo(to);
acl.getEntries().add(entry);
networkAcls.put(key(region, networkAclId), acl);
}
public synchronized void deleteNetworkAclEntry(String region, String networkAclId, int ruleNumber, boolean egress) {
NetworkAcl acl = getRequiredNetworkAcl(region, networkAclId);
acl.getEntries().removeIf(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
networkAcls.put(key(region, networkAclId), acl);
public void deleteNetworkAclEntry(String region, String networkAclId, int ruleNumber, boolean egress) {
synchronized (lockFor(key(region, networkAclId))) {
NetworkAcl acl = getRequiredNetworkAcl(region, networkAclId);
List<NetworkAclEntry> next = new ArrayList<>(acl.getEntries());
next.removeIf(e -> e.getRuleNumber() == ruleNumber && e.isEgress() == egress);
acl.setEntries(next);
networkAcls.put(key(region, networkAclId), acl);
}
}
public synchronized NetworkAclAssociation replaceNetworkAclAssociation(String region, String associationId, String networkAclId) {
public NetworkAclAssociation replaceNetworkAclAssociation(String region, String associationId, String networkAclId) {
NetworkAcl target = getRequiredNetworkAcl(region, networkAclId);
for (NetworkAcl acl : networkAcls.scan(k -> true)) {
if (!region.equals(acl.getRegion())) {
if (!region.equals(acl.getRegion())
|| acl.getAssociations().stream()
.noneMatch(a -> a.getNetworkAclAssociationId().equals(associationId))) {
continue;
}
for (NetworkAclAssociation existing : acl.getAssociations()) {
if (existing.getNetworkAclAssociationId().equals(associationId)) {
String subnetId = existing.getSubnetId();
acl.getAssociations().remove(existing);
networkAcls.put(key(region, acl.getNetworkAclId()), acl);
String sourceKey = key(region, acl.getNetworkAclId());
String targetKey = key(region, networkAclId);
// The move must be atomic across both ACLs, or a describe could observe the subnet
// associated with neither. Locks are taken in stripe order so two callers moving
// associations in opposite directions cannot deadlock; one stripe re-enters.
synchronized (lowerLockOf(sourceKey, targetKey)) {
synchronized (higherLockOf(sourceKey, targetKey)) {
List<NetworkAclAssociation> remaining = new ArrayList<>(acl.getAssociations());
NetworkAclAssociation claimed = remaining.stream()
.filter(a -> a.getNetworkAclAssociationId().equals(associationId))
.findFirst()
.orElse(null);
// The scan above ran unlocked, so a concurrent replace of the same association
// may already have moved it. That caller minted the new id; this one sees the
// requested id no longer exist.
if (claimed == null) {
break;
}
remaining.remove(claimed);
acl.setAssociations(remaining);
networkAcls.put(sourceKey, acl);
NetworkAclAssociation moved = new NetworkAclAssociation();
moved.setNetworkAclAssociationId("aclassoc-" + randomHex(17));
moved.setNetworkAclId(networkAclId);
moved.setSubnetId(subnetId);
target.getAssociations().add(moved);
networkAcls.put(key(region, networkAclId), target);
moved.setSubnetId(claimed.getSubnetId());
List<NetworkAclAssociation> next = new ArrayList<>(target.getAssociations());
next.add(moved);
target.setAssociations(next);
networkAcls.put(targetKey, target);
return moved;
}
}
@@ -524,6 +553,42 @@ public class Ec2Service {
return region + "::" + id;
}
// Per-resource mutation locks (#1464): storage get() returns the live stored object, so
// unsynchronized list mutations race under parallel clients (Terraform runs 10-wide) and
// drop entries. Mutators take the resource's stripe and swap collections copy-on-write so
// concurrent describes only ever see a complete list. A fixed stripe array keeps this
// bounded — a lock per storage key would never evict — at the cost of unrelated resources
// sharing a monitor on hash collision.
private static final int LOCK_STRIPES = 512;
private final Object[] resourceLocks = newLockStripes();
private static Object[] newLockStripes() {
Object[] stripes = new Object[LOCK_STRIPES];
for (int i = 0; i < stripes.length; i++) {
stripes[i] = new Object();
}
return stripes;
}
private int stripeOf(String storeKey) {
return Math.floorMod(storeKey.hashCode(), LOCK_STRIPES);
}
private Object lockFor(String storeKey) {
return resourceLocks[stripeOf(storeKey)];
}
// Stripe index, not key order, is the total order two-lock callers must agree on: distinct
// keys can share a stripe, so ordering by key could have two callers take the same pair of
// monitors in opposite orders.
private Object lowerLockOf(String keyA, String keyB) {
return resourceLocks[Math.min(stripeOf(keyA), stripeOf(keyB))];
}
private Object higherLockOf(String keyA, String keyB) {
return resourceLocks[Math.max(stripeOf(keyA), stripeOf(keyB))];
}
private String randomHex(int len) {
StringBuilder sb = new StringBuilder(len);
Random rand = new Random();
@@ -1326,28 +1391,34 @@ public class Ec2Service {
public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<SecurityGroupRule> rules = new ArrayList<>();
for (IpPermission perm : permissions) {
sg.getIpPermissions().add(perm);
rules.addAll(createRules(region, groupId, perm, false));
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
for (IpPermission perm : permissions) {
next.add(perm);
rules.addAll(createRules(region, groupId, perm, false));
}
sg.setIpPermissions(next);
securityGroups.put(key(region, groupId), sg);
}
securityGroups.put(key(region, groupId), sg);
reconcilePublishedPortsForGroup(region, groupId);
return rules;
}
public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<SecurityGroupRule> rules = new ArrayList<>();
for (IpPermission perm : permissions) {
sg.getIpPermissionsEgress().add(perm);
rules.addAll(createRules(region, groupId, perm, true));
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
for (IpPermission perm : permissions) {
next.add(perm);
rules.addAll(createRules(region, groupId, perm, true));
}
sg.setIpPermissionsEgress(next);
securityGroups.put(key(region, groupId), sg);
}
securityGroups.put(key(region, groupId), sg);
return rules;
}
@@ -1386,19 +1457,25 @@ public class Ec2Service {
public void revokeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
sg.getIpPermissions().removeIf(p -> matchesAnyPermission(p, permissions));
securityGroups.put(key(region, groupId), sg);
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
next.removeIf(p -> matchesAnyPermission(p, permissions));
sg.setIpPermissions(next);
securityGroups.put(key(region, groupId), sg);
}
reconcilePublishedPortsForGroup(region, groupId);
}
public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
sg.getIpPermissionsEgress().removeIf(p -> matchesAnyPermission(p, permissions));
securityGroups.put(key(region, groupId), sg);
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
next.removeIf(p -> matchesAnyPermission(p, permissions));
sg.setIpPermissionsEgress(next);
securityGroups.put(key(region, groupId), sg);
}
}
private SecurityGroup getRequiredSecurityGroup(String region, String groupId) {
@@ -2027,28 +2104,33 @@ public class Ec2Service {
public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
List<Tag> existing = tags.get(resourceId).orElse(new ArrayList<>());
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey()));
existing.add(tag);
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);
}
}
public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
List<Tag> existing = tags.get(resourceId).orElse(null);
if (existing != null) {
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey())
&& (tag.getValue() == null || tag.getValue().equals(t.getValue())));
synchronized (lockFor(key(region, resourceId))) {
List<Tag> stored = tags.get(resourceId).orElse(null);
if (stored != null) {
List<Tag> existing = new ArrayList<>(stored);
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey())
&& (tag.getValue() == null || tag.getValue().equals(t.getValue())));
}
tags.put(resourceId, existing);
updateResourceTags(region, resourceId, existing);
}
tags.put(resourceId, existing);
updateResourceTags(region, resourceId, existing);
}
}
}
@@ -2240,37 +2322,55 @@ public class Ec2Service {
assoc.setSubnetId(subnetId);
assoc.setMain(false);
assoc.setAssociationState("associated");
rt.getAssociations().add(assoc);
routeTables.put(key(region, routeTableId), rt);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
List<RouteTableAssociation> next = new ArrayList<>(current.getAssociations());
next.add(assoc);
current.setAssociations(next);
routeTables.put(key(region, routeTableId), current);
}
return assoc;
}
public void disassociateRouteTable(String region, String associationId) {
ensureDefaultResources(region);
for (RouteTable rt : routeTables.scan(k -> true)) {
if (rt.getRegion().equals(region)) {
rt.getAssociations().removeIf(a -> a.getRouteTableAssociationId().equals(associationId));
routeTables.put(key(region, rt.getRouteTableId()), rt);
if (rt.getRegion().equals(region)
&& rt.getAssociations().stream()
.anyMatch(a -> a.getRouteTableAssociationId().equals(associationId))) {
synchronized (lockFor(key(region, rt.getRouteTableId()))) {
RouteTable current = getRequiredRouteTable(region, rt.getRouteTableId());
List<RouteTableAssociation> next = new ArrayList<>(current.getAssociations());
next.removeIf(a -> a.getRouteTableAssociationId().equals(associationId));
current.setAssociations(next);
routeTables.put(key(region, current.getRouteTableId()), current);
}
}
}
}
public void createRoute(String region, String routeTableId, String destinationCidrBlock, String gatewayId, String natGatewayId) {
ensureDefaultResources(region);
RouteTable rt = getRequiredRouteTable(region, routeTableId);
Route route = new Route(destinationCidrBlock, gatewayId, "CreateRoute");
route.setNatGatewayId(natGatewayId);
rt.getRoutes().add(route);
routeTables.put(key(region, routeTableId), rt);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
List<Route> next = new ArrayList<>(current.getRoutes());
Route route = new Route(destinationCidrBlock, gatewayId, "CreateRoute");
route.setNatGatewayId(natGatewayId);
next.add(route);
current.setRoutes(next);
routeTables.put(key(region, routeTableId), current);
}
}
public void deleteRoute(String region, String routeTableId, String destinationCidrBlock) {
ensureDefaultResources(region);
RouteTable rt = getRequiredRouteTable(region, routeTableId);
rt.getRoutes().removeIf(r -> r.getDestinationCidrBlock().equals(destinationCidrBlock));
routeTables.put(key(region, routeTableId), rt);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
List<Route> next = new ArrayList<>(current.getRoutes());
next.removeIf(r -> r.getDestinationCidrBlock().equals(destinationCidrBlock));
current.setRoutes(next);
routeTables.put(key(region, routeTableId), current);
}
}
private RouteTable getRequiredRouteTable(String region, String routeTableId) {