mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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 <AndreKurait@gmail.com> * 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 <AndreKurait@gmail.com> --------- Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
9f0856c691
commit
e714fd9594
8 files changed
+646
-92
No files matched your search
+81
@@ -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));
|
||||
}
|
||||
}
|
||||
+160
@@ -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;
|
||||
}
|
||||
}
|
||||
+138
-20
@@ -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<Arguments> 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<List<TargetDescription>> 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<List<TargetDescription>> 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"),
|
||||
|
||||
+28
@@ -48,6 +48,34 @@ class AutoScalingStandbyStorageTest {
|
||||
@TempDir Path directory;
|
||||
private final List<StorageFactory> 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 {
|
||||
|
||||
+166
@@ -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<Map<String, Map<String, TargetGroup>>> TARGETS = new TypeReference<>() {};
|
||||
|
||||
@TempDir Path directory;
|
||||
private StorageFactory factory;
|
||||
|
||||
@Test
|
||||
void failedSecondTargetWriteRetainsDurableOwnershipAndRetriesWithoutRemovingForeignTargets() throws Exception {
|
||||
factory = StorageFactories.open(directory, "wal", ACCOUNT);
|
||||
AccountAwareStorageBackend<Map<String, TargetGroup>> targets = targetStore();
|
||||
Map<String, TargetGroup> 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<Map<String, TargetGroup>> targetStore() {
|
||||
return factory.create("elbv2", "elbv2-target-groups.json", TARGETS);
|
||||
}
|
||||
|
||||
private List<String> 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<TargetDescription> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user