fix(elbv2): relink target groups when ModifyRule changes a rule's actions (#8362)

ModifyRule stored a rule's new actions but left the target groups' links
to the load balancer as they were: the group the rule moved to did not
list the load balancer, and the one it left still did, so
DeleteTargetGroup refused it with ResourceInUse although nothing routed
to it. ModifyRule now links the groups its new actions forward to and
unlinks the ones nothing routes to any more, as ModifyListener does.

CreateRule, ModifyRule and DeleteRule now change a rule and its links
while holding the load balancer, as listener changes do, so one rule
change can no longer drop the link of a group another rule still
forwards to. underLoadBalancerLock and loadBalancerOf replace the inline
copies in DeleteListener and RestoreListener, and the ModifyRule
integration test builds its resources with AlbFixtures.
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-14 23:37:37 -04:00
1 parent d6cf46ba3d
commit d64d02e8f2
3 files changed
+193 -26

No files matched your search

@@ -809,7 +809,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
return;
}
ListenerState expected = listenerState(listener);
LoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(listener.getLoadBalancerArn());
LoadBalancer lb = loadBalancerOf(region, listener);
BooleanSupplier removal = () -> {
if (!isCurrentListener(region, expected)) {
return false;
@@ -827,14 +827,8 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
return true;
};
boolean removed = dataPlane.removeListener(listenerArn, expected.port(), () -> {
if (lb == null) {
return removal.getAsBoolean();
}
synchronized (lb) {
return removal.getAsBoolean();
}
});
boolean removed = dataPlane.removeListener(listenerArn, expected.port(),
() -> underLoadBalancerLock(lb, removal::getAsBoolean));
if (removed) {
return;
}
@@ -987,13 +981,15 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
rule.setActions(actions != null ? new ArrayList<>(actions) : new ArrayList<>());
rule.setDefault(false);
regionRules.put(ruleArn, rule);
rules.put(region, regionRules);
listenerToRules.computeIfAbsent(listenerArn, k -> new CopyOnWriteArrayList<>()).add(ruleArn);
synchronized (lb) {
regionRules.put(ruleArn, rule);
rules.put(region, regionRules);
listenerToRules.computeIfAbsent(listenerArn, k -> new CopyOnWriteArrayList<>()).add(ruleArn);
// update TG → LB index for all target group actions
for (Action a : rule.getActions()) {
linkTgToLb(a, listener.getLoadBalancerArn());
// update TG → LB index for all target group actions
for (Action a : rule.getActions()) {
linkTgToLb(a, listener.getLoadBalancerArn());
}
}
if (!initialTags.isEmpty()) {
@@ -1032,27 +1028,65 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
"The default rule for a listener cannot be deleted.", 400);
}
String listenerArn = rule.getListenerArn();
regionRules.remove(ruleArn);
rules.put(region, regionRules);
removeFromIndex(listenerToRules, listenerArn, ruleArn);
tags.remove(ruleArn);
Listener listener = listeners.getOrDefault(region, Map.of()).get(listenerArn);
if (listener != null) {
unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
}
underLoadBalancerLock(loadBalancerOf(region, listener), () -> {
regionRules.remove(ruleArn);
rules.put(region, regionRules);
removeFromIndex(listenerToRules, listenerArn, ruleArn);
tags.remove(ruleArn);
if (listener != null) {
unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
}
return rule;
});
dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));
}
public Rule modifyRule(String region, String ruleArn, List<RuleCondition> conditions, List<Action> actions) {
Rule rule = requireRule(region, ruleArn);
String listenerArn = rule.getListenerArn();
if (conditions != null) rule.setConditions(new ArrayList<>(conditions));
if (actions != null) rule.setActions(new ArrayList<>(actions));
persistRegion(rules, region);
Listener listener = listeners.getOrDefault(region, Map.of()).get(listenerArn);
underLoadBalancerLock(loadBalancerOf(region, listener), () -> {
if (conditions != null) {
rule.setConditions(new ArrayList<>(conditions));
}
if (actions != null) {
rule.setActions(new ArrayList<>(actions));
if (listener != null) {
// As ModifyListener does for its default actions: a target group the rule now forwards to is in
// use by the load balancer, and one nothing routes to any more is not, so it can be deleted.
for (Action action : actions) {
linkTgToLb(action, listener.getLoadBalancerArn());
}
unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
}
}
persistRegion(rules, region);
return rule;
});
dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));
return rule;
}
/** The load balancer {@code listener} belongs to; null when the listener or its load balancer is gone. */
private LoadBalancer loadBalancerOf(String region, Listener listener) {
return listener == null ? null : loadBalancers.getOrDefault(region, Map.of()).get(listener.getLoadBalancerArn());
}
/**
* Runs {@code change} holding {@code lb}'s monitor, as every change to the actions of the load balancer's
* listeners and rules does, so that unlinking the target groups nothing routes to any more sees each rule as
* the other changes left it; unlocked when there is no load balancer, as for a listener whose one is gone.
*/
private <T> T underLoadBalancerLock(LoadBalancer lb, Supplier<T> change) {
if (lb == null) {
return change.get();
}
synchronized (lb) {
return change.get();
}
}
public void setRulePriorities(String region, Map<String, Integer> arnToPriority) {
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
@@ -1556,7 +1590,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
if (listener == null) {
return;
}
LoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(listener.getLoadBalancerArn());
LoadBalancer lb = loadBalancerOf(region, listener);
if (lb == null) {
return;
}
@@ -0,0 +1,75 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.testing.AlbFixtures;
import io.floci.aws.testing.QueryRequests;
import io.floci.aws.testutil.FreePorts;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A rule moved to another target group with ModifyRule leaves the first one unused: DescribeTargetGroups lists the
* load balancer for the group the rule forwards to and not for the other, and only the unused one can be deleted.
*/
@QuarkusTest
class ElbV2ModifyRuleTargetGroupIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
@Test
void aRuleMovedToAnotherTargetGroupLeavesTheFirstUnused() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String lb = null;
String fallback = null;
String first = null;
String second = null;
String listener = null;
try {
lb = AlbFixtures.createLoadBalancer(ACCOUNT, "modify-rule-" + suffix);
fallback = AlbFixtures.createTargetGroup(ACCOUNT, "default-" + suffix, "ip", 80);
first = AlbFixtures.createTargetGroup(ACCOUNT, "first-" + suffix, "ip", 80);
second = AlbFixtures.createTargetGroup(ACCOUNT, "second-" + suffix, "ip", 80);
listener = AlbFixtures.createListener(ACCOUNT, lb, fallback, FreePorts.anyInterfacePort());
String rule = send("CreateRule", "ListenerArn", listener, "Priority", "10",
"Conditions.member.1.Field", "path-pattern", "Conditions.member.1.Values.member.1", "/app/*",
"Actions.member.1.Type", "forward", "Actions.member.1.TargetGroupArn", first)
.then().statusCode(200).extract()
.path("CreateRuleResponse.CreateRuleResult.Rules.member.RuleArn");
send("ModifyRule", "RuleArn", rule,
"Actions.member.1.Type", "forward", "Actions.member.1.TargetGroupArn", second)
.then().statusCode(200);
assertEquals(List.of(lb), loadBalancersOf(fallback));
assertEquals(List.of(), loadBalancersOf(first));
assertEquals(List.of(lb), loadBalancersOf(second));
send("DeleteTargetGroup", "TargetGroupArn", second).then().statusCode(400);
send("DeleteTargetGroup", "TargetGroupArn", first).then().statusCode(200);
first = null;
} finally {
// Deleting the listener deletes its rule too.
AlbFixtures.deleteListener(ACCOUNT, listener);
AlbFixtures.deleteLoadBalancer(ACCOUNT, lb);
for (String group : new String[] {fallback, first, second}) {
AlbFixtures.deleteTargetGroup(ACCOUNT, group);
}
}
}
private static List<String> loadBalancersOf(String targetGroup) {
return send("DescribeTargetGroups", "TargetGroupArns.member.1", targetGroup)
.then().statusCode(200).extract().xmlPath()
.getList("DescribeTargetGroupsResponse.DescribeTargetGroupsResult.TargetGroups.member"
+ ".LoadBalancerArns.member", String.class);
}
private static Response send(String action, String... params) {
return QueryRequests.request(ACCOUNT, REGION, "elasticloadbalancing", action, params).when().post("/");
}
}
@@ -21,6 +21,7 @@ import io.floci.aws.services.elbv2.model.RuleCondition;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.services.elbv2.model.TargetGroup;
import io.floci.aws.services.elbv2.model.TargetHealth;
import io.floci.aws.testing.ThreadStates;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
@@ -35,6 +36,8 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
@@ -48,6 +51,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -734,6 +738,60 @@ class ElbV2ServiceTest {
assertTrue(newTargetGroup.getLoadBalancerArns().contains(lbArn));
}
/**
* Creating, modifying and deleting a rule change which target groups the load balancer routes to while holding
* the load balancer, as listener changes do: unlinking the groups nothing routes to any more reads every rule of
* the load balancer, so a rule changed beside it unlocked could have the link of a group it forwards to dropped.
*/
@ParameterizedTest
@ValueSource(strings = {"create", "modify", "delete"})
void aRuleChangeWaitsForItsLoadBalancerAndLeavesExactlyTheGroupsItForwardsToLinked(String change)
throws Exception {
String fallback = createTargetGroup("rule-lock-default-" + change);
String first = createTargetGroup("rule-lock-first-" + change);
String second = createTargetGroup("rule-lock-second-" + change);
LoadBalancer lb = service.createLoadBalancer(REGION, "rule-lock-" + change, "internal", "application", "ipv4",
ALB_SUBNETS, List.of("sg-a"), Map.of());
String listener = service.createListener(REGION, lb.getLoadBalancerArn(), "HTTP", 80, null, List.of(),
List.of(forwardAction(fallback)), List.of(), Map.of()).getListenerArn();
Rule rule = "create".equals(change) ? null : service.createRule(REGION, listener,
List.of(pathPattern("/app/*")), 10, List.of(forwardAction(first)), Map.of());
AtomicReference<Thread> writer = new AtomicReference<>();
ExecutorService worker = Executors.newSingleThreadExecutor();
try {
Future<?> write;
synchronized (lb) {
write = worker.submit(() -> {
writer.set(Thread.currentThread());
switch (change) {
case "create" -> service.createRule(REGION, listener, List.of(pathPattern("/app/*")), 10,
List.of(forwardAction(first)), Map.of());
case "modify" -> service.modifyRule(REGION, rule.getRuleArn(), null,
List.of(forwardAction(second)));
default -> service.deleteRule(REGION, rule.getRuleArn());
}
});
ThreadStates.awaitBlockedOrDone(writer, write);
assertFalse(write.isDone(), "the rule changed without waiting for its load balancer");
ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(writer.get().threadId());
assertEquals(Thread.State.BLOCKED, info.getThreadState());
assertEquals(Thread.currentThread().threadId(), info.getLockOwnerId());
}
write.get(5, TimeUnit.SECONDS);
} finally {
worker.shutdownNow();
assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
}
assertEquals(List.of(lb.getLoadBalancerArn()), loadBalancersOf(fallback));
assertEquals("create".equals(change) ? List.of(lb.getLoadBalancerArn()) : List.of(), loadBalancersOf(first));
assertEquals("modify".equals(change) ? List.of(lb.getLoadBalancerArn()) : List.of(), loadBalancersOf(second));
}
private List<String> loadBalancersOf(String targetGroupArn) {
return service.describeTargetGroups(REGION, null, List.of(targetGroupArn), null).getFirst()
.getLoadBalancerArns();
}
@ParameterizedTest
@ValueSource(ints = {1, 65535})
void gatewayListenerRejectsExplicitPortWithoutPublication(int port) {