From e714fd95946f81062ac2d2da33af3f2d1a614825 Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Sat, 31 Oct 2026 04:12:23 -0500 Subject: [PATCH] fix(autoscaling): scope target cleanup to group-owned instances (#7038) * fix(autoscaling): preserve group-owned target cleanup across lifecycle paths Preserve the reviewed strict shared cleanup, Classic load-balancer detach behavior, and failure ownership for retries. Reconcile current main test SDK dependencies without changing the reviewed Java sources. Signed-off-by: Andre Kurait * fix(autoscaling): share Classic cleanup and retain failed members Use the same Classic load-balancer deregistration helper for detach and every reconciler cleanup path. Preserve members for retry on actual failures, tolerate deleted balancers, and move detach cases to the existing complete fixture. Signed-off-by: Andre Kurait --------- Signed-off-by: Andre Kurait --- pom.xml | 12 ++ .../autoscaling/AutoScalingReconciler.java | 82 ++------- .../autoscaling/AutoScalingService.java | 51 ++++++ ...ingDetachLoadBalancersIntegrationTest.java | 81 +++++++++ .../AutoScalingDetachLoadBalancersTest.java | 160 +++++++++++++++++ .../AutoScalingReconcilerTest.java | 158 ++++++++++++++--- .../AutoScalingStandbyStorageTest.java | 28 +++ .../AutoScalingTargetCleanupStorageTest.java | 166 ++++++++++++++++++ 8 files changed, 646 insertions(+), 92 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingTargetCleanupStorageTest.java diff --git a/pom.xml b/pom.xml index eeab220463..9cabe0095b 100644 --- a/pom.xml +++ b/pom.xml @@ -516,6 +516,18 @@ ${aws.sdk.version} test + + software.amazon.awssdk + autoscaling + ${aws.sdk.version} + test + + + software.amazon.awssdk + elasticloadbalancing + ${aws.sdk.version} + test + io.quarkus quarkus-junit diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java index 244f647035..b0d3621975 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java @@ -22,7 +22,6 @@ import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.elb.ElbClassicService; import io.github.hectorvent.floci.services.elbv2.ElbV2Service; import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; -import io.github.hectorvent.floci.services.elbv2.model.TargetHealth; import io.github.hectorvent.floci.services.ssm.SsmCommandService; import io.quarkus.runtime.StartupEvent; import jakarta.annotation.PostConstruct; @@ -144,7 +143,6 @@ public class AutoScalingReconciler { settleStandbyMoves(asg); removeTerminatingInstances(asg); removeStaleInstances(asg); - removeOrphanedTargetRegistrations(asg); promoteReadyInstances(asg); reconcileRefreshReplacements(asg); @@ -255,8 +253,8 @@ public class AutoScalingReconciler { } if (!entering.isEmpty()) { List instanceIds = entering.stream().map(AsgInstance::getInstanceId).toList(); - deregisterFromTargetGroups(asg, instanceIds); - deregisterFromClassicLoadBalancers(asg, instanceIds); + AutoScalingService.deregisterFromTargetGroups(elbV2Service, asg, instanceIds); + AutoScalingService.deregisterFromClassicLoadBalancers(elbClassicService, asg, instanceIds); for (AsgInstance instance : entering) { instance.setLifecycleState("Standby"); if (instance.getStandbyActivityId() != null) { @@ -343,8 +341,8 @@ public class AutoScalingReconciler { .map(AsgInstance::getInstanceId) .collect(Collectors.toList()); failActiveSsmInvocations(asg, instanceIds); - deregisterFromTargetGroups(asg, instanceIds); - deregisterFromClassicLoadBalancers(asg, instanceIds); + AutoScalingService.deregisterFromTargetGroups(elbV2Service, asg, instanceIds); + AutoScalingService.deregisterFromClassicLoadBalancers(elbClassicService, asg, instanceIds); asg.getInstances().removeIf(instance -> instanceIds.contains(instance.getInstanceId())); asgService.saveAutoScalingGroupIfPresent(asg); asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(), @@ -376,8 +374,8 @@ public class AutoScalingReconciler { } } failActiveSsmInvocations(asg, instanceIds); - deregisterFromTargetGroups(asg, instanceIds); - deregisterFromClassicLoadBalancers(asg, instanceIds); + AutoScalingService.deregisterFromTargetGroups(elbV2Service, asg, instanceIds); + AutoScalingService.deregisterFromClassicLoadBalancers(elbClassicService, asg, instanceIds); asgService.cancelStandbyMoves(returning); asg.getInstances().removeIf(instance -> instanceIds.contains(instance.getInstanceId())); asgService.saveAutoScalingGroupIfPresent(asg); @@ -455,39 +453,6 @@ public class AutoScalingReconciler { } } - private void removeOrphanedTargetRegistrations(AutoScalingGroup asg) { - if (asg.getTargetGroupARNs().isEmpty()) { - return; - } - - Set activeInstanceIds = asg.getInstances().stream() - .filter(instance -> isActiveLifecycleState(instance.getLifecycleState()) - || pausedRefreshOwns(asg, instance.getInstanceId())) - .map(AsgInstance::getInstanceId) - .collect(Collectors.toSet()); - - for (String tgArn : asg.getTargetGroupARNs()) { - try { - List orphanedTargets = elbV2Service.describeTargetHealth( - asg.getRegion(), tgArn, List.of()).stream() - .map(TargetHealth::getTarget) - .filter(target -> target != null && target.getId() != null) - .filter(target -> !activeInstanceIds.contains(target.getId())) - .collect(Collectors.toList()); - if (!orphanedTargets.isEmpty()) { - elbV2Service.deregisterTargets(asg.getRegion(), tgArn, orphanedTargets); - LOG.infov("ASG {0}: deregistered orphaned target(s) {1} from TG {2}", - asg.getAutoScalingGroupName(), - orphanedTargets.stream().map(TargetDescription::getId).collect(Collectors.toList()), - tgArn); - } - } catch (Exception e) { - LOG.debugv("ASG {0}: could not reconcile TG {1}: {2}", - asg.getAutoScalingGroupName(), tgArn, e.getMessage()); - } - } - } - private void removeTerminatingInstances(AutoScalingGroup asg) { List terminatingInstances = asg.getInstances().stream() .filter(instance -> "Terminating".equals(instance.getLifecycleState())) @@ -522,8 +487,8 @@ public class AutoScalingReconciler { return; } - deregisterFromTargetGroups(asg, instanceIds); - deregisterFromClassicLoadBalancers(asg, instanceIds); + AutoScalingService.deregisterFromTargetGroups(elbV2Service, asg, instanceIds); + AutoScalingService.deregisterFromClassicLoadBalancers(elbClassicService, asg, instanceIds); asg.getInstances().removeIf(instance -> instanceIds.contains(instance.getInstanceId())); asgService.saveAutoScalingGroupIfPresent(asg); asgService.recordActivity(asg.getRegion(), asg.getAutoScalingGroupName(), @@ -856,8 +821,8 @@ public class AutoScalingReconciler { return; } - deregisterFromTargetGroups(asg, instanceIds); - deregisterFromClassicLoadBalancers(asg, instanceIds); + AutoScalingService.deregisterFromTargetGroups(elbV2Service, asg, instanceIds); + AutoScalingService.deregisterFromClassicLoadBalancers(elbClassicService, asg, instanceIds); asg.getInstances().removeIf(i -> instanceIds.contains(i.getInstanceId())); asgService.saveAutoScalingGroupIfPresent(asg); @@ -907,19 +872,6 @@ public class AutoScalingReconciler { return message.substring(0, end) + suffix; } - private void deregisterFromTargetGroups(AutoScalingGroup asg, List instanceIds) { - for (String tgArn : asg.getTargetGroupARNs()) { - try { - List targets = instanceIds.stream() - .map(id -> { TargetDescription td = new TargetDescription(); td.setId(id); return td; }) - .collect(Collectors.toList()); - elbV2Service.deregisterTargets(asg.getRegion(), tgArn, targets); - } catch (Exception e) { - LOG.debugv("ASG {0}: could not deregister from TG {1}: {2}", - asg.getAutoScalingGroupName(), tgArn, e.getMessage()); - } - } - } /** * Registers a newly launched instance with every Classic load balancer the group names. @@ -946,20 +898,6 @@ public class AutoScalingReconciler { } } - private void deregisterFromClassicLoadBalancers(AutoScalingGroup asg, List instanceIds) { - if (elbClassicService == null) { - return; - } - for (String lbName : asg.getLoadBalancerNames()) { - try { - elbClassicService.deregisterInstances(asg.getRegion(), lbName, instanceIds); - } catch (Exception e) { - LOG.debugv("ASG {0}: could not deregister from Classic ELB {1}: {2}", - asg.getAutoScalingGroupName(), lbName, e.getMessage()); - } - } - } - private void registerWithTargetGroups(AutoScalingGroup asg, AsgInstance asgInst) { for (String tgArn : asg.getTargetGroupARNs()) { try { diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index cc58abf5e4..9bd7692dc5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -17,6 +17,9 @@ import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; import io.github.hectorvent.floci.services.ec2.model.Tag; +import io.github.hectorvent.floci.services.elb.ElbClassicService; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; +import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; @@ -126,6 +129,19 @@ public class AutoScalingService implements PassedRoleLookup { @Inject Ec2Service ec2Service; + private final ElbV2Service elbV2Service; + private final ElbClassicService elbClassicService; + + @Inject + public AutoScalingService(ElbV2Service elbV2Service, ElbClassicService elbClassicService) { + this.elbV2Service = elbV2Service; + this.elbClassicService = elbClassicService; + } + + AutoScalingService() { + this(null, null); + } + // region :: name → resource private Map launchConfigs = new ConcurrentHashMap<>(); Map groups = new ConcurrentHashMap<>(); @@ -940,6 +956,39 @@ public class AutoScalingService implements PassedRoleLookup { } } + static void deregisterFromTargetGroups(ElbV2Service elb, AutoScalingGroup asg, List instanceIds) { + List targets = instanceIds.stream().map(id -> { + TargetDescription target = new TargetDescription(); + target.setId(id); + return target; + }).toList(); + for (String targetGroup : asg.getTargetGroupARNs()) { + try { + elb.deregisterTargets(asg.getRegion(), targetGroup, targets); + } catch (AwsException e) { + if (!"TargetGroupNotFound".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("ASG {0}: target group {1} is already deleted", asg.getAutoScalingGroupName(), targetGroup); + } + } + } + + static void deregisterFromClassicLoadBalancers(ElbClassicService elb, AutoScalingGroup asg, + List instanceIds) { + for (String loadBalancer : asg.getLoadBalancerNames()) { + try { + elb.deregisterInstances(asg.getRegion(), loadBalancer, instanceIds); + } catch (AwsException e) { + if (!"LoadBalancerNotFound".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("ASG {0}: Classic load balancer {1} is already deleted", + asg.getAutoScalingGroupName(), loadBalancer); + } + } + } + public void detachInstances(String region, String name, List instanceIds, boolean decrementDesiredCapacity) { String key = asgKey(region, name); @@ -959,6 +1008,8 @@ public class AutoScalingService implements PassedRoleLookup { List detached = asg.getInstances().stream().map(AsgInstance::getInstanceId) .filter(instanceIds::contains).toList(); if (!detached.isEmpty()) { + deregisterFromTargetGroups(elbV2Service, asg, detached); + deregisterFromClassicLoadBalancers(elbClassicService, asg, detached); // Detaching removes only the group-name tag, and only where it still names this group. ec2Service.deleteSystemTag(region, detached, GROUP_NAME_TAG, name); } diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersIntegrationTest.java new file mode 100644 index 0000000000..cc41cefa70 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersIntegrationTest.java @@ -0,0 +1,81 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.autoscaling.AutoScalingClient; +import software.amazon.awssdk.services.elasticloadbalancing.ElasticLoadBalancingClient; +import software.amazon.awssdk.services.elasticloadbalancing.model.Instance; +import software.amazon.awssdk.services.elasticloadbalancing.model.Listener; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class AutoScalingDetachLoadBalancersIntegrationTest { + // Exercise management membership through the SDK without launching an EC2 guest. + @InjectMock + AutoScalingReconciler reconciler; + + @Test + void sdkDetachPreservesOtherGroupAndManualClassicRegistrations() throws Exception { + String name = "detach-" + UUID.randomUUID().toString().substring(0, 12); + try (AutoScalingClient scaling = AwsTestClients.create(AutoScalingClient.builder(), "000000000000", Region.US_EAST_1); + ElasticLoadBalancingClient classic = AwsTestClients.create( + ElasticLoadBalancingClient.builder(), "000000000000", Region.US_EAST_1)) { + classic.createLoadBalancer(request -> request.loadBalancerName(name).availabilityZones("us-east-1a") + .listeners(Listener.builder().protocol("HTTP").loadBalancerPort(80).instancePort(8080).build())); + try (AutoCloseable loadBalancer = () -> classic.deleteLoadBalancer(request -> request.loadBalancerName(name))) { + scaling.createLaunchConfiguration(request -> request.launchConfigurationName(name) + .imageId("ami-12345678").instanceType("t3.micro")); + try (AutoCloseable launchConfiguration = () -> scaling.deleteLaunchConfiguration( + request -> request.launchConfigurationName(name))) { + createGroup(scaling, name, name); + try (AutoCloseable group = () -> scaling.deleteAutoScalingGroup( + request -> request.autoScalingGroupName(name).forceDelete(true))) { + String other = name + "-other"; + createGroup(scaling, other, name); + try (AutoCloseable otherGroup = () -> scaling.deleteAutoScalingGroup( + request -> request.autoScalingGroupName(other).forceDelete(true))) { + scaling.attachInstances(request -> request.autoScalingGroupName(name).instanceIds("i-owned")); + scaling.attachInstances(request -> request.autoScalingGroupName(other).instanceIds("i-other")); + classic.registerInstancesWithLoadBalancer(request -> request.loadBalancerName(name).instances( + Instance.builder().instanceId("i-owned").build(), + Instance.builder().instanceId("i-other").build(), + Instance.builder().instanceId("i-manual").build())); + + scaling.detachInstances(request -> request.autoScalingGroupName(name) + .instanceIds("i-owned").shouldDecrementDesiredCapacity(true)); + + assertEquals(List.of("i-other", "i-manual"), classic.describeLoadBalancers( + request -> request.loadBalancerNames(name)).loadBalancerDescriptions().getFirst() + .instances().stream().map(Instance::instanceId).toList()); + assertTrue(scaling.describeAutoScalingGroups(request -> request.autoScalingGroupNames(name)) + .autoScalingGroups().getFirst().instances().isEmpty()); + assertEquals(List.of("i-other"), scaling.describeAutoScalingGroups( + request -> request.autoScalingGroupNames(other)).autoScalingGroups().getFirst() + .instances().stream().map(instance -> instance.instanceId()).toList()); + } + } + } + } + assertTrue(scaling.describeAutoScalingGroups(request -> request.autoScalingGroupNames(name, name + "-other")) + .autoScalingGroups().isEmpty()); + assertTrue(scaling.describeLaunchConfigurations(request -> request.launchConfigurationNames(name)) + .launchConfigurations().isEmpty()); + assertTrue(classic.describeLoadBalancers().loadBalancerDescriptions().stream() + .noneMatch(loadBalancer -> name.equals(loadBalancer.loadBalancerName()))); + } + } + + private static void createGroup(AutoScalingClient scaling, String group, String loadBalancer) { + scaling.createAutoScalingGroup(request -> request.autoScalingGroupName(group) + .launchConfigurationName(loadBalancer).minSize(0).maxSize(3).desiredCapacity(0) + .availabilityZones("us-east-1a").loadBalancerNames(loadBalancer)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersTest.java new file mode 100644 index 0000000000..fad84107dc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingDetachLoadBalancersTest.java @@ -0,0 +1,160 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; +import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup; +import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefresh; +import io.github.hectorvent.floci.services.autoscaling.model.InstanceRefreshReplacement; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.elb.ElbClassicService; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class AutoScalingDetachLoadBalancersTest { + private static final String REGION = "us-east-1"; + private final ElbV2Service targets = mock(ElbV2Service.class); + private final ElbClassicService classic = mock(ElbClassicService.class); + private final AutoScalingService service = new AutoScalingService(targets, classic); + private final AutoScalingGroup group = new AutoScalingGroup(); + private final AsgInstance owned = member("i-owned"); + private final AsgInstance retained = member("i-retained"); + + AutoScalingDetachLoadBalancersTest() { + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.ec2Service = mock(Ec2Service.class); + group.setAutoScalingGroupName("group"); + group.setRegion(REGION); + group.setDesiredCapacity(2); + group.setLoadBalancerNames(List.of("first", "second")); + group.setTargetGroupARNs(List.of("target-group")); + group.getInstances().addAll(List.of(owned, retained)); + service.groups.put(REGION + "::group", group); + } + + @ParameterizedTest + @ValueSource(strings = {"InService", "Standby"}) + void detachCleansBothBalancerKindsAndOnlyActualMembers(String state) { + owned.setLifecycleState(state); + + service.detachInstances(REGION, "group", List.of("i-owned", "i-other-group"), false); + + verify(classic).deregisterInstances(REGION, "first", List.of("i-owned")); + verify(classic).deregisterInstances(REGION, "second", List.of("i-owned")); + verifyNoMoreInteractions(classic); + verify(targets).deregisterTargets(eq(REGION), eq("target-group"), + argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId()))); + assertEquals(List.of(retained), group.getInstances()); + assertEquals(2, group.getDesiredCapacity()); + } + + @Test + void failedClassicCleanupPreservesMembershipCapacityTagsAndRefreshUntilRetry() { + InstanceRefresh refresh = service.startInstanceRefresh(REGION, "group", new InstanceRefresh()); + assertEquals(List.of("i-owned", "i-retained"), refresh.getReplacements().stream() + .map(InstanceRefreshReplacement::getOriginalInstanceId).toList()); + AwsException failure = new AwsException("Throttling", "retry", 503); + when(classic.deregisterInstances(REGION, "second", List.of("i-owned"))) + .thenThrow(failure).thenReturn(List.of("i-retained")); + + assertSame(failure, assertThrows(AwsException.class, + () -> service.detachInstances(REGION, "group", List.of("i-owned"), true))); + assertEquals(List.of(owned, retained), group.getInstances()); + assertEquals(2, group.getDesiredCapacity()); + verifyNoInteractions(service.ec2Service); + assertEquals(List.of("i-owned", "i-retained"), refresh.getReplacements().stream() + .map(InstanceRefreshReplacement::getOriginalInstanceId).toList()); + + service.detachInstances(REGION, "group", List.of("i-owned"), true); + + assertEquals(List.of(retained), group.getInstances()); + assertEquals(1, group.getDesiredCapacity()); + assertEquals(List.of("i-retained"), refresh.getReplacements().stream() + .map(InstanceRefreshReplacement::getOriginalInstanceId).toList()); + verify(classic, times(2)).deregisterInstances(REGION, "first", List.of("i-owned")); + verify(classic, times(2)).deregisterInstances(REGION, "second", List.of("i-owned")); + verify(service.ec2Service).deleteSystemTag(REGION, List.of("i-owned"), + AutoScalingService.GROUP_NAME_TAG, "group"); + } + + @Test + void deletedClassicBalancerDoesNotPreventRemainingCleanup() { + when(classic.deregisterInstances(REGION, "first", List.of("i-owned"))) + .thenThrow(new AwsException("LoadBalancerNotFound", "deleted", 400)); + + service.detachInstances(REGION, "group", List.of("i-owned"), true); + + verify(classic).deregisterInstances(REGION, "second", List.of("i-owned")); + assertEquals(List.of(retained), group.getInstances()); + } + + @Test + void rejectedStandbyTransitionDoesNotDeregisterAnything() { + owned.setLifecycleState("EnteringStandby"); + + assertThrows(AwsException.class, + () -> service.detachInstances(REGION, "group", List.of("i-owned"), true)); + + verifyNoInteractions(classic, targets, service.ec2Service); + assertEquals(List.of(owned, retained), group.getInstances()); + } + + @Test + void nonmemberDetachDoesNotTouchLoadBalancers() { + service.detachInstances(REGION, "group", List.of("i-other-group"), false); + + verifyNoInteractions(classic, targets, service.ec2Service); + assertEquals(List.of(owned, retained), group.getInstances()); + } + + @Test + void detachDeregistersOnlyActualMembersBeforeRemovingOwnership() { + group.setTargetGroupARNs(List.of("shared-target-group")); + + service.detachInstances(REGION, "group", List.of("i-owned", "i-other-group"), false); + + verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"), + argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId()))); + assertEquals(List.of(retained), group.getInstances()); + } + + @Test + void detachDeregistrationFailurePreservesMembershipForRetry() { + group.setTargetGroupARNs(List.of("shared-target-group")); + doThrow(new AwsException("Throttling", "retry", 503)).when(targets) + .deregisterTargets(eq(REGION), eq("shared-target-group"), anyList()); + + assertThrows(AwsException.class, + () -> service.detachInstances(REGION, "group", List.of("i-owned"), false)); + + assertEquals(List.of(owned, retained), group.getInstances()); + verifyNoInteractions(classic, service.ec2Service); + } + + @Test + void detachSkipsDeletedTargetGroupAndCleansTheRemainingGroup() { + group.setTargetGroupARNs(List.of("deleted-target-group", "shared-target-group")); + doThrow(new AwsException("TargetGroupNotFound", "deleted", 400)).when(targets) + .deregisterTargets(eq(REGION), eq("deleted-target-group"), anyList()); + + service.detachInstances(REGION, "group", List.of("i-owned"), false); + + verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"), anyList()); + verify(classic).deregisterInstances(REGION, "first", List.of("i-owned")); + assertEquals(List.of(retained), group.getInstances()); + } + + private static AsgInstance member(String id) { + AsgInstance member = new AsgInstance(); + member.setInstanceId(id); + member.setLifecycleState("InService"); + return member; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java index 27a953040e..714522e7b3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java @@ -44,6 +44,7 @@ import static org.mockito.Mockito.anyList; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.isNull; import static org.mockito.Mockito.mock; @@ -64,6 +65,122 @@ class AutoScalingReconcilerTest { return service; } + @ParameterizedTest + @MethodSource("targetCleanupFailures") + void failedTargetCleanupKeepsMembershipUntilRetry(String phase, RuntimeException failure) { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + ElbV2Service elbV2Service = mock(ElbV2Service.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service); + AutoScalingGroup asg = cleanupGroup(phase, ec2Service); + doThrow(failure).doNothing().when(elbV2Service) + .deregisterTargets(eq("us-east-1"), eq("owned-target-group"), anyList()); + + assertEquals(failure, assertThrows(RuntimeException.class, () -> reconciler.reconcile(asg))); + + assertEquals(List.of("i-cleanup"), asg.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + verify(asgService, never()).saveAutoScalingGroupIfPresent(asg); + reconciler.reconcile(asg); + assertEquals(List.of(), asg.getInstances()); + verify(elbV2Service, times(2)).deregisterTargets(eq("us-east-1"), eq("owned-target-group"), + argThat(targets -> targets.size() == 1 && "i-cleanup".equals(targets.getFirst().getId()))); + } + + static Stream targetCleanupFailures() { + return Stream.of("stale", "scale-in", "refresh").flatMap(phase -> Stream.of( + Arguments.of(phase, new AwsException("Throttling", "retry target cleanup", 503)), + Arguments.of(phase, new IllegalStateException("target storage write failed")))); + } + + @ParameterizedTest + @ValueSource(strings = {"stale", "scale-in", "refresh"}) + void deletedTargetGroupDoesNotPreventOwnedCleanup(String phase) { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + ElbV2Service elbV2Service = mock(ElbV2Service.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service); + AutoScalingGroup asg = cleanupGroup(phase, ec2Service); + asg.setTargetGroupARNs(List.of("deleted-target-group", "owned-target-group")); + doThrow(new AwsException("TargetGroupNotFound", "deleted", 400)).when(elbV2Service) + .deregisterTargets(eq("us-east-1"), eq("deleted-target-group"), anyList()); + + reconciler.reconcile(asg); + + assertEquals(List.of(), asg.getInstances()); + verify(elbV2Service).deregisterTargets(eq("us-east-1"), eq("owned-target-group"), anyList()); + } + + @ParameterizedTest + @MethodSource("targetCleanupFailures") + void failedClassicCleanupKeepsMembershipUntilRetry(String phase, RuntimeException failure) { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + ElbV2Service elbV2Service = mock(ElbV2Service.class); + ElbClassicService classic = mock(ElbClassicService.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler( + asgService, ec2Service, elbV2Service, classic, null); + AutoScalingGroup asg = cleanupGroup(phase, ec2Service); + asg.setLoadBalancerNames(List.of("first", "second")); + when(classic.deregisterInstances("us-east-1", "second", List.of("i-cleanup"))) + .thenThrow(failure).thenReturn(List.of()); + + assertEquals(failure, assertThrows(RuntimeException.class, () -> reconciler.reconcile(asg))); + + assertEquals(List.of("i-cleanup"), asg.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + verify(asgService, never()).saveAutoScalingGroupIfPresent(asg); + reconciler.reconcile(asg); + assertEquals(List.of(), asg.getInstances()); + verify(classic, times(2)).deregisterInstances("us-east-1", "first", List.of("i-cleanup")); + verify(classic, times(2)).deregisterInstances("us-east-1", "second", List.of("i-cleanup")); + } + + @ParameterizedTest + @ValueSource(strings = {"stale", "scale-in", "refresh"}) + void deletedClassicBalancerDoesNotPreventOwnedCleanup(String phase) { + AutoScalingService asgService = scalingService(); + Ec2Service ec2Service = mock(Ec2Service.class); + ElbV2Service elbV2Service = mock(ElbV2Service.class); + ElbClassicService classic = mock(ElbClassicService.class); + AutoScalingReconciler reconciler = new AutoScalingReconciler( + asgService, ec2Service, elbV2Service, classic, null); + AutoScalingGroup asg = cleanupGroup(phase, ec2Service); + asg.setLoadBalancerNames(List.of("deleted", "remaining")); + when(classic.deregisterInstances("us-east-1", "deleted", List.of("i-cleanup"))) + .thenThrow(new AwsException("LoadBalancerNotFound", "deleted", 400)); + + reconciler.reconcile(asg); + + assertEquals(List.of(), asg.getInstances()); + verify(classic).deregisterInstances("us-east-1", "remaining", List.of("i-cleanup")); + } + + private static AutoScalingGroup cleanupGroup(String phase, Ec2Service ec2Service) { + AutoScalingGroup asg = new AutoScalingGroup(); + asg.setRegion("us-east-1"); + asg.setAutoScalingGroupName("cleanup-asg"); + asg.setDesiredCapacity(0); + asg.setTargetGroupARNs(List.of("owned-target-group")); + asg.getInstances().add(instance("i-cleanup", switch (phase) { + case "stale" -> "Pending"; + case "refresh" -> "Terminating"; + default -> "InService"; + })); + Instance ec2Instance = new Instance(); + ec2Instance.setInstanceId("i-cleanup"); + ec2Instance.setState("stale".equals(phase) ? InstanceState.terminated() : InstanceState.running()); + Reservation reservation = new Reservation(); + reservation.setInstances(List.of(ec2Instance)); + when(ec2Service.describeInstances("us-east-1", List.of("i-cleanup"), null)) + .thenReturn(List.of(reservation)); + when(ec2Service.isInstanceContainerRunning("i-cleanup")).thenAnswer(invocation -> + "running".equals(ec2Instance.getState().getName())); + doAnswer(invocation -> { + ec2Instance.setState(InstanceState.terminated()); + return List.of(); + }).when(ec2Service).terminateInstances("us-east-1", List.of("i-cleanup")); + return asg; + } + @Test void pendingInstancesCountAsActiveCapacity() { AutoScalingGroup asg = new AutoScalingGroup(); @@ -572,32 +689,28 @@ class AutoScalingReconcilerTest { } @Test - void reconcileDeregistersTargetsThatAreNotActiveAsgInstances() { + void reconcilePreservesOtherGroupsAndManuallyRegisteredTargets() { AutoScalingService asgService = scalingService(); Ec2Service ec2Service = mock(Ec2Service.class); ElbV2Service elbV2Service = mock(ElbV2Service.class); AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service); - AutoScalingGroup asg = new AutoScalingGroup(); - asg.setRegion("us-east-1"); - asg.setAutoScalingGroupName("app-asg"); - asg.setDesiredCapacity(1); - asg.setTargetGroupARNs(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/app/123")); - asg.getInstances().add(instance("i-active", "InService")); - when(ec2Service.isInstanceContainerRunning("i-active")).thenReturn(true); - when(elbV2Service.describeTargetHealth(asg.getRegion(), asg.getTargetGroupARNs().getFirst(), List.of())) - .thenReturn(List.of(targetHealth("i-active"), targetHealth("i-stale"))); + String targetGroup = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/shared/123"; + when(elbV2Service.describeTargetHealth("us-east-1", targetGroup, List.of())) + .thenReturn(List.of(targetHealth("i-blue"), targetHealth("i-green"), targetHealth("i-manual"))); + for (String id : List.of("i-blue", "i-green")) { + AutoScalingGroup asg = new AutoScalingGroup(); + asg.setRegion("us-east-1"); + asg.setAutoScalingGroupName(id); + asg.setDesiredCapacity(1); + asg.setTargetGroupARNs(List.of(targetGroup)); + asg.getInstances().add(instance(id, "InService")); + when(ec2Service.isInstanceContainerRunning(id)).thenReturn(true); - reconciler.reconcile(asg); + reconciler.reconcile(asg); - ArgumentCaptor> targets = ArgumentCaptor.captor(); - verify(elbV2Service).deregisterTargets( - eq(asg.getRegion()), - eq(asg.getTargetGroupARNs().getFirst()), - targets.capture()); - assertEquals(1, targets.getValue().size()); - assertEquals("i-stale", targets.getValue().getFirst().getId()); - verify(asgService).saveAutoScalingGroupIfPresent(asg); - verify(ec2Service, never()).terminateInstances(asg.getRegion(), List.of("i-active")); + assertEquals(List.of(id), asg.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + } + verify(elbV2Service, never()).deregisterTargets(anyString(), anyString(), anyList()); } @Test @@ -657,6 +770,7 @@ class AutoScalingReconcilerTest { asg.setAutoScalingGroupName("app-asg"); asg.setDesiredCapacity(0); asg.getInstances().add(instance("i-dead", "Pending")); + asg.setTargetGroupARNs(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/shared/123")); Instance ec2Instance = new Instance(); ec2Instance.setInstanceId("i-dead"); @@ -668,6 +782,10 @@ class AutoScalingReconcilerTest { reconciler.reconcile(asg); + ArgumentCaptor> targets = ArgumentCaptor.captor(); + verify(elbV2Service).deregisterTargets(eq("us-east-1"), + eq(asg.getTargetGroupARNs().getFirst()), targets.capture()); + assertEquals(List.of("i-dead"), targets.getValue().stream().map(TargetDescription::getId).toList()); assertEquals(0, asg.getInstances().size()); verify(asgService).recordActivity( eq("us-east-1"), diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingStandbyStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingStandbyStorageTest.java index f806692701..fe0fee5433 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingStandbyStorageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingStandbyStorageTest.java @@ -48,6 +48,34 @@ class AutoScalingStandbyStorageTest { @TempDir Path directory; private final List factories = new ArrayList<>(); + @ParameterizedTest + @ValueSource(strings = {"persistent", "hybrid", "wal"}) + void failedTargetCleanupRetainsStoredMembershipAcrossRestart(String mode) throws IOException { + AutoScalingService service = storedService(mode); + storeGroup(service); + AutoScalingGroup stored = group(service); + stored.setDesiredCapacity(0); + stored.setTargetGroupARNs(List.of("owned-target-group")); + service.saveAutoScalingGroupIfPresent(stored); + Ec2Service ec2 = mock(Ec2Service.class); + ElbV2Service elb = mock(ElbV2Service.class); + IllegalStateException failure = new IllegalStateException("target storage write failed"); + doThrow(failure).when(elb).deregisterTargets(eq(REGION), eq("owned-target-group"), anyList()); + AutoScalingReconciler reconciler = new AutoScalingReconciler(service, ec2, elb); + + assertSame(failure, assertThrows(IllegalStateException.class, () -> reconciler.reconcile(stored))); + + service = restart(mode); + assertEquals(List.of("i-a", "i-b"), memberIds(service)); + reset(elb); + new AutoScalingReconciler(service, ec2, elb).reconcile(group(service)); + verify(elb).deregisterTargets(eq(REGION), eq("owned-target-group"), + argThat(targets -> targets.stream().map(target -> target.getId()).toList() + .equals(List.of("i-a", "i-b")))); + service = restart(mode); + assertTrue(memberIds(service).isEmpty()); + } + @ParameterizedTest @ValueSource(strings = {"persistent", "hybrid", "wal"}) void movesInterruptedByARestartFinishAfterIt(String mode) throws IOException { diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingTargetCleanupStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingTargetCleanupStorageTest.java new file mode 100644 index 0000000000..aab8365473 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingTargetCleanupStorageTest.java @@ -0,0 +1,166 @@ +package io.github.hectorvent.floci.services.autoscaling; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.core.storage.WalStorage; +import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance; +import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.elbv2.ElbV2HealthChecker; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; +import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; +import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; +import io.github.hectorvent.floci.testing.StorageFactories; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class AutoScalingTargetCleanupStorageTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String FIRST = "first-target-group"; + private static final String SECOND = "second-target-group"; + private static final TypeReference>> TARGETS = new TypeReference<>() {}; + + @TempDir Path directory; + private StorageFactory factory; + + @Test + void failedSecondTargetWriteRetainsDurableOwnershipAndRetriesWithoutRemovingForeignTargets() throws Exception { + factory = StorageFactories.open(directory, "wal", ACCOUNT); + AccountAwareStorageBackend> targets = targetStore(); + Map groups = new LinkedHashMap<>(); + groups.put(FIRST, targetGroup(FIRST)); + groups.put(SECOND, targetGroup(SECOND)); + targets.put(REGION, groups); + AutoScalingService scaling = scalingService(); + AutoScalingGroup group = new AutoScalingGroup(); + group.setRegion(REGION); + group.setAutoScalingGroupName("cleanup-group"); + group.setDesiredCapacity(0); + group.setTargetGroupARNs(List.of(FIRST, SECOND)); + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-owned"); + instance.setLifecycleState("InService"); + group.getInstances().add(instance); + scaling.groups.put(REGION + "::cleanup-group", group); + ElbV2Service elb = spy(elbService()); + doAnswer(invocation -> { + failNextTargetWrite(targets); + return invocation.callRealMethod(); + }).when(elb).deregisterTargets(eq(REGION), eq(SECOND), anyList()); + AutoScalingReconciler reconciler = new AutoScalingReconciler(scaling, mock(Ec2Service.class), elb); + + assertThrows(UncheckedIOException.class, () -> reconciler.reconcile(group)); + + // Close WAL writers without snapshot compaction, then replay only what the disk accepted. + closeWithoutCompaction(); + factory = StorageFactories.open(directory, "wal", ACCOUNT); + assertEquals(List.of("i-foreign"), targetIds(FIRST)); + assertEquals(List.of("i-owned", "i-foreign"), targetIds(SECOND)); + scaling = scalingService(); + AutoScalingGroup restored = scaling.requireGroup(REGION, "cleanup-group"); + assertEquals(List.of("i-owned"), restored.getInstances().stream().map(AsgInstance::getInstanceId).toList()); + new AutoScalingReconciler(scaling, mock(Ec2Service.class), elbService()).reconcile(restored); + factory.shutdownAll(); + factory = StorageFactories.open(directory, "wal", ACCOUNT); + + assertTrue(scalingService().requireGroup(REGION, "cleanup-group").getInstances().isEmpty()); + assertEquals(List.of("i-foreign"), targetIds(FIRST)); + assertEquals(List.of("i-foreign"), targetIds(SECOND)); + } + + private AutoScalingService scalingService() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, ACCOUNT); + service.storageFactory = factory; + service.initializeStorage(); + return service; + } + + private ElbV2Service elbService() throws Exception { + ElbV2Service service = new ElbV2Service(); + field(ElbV2Service.class, "storageFactory").set(service, factory); + field(ElbV2Service.class, "healthChecker").set(service, mock(ElbV2HealthChecker.class)); + Method initialize = ElbV2Service.class.getDeclaredMethod("initializeStorage"); + initialize.setAccessible(true); + initialize.invoke(service); + return service; + } + + private AccountAwareStorageBackend> targetStore() { + return factory.create("elbv2", "elbv2-target-groups.json", TARGETS); + } + + private List targetIds(String arn) { + return targetStore().get(REGION).orElseThrow().get(arn).getTargets().stream() + .map(TargetDescription::getId).toList(); + } + + private static TargetGroup targetGroup(String arn) { + TargetGroup group = new TargetGroup(); + group.setTargetGroupArn(arn); + group.setTargetType("instance"); + group.setPort(80); + List targets = new ArrayList<>(); + for (String id : List.of("i-owned", "i-foreign")) { + TargetDescription target = new TargetDescription(); + target.setId(id); + target.setPort(80); + targets.add(target); + } + group.setTargets(targets); + return group; + } + + private static void failNextTargetWrite(AccountAwareStorageBackend store) throws Exception { + Object wal = field(AccountAwareStorageBackend.class, "delegate").get(store); + Field writer = field(WalStorage.class, "walWriter"); + ((DataOutputStream) writer.get(wal)).close(); + writer.set(wal, new DataOutputStream(OutputStream.nullOutputStream()) { + @Override + public void flush() throws IOException { + throw new IOException("target WAL flush failed"); + } + }); + } + + private void closeWithoutCompaction() throws Exception { + List stores = (List) field(StorageFactory.class, "walBackends").get(factory); + for (Object store : stores) { + ((WalStorage) store).shutdown(); + } + factory = null; + } + + private static Field field(Class type, String name) throws NoSuchFieldException { + Field field = type.getDeclaredField(name); + field.setAccessible(true); + return field; + } + + @AfterEach + void closeStorage() { + if (factory != null) { + factory.shutdownAll(); + } + } +}