From 7872b07c43f577a23786c05d9b660603e1719a35 Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:48:23 +0100 Subject: [PATCH] fix(autoscaling): register instances with a target group on attach and deregister them on detach (#8469) --- docs/services/autoscaling.md | 8 +- .../autoscaling/AutoScalingReconciler.java | 3 +- .../autoscaling/AutoScalingService.java | 75 ++++++--- .../autoscaling/AutoScalingStandbyTest.java | 24 +++ .../AutoScalingTargetGroupAttachmentTest.java | 159 ++++++++++++++++++ .../services/autoscaling/TargetMatchers.java | 7 +- 6 files changed, 243 insertions(+), 33 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index acebe0dec8..f2aceac851 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -180,8 +180,8 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash. | Operation | Notes | |---|---| -| `AttachLoadBalancerTargetGroups` | Attaches ELB v2 target group ARNs. The reconciler registers each instance with them as it comes into service; instances already in service stay unregistered, which AWS registers. An EKS nodegroup's group registers its node at once | -| `DetachLoadBalancerTargetGroups` | Detaches target groups. The group's instances stay registered with them, which AWS deregisters; an EKS nodegroup's group deregisters its node at once | +| `AttachLoadBalancerTargetGroups` | Attaches ELB v2 target group ARNs and registers the group's `InService` instances with the ones it adds, as AWS does; the reconciler registers each later instance as it comes into service | +| `DetachLoadBalancerTargetGroups` | Detaches target groups and deregisters the group's instances from them, as AWS does; a target group already deleted is detached all the same. An EKS nodegroup's node stays registered with a target group another nodegroup's group still has attached | | `DescribeLoadBalancerTargetGroups` | Lists target groups attached to a group | | `AttachLoadBalancers` | Classic ELB attachment (stored; no ELB v1 routing) | | `DetachLoadBalancers` | Classic ELB detachment | @@ -191,8 +191,8 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash. | Operation | Notes | |---|---| -| `AttachTrafficSources` | Unified elb/elbv2/vpc-lattice attachment API; stored per identifier with its type. Instances are not registered with an `elbv2` source, which AWS does, except an EKS nodegroup's node, registered at once | -| `DetachTrafficSources` | Removes a traffic source by identifier; an EKS nodegroup's group deregisters its node from an `elbv2` source at once | +| `AttachTrafficSources` | Unified elb/elbv2/vpc-lattice attachment API; stored per identifier with its type. The group's `InService` instances are registered with an `elbv2` source it adds, as with a target group | +| `DetachTrafficSources` | Removes a traffic source by identifier, deregistering the group's instances from an `elbv2` source | | `DescribeTrafficSources` | Lists attached sources, optionally filtered by type; every source reports `InService` | ### Lifecycle Hooks diff --git a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java index 352654f35a..c72c69c33a 100644 --- a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java +++ b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java @@ -299,7 +299,8 @@ public class AutoScalingReconciler { if ("running".equals(ec2State)) { String standbyActivityId = asgInst.getStandbyActivityId(); boolean returningFromStandby = standbyActivityId != null; - AutoScalingService.registerWithTargetGroups(elbV2Service, asg, asg.getTargetGroupARNs(), + AutoScalingService.registerWithTargetGroups(elbV2Service, asg, + AutoScalingService.attachedTargetGroups(asg), asgInst.getInstanceId(), returningFromStandby); registerWithClassicLoadBalancers(asg, asgInst, returningFromStandby); asgInst.setLifecycleState("InService"); diff --git a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java index 0e4075ac5b..bac9fd9fb0 100644 --- a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java @@ -634,6 +634,14 @@ public class AutoScalingService implements PassedRoleLookup { // is not terminated, and stays in the target groups another of their groups has attached. deregisterFromUnsharedTargetGroups(asg, memberIds(asg), attachedTargetGroups(asg)); } else if (forceDelete && ec2Service != null && !active.isEmpty()) { + // The instances leave the group's load balancers before they are terminated, as on a scale-in. + List leaving = active.stream().map(AsgInstance::getInstanceId).filter(Objects::nonNull).toList(); + if (elbV2Service != null) { + deregisterFromTargetGroups(elbV2Service, asg, leaving); + } + if (elbClassicService != null) { + deregisterFromClassicLoadBalancers(elbClassicService, asg, leaving); + } active.stream() .map(AsgInstance::getInstanceId) .filter(Objects::nonNull) @@ -1037,16 +1045,30 @@ public class AutoScalingService implements PassedRoleLookup { */ static void registerWithTargetGroups(ElbV2Service elb, AutoScalingGroup asg, Collection targetGroupArns, String instanceId, boolean strict) { + registerWithTargetGroups(elb, asg, targetGroupArns, List.of(instanceId), strict); + } + + /** As above, for several instances, with one call to each target group. */ + static void registerWithTargetGroups(ElbV2Service elb, AutoScalingGroup asg, Collection targetGroupArns, + List instanceIds, boolean strict) { + if (instanceIds.isEmpty()) { + return; + } + String instances = String.join(", ", instanceIds); for (String tgArn : targetGroupArns) { + // Fresh targets for each target group: ELBv2 fills a target's missing port in with the group's own. + List targets = instanceIds.stream().map(id -> { + TargetDescription target = new TargetDescription(); + target.setId(id); + return target; + }).toList(); try { - TargetDescription td = new TargetDescription(); - td.setId(instanceId); - elb.registerTargets(asg.getRegion(), tgArn, List.of(td)); + elb.registerTargets(asg.getRegion(), tgArn, targets); LOG.debugv("ASG {0}: registered {1} with TG {2}", - asg.getAutoScalingGroupName(), instanceId, tgArn); + asg.getAutoScalingGroupName(), instances, tgArn); } catch (Exception e) { LOG.warnv(e, "ASG {0}: could not register {1} with TG {2}: {3}", - asg.getAutoScalingGroupName(), instanceId, tgArn, e.getMessage()); + asg.getAutoScalingGroupName(), instances, tgArn, e.getMessage()); if (strict && !(e instanceof AwsException aws && "TargetGroupNotFound".equals(aws.getErrorCode()))) { throw e; @@ -1071,8 +1093,9 @@ public class AutoScalingService implements PassedRoleLookup { } } + /** Deregisters {@code instanceIds} from every target group attached to {@code asg}, elbv2 sources included. */ static void deregisterFromTargetGroups(ElbV2Service elb, AutoScalingGroup asg, List instanceIds) { - deregisterFromTargetGroups(elb, asg, asg.getTargetGroupARNs(), instanceIds); + deregisterFromTargetGroups(elb, asg, attachedTargetGroups(asg), instanceIds); } /** As above, from {@code targetGroupArns} rather than from every target group the group has attached. */ @@ -1495,9 +1518,9 @@ public class AutoScalingService implements PassedRoleLookup { // unified ASG-to-load-balancer wiring API (elb, elbv2, vpc-lattice), which // aws_autoscaling_traffic_source_attachment uses instead of the older // AttachLoadBalancerTargetGroups. Like the target-group attachment above, each source is - // stored with its type, and only an EKS group's node is registered with an elbv2 source as - // it is attached and deregistered as it is detached. Floci has no real health-checking loop, - // so every attached traffic source is reported InService immediately. + // stored with its type, and the group's instances join and leave an elbv2 source as they + // do a target group attached the older way. Floci has no real health-checking loop, so + // every attached traffic source is reported InService immediately. public record TrafficSourceIdentifier(String identifier, String type) {} @@ -1533,7 +1556,7 @@ public class AutoScalingService implements PassedRoleLookup { } /** The target groups attached to {@code asg}: as target groups, and as {@code elbv2} traffic sources. */ - private static Set attachedTargetGroups(AutoScalingGroup asg) { + static Set attachedTargetGroups(AutoScalingGroup asg) { Set attached = new LinkedHashSet<>(asg.getTargetGroupARNs()); asg.getTrafficSourceTypeByIdentifier().forEach((identifier, type) -> { if ("elbv2".equals(type)) { @@ -1615,19 +1638,13 @@ public class AutoScalingService implements PassedRoleLookup { /** * Applies {@code change} to the target groups and traffic sources attached to the group {@code name}, and - * stores it. An EKS group's in-service members are then registered with the target groups the change attached - * and deregistered from those it detached, as AWS does, all under the Region's lock and then the group's, like - * every change to an EKS group's members or target groups. Other groups' members are left as they are: the - * reconciler registers them as they come into service. + * stores it. The group's members are deregistered from the target groups the change detached, and its in-service + * members registered with those it attached, as AWS does, all under the Region's lock and then the group's, in + * the order {@code attachInstances} and the changes to an EKS group's members take them. An instance an EKS group + * shares with another group stays in a target group that other group still has attached. */ private void changeAttachments(String region, String name, Consumer change) { String key = asgKey(region, name); - AutoScalingGroup asg = requireGroup(region, name); - if (!asg.isEksManaged()) { - change.accept(asg); - groups.put(key, asg); - return; - } synchronized (lockFor(region)) { synchronized (lockFor(key)) { AutoScalingGroup current = requireGroup(region, name); @@ -1639,21 +1656,25 @@ public class AutoScalingService implements PassedRoleLookup { Set detached = new LinkedHashSet<>(attachedBefore); detached.removeAll(attached); attached.removeAll(attachedBefore); - // The node leaves the target groups the change detached before the change is stored: when ELBv2 + // The members leave the target groups the change detached before the change is stored: when ELBv2 // refuses, the group keeps them attached, so the detach can be sent again. try { - deregisterFromUnsharedTargetGroups(current, memberIds(current), detached); + if (current.isEksManaged()) { + deregisterFromUnsharedTargetGroups(current, memberIds(current), detached); + } else if (!detached.isEmpty() && !memberIds(current).isEmpty()) { + // An ordinary group's instances are its own, so they leave every target group it detached. + deregisterFromTargetGroups(elbV2Service, current, detached, memberIds(current)); + } } catch (RuntimeException e) { current.setTargetGroupARNs(targetGroupsBefore); current.setTrafficSourceTypeByIdentifier(trafficSourcesBefore); throw e; } groups.put(key, current); - for (AsgInstance member : current.getInstances()) { - if ("InService".equals(member.getLifecycleState())) { - registerWithTargetGroups(elbV2Service, current, attached, member.getInstanceId(), false); - } - } + List inService = current.getInstances().stream() + .filter(member -> "InService".equals(member.getLifecycleState())) + .map(AsgInstance::getInstanceId).filter(Objects::nonNull).toList(); + registerWithTargetGroups(elbV2Service, current, attached, inService, false); } } } diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java index 607b856959..dcd05f30a9 100644 --- a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java @@ -42,6 +42,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.LogRecord; +import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -318,6 +319,29 @@ class AutoScalingStandbyTest { assertEquals(1, launches.get()); } + /** + * An instance leaves an elbv2 traffic source as it enters standby and joins it again as it comes back into + * service, as it does a target group attached as one. + */ + @Test + void anElbV2TrafficSourceIsLeftInStandbyAndJoinedAgainOnTheWayBack() { + String source = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/source/0123456789abcdef"; + AutoScalingGroup group = group(); + group.getTrafficSourceTypeByIdentifier().put(source, "elbv2"); + service.saveAutoScalingGroupIfPresent(group); + + ok(enterStandby(true, "i-a")); + reconciler.reconcile(group()); + assertEquals("Standby", lifecycle("i-a")); + verify(elbV2).deregisterTargets(eq(REGION), eq(source), onlyTarget("i-a")); + clearInvocations(elbV2); + + ok(exitStandby("i-a")); + reconciler.reconcile(group()); + assertEquals("InService", lifecycle("i-a")); + verify(elbV2).registerTargets(eq(REGION), eq(source), onlyTarget("i-a")); + } + @Test void exitStandbyGoesThroughPendingAndRegistersWithTheLoadBalancers() { ok(enterStandby(true, "i-a")); diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java new file mode 100644 index 0000000000..b0f2e6d781 --- /dev/null +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java @@ -0,0 +1,159 @@ +package io.floci.aws.services.autoscaling; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.autoscaling.model.AsgInstance; +import io.floci.aws.services.autoscaling.model.AutoScalingGroup; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.elb.ElbClassicService; +import io.floci.aws.services.elbv2.ElbV2Service; +import io.floci.aws.services.elbv2.model.TargetDescription; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static io.floci.aws.services.autoscaling.TargetMatchers.exactlyTargets; +import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Attaching a target group to a group registers the group's in-service instances with it, and detaching one + * deregisters the group's instances from it, as AWS does, for an ordinary group as for an EKS group + * ({@link AutoScalingEksManagedGroupTest}): as target groups and as {@code elbv2} traffic sources. + */ +class AutoScalingTargetGroupAttachmentTest { + + private static final String REGION = "us-east-1"; + private static final String GROUP = "web"; + private static final String IN_SERVICE = "i-0a1b2c3d4e5f60001"; + private static final String STANDBY = "i-0a1b2c3d4e5f60002"; + + private final ElbV2Service targets = mock(ElbV2Service.class); + private final AutoScalingService service = new AutoScalingService(targets, mock(ElbClassicService.class)); + private final AutoScalingGroup group = new AutoScalingGroup(); + + AutoScalingTargetGroupAttachmentTest() { + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.ec2Service = mock(Ec2Service.class); + group.setAutoScalingGroupName(GROUP); + group.setRegion(REGION); + group.setTargetGroupARNs(new ArrayList<>(List.of("tg-attached"))); + group.getInstances().addAll(List.of(member(IN_SERVICE, "InService"), member(STANDBY, "Standby"))); + service.groups.put(REGION + "::" + GROUP, group); + } + + @Test + void attachingATargetGroupRegistersTheGroupsInServiceInstancesWithIt() { + service.attachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-attached", "tg-new")); + + // Only the target group the attach added, and only the instance in service: one in standby is not. + verify(targets).registerTargets(eq(REGION), eq("tg-new"), onlyTarget(IN_SERVICE)); + verifyNoMoreInteractions(targets); + assertEquals(List.of("tg-attached", "tg-new"), group.getTargetGroupARNs()); + } + + /** + * Each target group gets targets of its own: ELBv2 fills a target's missing port in with its group's port, so + * targets shared between two groups would join the second with the first group's port. + */ + @Test + void eachTargetGroupAttachedAtOnceRegistersTargetsOfItsOwn() { + List portsGiven = new ArrayList<>(); + doAnswer(call -> { + List given = call.getArgument(2); + given.forEach(target -> portsGiven.add(target.getPort())); + given.forEach(target -> target.setPort("tg-http".equals(call.getArgument(1)) ? 80 : 8080)); + return null; + }).when(targets).registerTargets(eq(REGION), anyString(), anyList()); + + service.attachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-http", "tg-admin")); + + Integer noPort = null; + assertEquals(Arrays.asList(noPort, noPort), portsGiven); + } + + /** A group deleted with its instances takes them out of its target groups before it terminates them. */ + @Test + void aForceDeleteDeregistersTheInstancesBeforeTerminatingThem() { + service.deleteAutoScalingGroup(REGION, GROUP, true); + + InOrder order = inOrder(targets, service.ec2Service); + order.verify(targets).deregisterTargets(eq(REGION), eq("tg-attached"), exactlyTargets(IN_SERVICE, STANDBY)); + order.verify(service.ec2Service).terminateInstances(REGION, List.of(IN_SERVICE)); + } + + @Test + void detachingATargetGroupDeregistersTheGroupsInstancesFromIt() { + group.getTargetGroupARNs().add("tg-kept"); + + service.detachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-attached")); + + // In one call: the group's instances are its own, so none stays in the target group for another group. + verify(targets).deregisterTargets(eq(REGION), eq("tg-attached"), exactlyTargets(IN_SERVICE, STANDBY)); + verifyNoMoreInteractions(targets); + assertEquals(List.of("tg-kept"), group.getTargetGroupARNs()); + } + + @Test + void anElbV2TrafficSourceRegistersAndDeregistersTheInstancesAsATargetGroupDoes() { + service.attachTrafficSources(REGION, GROUP, List.of( + new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"))); + verify(targets).registerTargets(eq(REGION), eq("tg-source"), onlyTarget(IN_SERVICE)); + + service.detachTrafficSources(REGION, GROUP, List.of( + new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"))); + + verify(targets).deregisterTargets(eq(REGION), eq("tg-source"), exactlyTargets(IN_SERVICE, STANDBY)); + verifyNoMoreInteractions(targets); + assertEquals(Map.of(), group.getTrafficSourceTypeByIdentifier()); + } + + @Test + void aDetachElbV2RefusesLeavesTheTargetGroupAttachedSoTheDetachCanBeSentAgain() { + AwsException refusal = new AwsException("Throttling", "Rate exceeded", 400); + doThrow(refusal).doNothing().when(targets).deregisterTargets(eq(REGION), eq("tg-attached"), anyList()); + + assertSame(refusal, assertThrows(AwsException.class, + () -> service.detachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-attached")))); + assertEquals(List.of("tg-attached"), group.getTargetGroupARNs()); + + service.detachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-attached")); + + verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-attached"), + exactlyTargets(IN_SERVICE, STANDBY)); + assertEquals(List.of(), group.getTargetGroupARNs()); + } + + @Test + void aTargetGroupDeletedBeforeItsDetachIsDetached() { + doThrow(new AwsException("TargetGroupNotFound", "One or more target groups not found", 400)) + .when(targets).deregisterTargets(eq(REGION), eq("tg-attached"), anyList()); + + service.detachLoadBalancerTargetGroups(REGION, GROUP, List.of("tg-attached")); + + assertEquals(List.of(), group.getTargetGroupARNs()); + } + + private static AsgInstance member(String id, String state) { + AsgInstance member = new AsgInstance(); + member.setInstanceId(id); + member.setLifecycleState(state); + return member; + } +} diff --git a/src/test/java/io/floci/aws/services/autoscaling/TargetMatchers.java b/src/test/java/io/floci/aws/services/autoscaling/TargetMatchers.java index 419128c7e8..716eede11c 100644 --- a/src/test/java/io/floci/aws/services/autoscaling/TargetMatchers.java +++ b/src/test/java/io/floci/aws/services/autoscaling/TargetMatchers.java @@ -13,6 +13,11 @@ final class TargetMatchers { /** Matches a target list holding {@code instanceId} and nothing else. */ static List onlyTarget(String instanceId) { - return argThat(targets -> targets.size() == 1 && instanceId.equals(targets.getFirst().getId())); + return exactlyTargets(instanceId); + } + + /** Matches a target list holding exactly {@code instanceIds}, in that order. */ + static List exactlyTargets(String... instanceIds) { + return argThat(targets -> targets.stream().map(TargetDescription::getId).toList().equals(List.of(instanceIds))); } }