diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index f2aceac851..e1b79df19f 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -183,16 +183,16 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash. | `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 | +| `AttachLoadBalancers` | Attaches Classic Load Balancers by name 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. Floci runs no Classic data plane ([Classic ELB](elb-classic.md)) | +| `DetachLoadBalancers` | Detaches Classic Load Balancers and deregisters the group's instances from them, as AWS does; a load balancer already deleted is detached all the same. An EKS nodegroup's node stays registered with a load balancer another nodegroup's group still has attached | | `DescribeLoadBalancers` | Lists classic ELBs attached to a group | ### Traffic Sources | Operation | Notes | |---|---| -| `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 | +| `AttachTrafficSources` | Unified elb/elbv2/vpc-lattice attachment API; stored per identifier with its type. The group's `InService` instances are registered with an `elbv2` or `elb` source it adds, as with a target group or a Classic Load Balancer | +| `DetachTrafficSources` | Removes a traffic source by identifier, deregistering the group's instances from an `elbv2` or `elb` 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 c72c69c33a..c8e2f3f82b 100644 --- a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java +++ b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingReconciler.java @@ -302,7 +302,11 @@ public class AutoScalingReconciler { AutoScalingService.registerWithTargetGroups(elbV2Service, asg, AutoScalingService.attachedTargetGroups(asg), asgInst.getInstanceId(), returningFromStandby); - registerWithClassicLoadBalancers(asg, asgInst, returningFromStandby); + // Without this a Classic Load Balancer would stay empty, and a min_elb_capacity wait would never + // be satisfied. + AutoScalingService.registerWithClassicLoadBalancers(elbClassicService, asg, + AutoScalingService.attachedClassicLoadBalancers(asg), List.of(asgInst.getInstanceId()), + returningFromStandby); asgInst.setLifecycleState("InService"); changed = true; if (standbyActivityId != null) { @@ -881,36 +885,6 @@ public class AutoScalingReconciler { } - /** - * Registers a newly launched or returning instance with every Classic load balancer the group names. - * - *

An ASG attached through {@code LoadBalancerNames} feeds a Classic load balancer, not a - * target group, and the two lists are independent; a group can carry either or both. Without - * this the Classic load balancer would stay empty, and a {@code min_elb_capacity} wait would - * never be satisfied. - */ - private void registerWithClassicLoadBalancers(AutoScalingGroup asg, AsgInstance asgInst, - boolean returningFromStandby) { - if (elbClassicService == null) { - return; - } - for (String lbName : asg.getLoadBalancerNames()) { - try { - elbClassicService.registerInstances(asg.getRegion(), lbName, - List.of(asgInst.getInstanceId())); - LOG.debugv("ASG {0}: registered {1} with Classic ELB {2}", - asg.getAutoScalingGroupName(), asgInst.getInstanceId(), lbName); - } catch (Exception e) { - LOG.warnv(e, "ASG {0}: could not register {1} with Classic ELB {2}: {3}", - asg.getAutoScalingGroupName(), asgInst.getInstanceId(), lbName, e.getMessage()); - if (returningFromStandby && !(e instanceof AwsException aws - && "LoadBalancerNotFound".equals(aws.getErrorCode()))) { - throw e; - } - } - } - } - private LaunchSource resolveLaunchSource(AutoScalingGroup asg) { LaunchConfiguration lc = resolveLaunchConfiguration(asg); if (lc != null) { 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 bac9fd9fb0..ee169f3f1d 100644 --- a/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/floci/aws/services/autoscaling/AutoScalingService.java @@ -33,7 +33,9 @@ import java.time.temporal.ChronoUnit; import java.util.*; import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; import java.util.function.Consumer; +import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -631,8 +633,9 @@ public class AutoScalingService implements PassedRoleLookup { } if (asg.isEksManaged()) { // The instance is the cluster's node, which EKS owns and the cluster's other node groups share: it - // is not terminated, and stays in the target groups another of their groups has attached. + // is not terminated, and stays in the load balancers another of their groups has attached. deregisterFromUnsharedTargetGroups(asg, memberIds(asg), attachedTargetGroups(asg)); + deregisterFromUnsharedClassicLoadBalancers(asg, memberIds(asg), attachedClassicLoadBalancers(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(); @@ -1077,6 +1080,34 @@ public class AutoScalingService implements PassedRoleLookup { } } + /** + * Registers {@code instanceIds} with each of {@code loadBalancerNames}, Classic Load Balancers, in one call to + * each. A load balancer that refuses them is logged and skipped, unless {@code strict}: then only a load balancer + * that is gone is skipped, and any other failure is thrown. + */ + static void registerWithClassicLoadBalancers(ElbClassicService elb, AutoScalingGroup asg, + Collection loadBalancerNames, List instanceIds, + boolean strict) { + if (elb == null || instanceIds.isEmpty()) { + return; + } + String instances = String.join(", ", instanceIds); + for (String loadBalancer : loadBalancerNames) { + try { + elb.registerInstances(asg.getRegion(), loadBalancer, instanceIds); + LOG.debugv("ASG {0}: registered {1} with Classic ELB {2}", + asg.getAutoScalingGroupName(), instances, loadBalancer); + } catch (Exception e) { + LOG.warnv(e, "ASG {0}: could not register {1} with Classic ELB {2}: {3}", + asg.getAutoScalingGroupName(), instances, loadBalancer, e.getMessage()); + if (strict && !(e instanceof AwsException aws + && "LoadBalancerNotFound".equals(aws.getErrorCode()))) { + throw e; + } + } + } + } + /** * Runs {@code action} on each group in {@code region}, under the group's own lock, which guards its member list * against the reconciler. Callers hold the Region's lock, so no other change to which group holds an instance @@ -1118,9 +1149,21 @@ public class AutoScalingService implements PassedRoleLookup { } } + /** + * Deregisters {@code instanceIds} from every Classic Load Balancer attached to {@code asg}, elb sources included. + */ static void deregisterFromClassicLoadBalancers(ElbClassicService elb, AutoScalingGroup asg, List instanceIds) { - for (String loadBalancer : asg.getLoadBalancerNames()) { + deregisterFromClassicLoadBalancers(elb, asg, attachedClassicLoadBalancers(asg), instanceIds); + } + + /** As above, from {@code loadBalancerNames} rather than from every Classic Load Balancer the group has attached. */ + static void deregisterFromClassicLoadBalancers(ElbClassicService elb, AutoScalingGroup asg, + Collection loadBalancerNames, List instanceIds) { + if (elb == null || instanceIds.isEmpty()) { + return; + } + for (String loadBalancer : loadBalancerNames) { try { elb.deregisterInstances(asg.getRegion(), loadBalancer, instanceIds); } catch (AwsException e) { @@ -1160,12 +1203,13 @@ public class AutoScalingService implements PassedRoleLookup { InstanceRefresh refresh = activeInstanceRefresh(asg); if (!detached.isEmpty()) { if (asg.isEksManaged()) { - // The node stays in the target groups another group holding it has attached. + // The node stays in the load balancers another group holding it has attached. deregisterFromUnsharedTargetGroups(asg, detached, attachedTargetGroups(asg)); + deregisterFromUnsharedClassicLoadBalancers(asg, detached, attachedClassicLoadBalancers(asg)); } else { deregisterFromTargetGroups(elbV2Service, asg, detached); + deregisterFromClassicLoadBalancers(elbClassicService, 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); completeInstanceRefreshIfSettled(region, name, asg); @@ -1498,19 +1542,17 @@ public class AutoScalingService implements PassedRoleLookup { } public void attachLoadBalancers(String region, String name, List lbNames) { - AutoScalingGroup asg = requireGroup(region, name); - for (String lb : lbNames) { - if (!asg.getLoadBalancerNames().contains(lb)) { - asg.getLoadBalancerNames().add(lb); + changeAttachments(region, name, asg -> { + for (String lb : lbNames) { + if (!asg.getLoadBalancerNames().contains(lb)) { + asg.getLoadBalancerNames().add(lb); + } } - } - groups.put(asgKey(region, name), asg); + }); } public void detachLoadBalancers(String region, String name, List lbNames) { - AutoScalingGroup asg = requireGroup(region, name); - asg.getLoadBalancerNames().removeAll(lbNames); - groups.put(asgKey(region, name), asg); + changeAttachments(region, name, asg -> asg.getLoadBalancerNames().removeAll(lbNames)); } // ── Traffic sources ───────────────────────────────────────────────────────────── @@ -1557,9 +1599,18 @@ public class AutoScalingService implements PassedRoleLookup { /** The target groups attached to {@code asg}: as target groups, and as {@code elbv2} traffic sources. */ static Set attachedTargetGroups(AutoScalingGroup asg) { - Set attached = new LinkedHashSet<>(asg.getTargetGroupARNs()); + return attached(asg.getTargetGroupARNs(), asg, "elbv2"); + } + + /** The Classic Load Balancers attached to {@code asg}: by name, and as {@code elb} traffic sources. */ + static Set attachedClassicLoadBalancers(AutoScalingGroup asg) { + return attached(asg.getLoadBalancerNames(), asg, "elb"); + } + + private static Set attached(List listed, AutoScalingGroup asg, String sourceType) { + Set attached = new LinkedHashSet<>(listed); asg.getTrafficSourceTypeByIdentifier().forEach((identifier, type) -> { - if ("elbv2".equals(type)) { + if (sourceType.equals(type)) { attached.add(identifier); } }); @@ -1569,9 +1620,9 @@ public class AutoScalingService implements PassedRoleLookup { // ── EKS managed node groups ──────────────────────────────────────────────── // EKS keeps a group for each managed node group, under the name DescribeNodegroup reports. Floci runs one node // per cluster, which all of the cluster's node groups share, so their groups all hold that node, and the - // reconciler leaves them alone. The reconciler registers other groups' members with their target groups as - // they come into service; these groups' members are registered and deregistered here, as target groups are - // attached and detached. + // reconciler leaves them alone. The reconciler registers other groups' members with their target groups and + // Classic Load Balancers as they come into service; these groups' members are registered and deregistered here, + // as those are attached and detached. /** * Creates the group EKS keeps for a managed node group, unless a group of that name exists. It has no launch @@ -1597,7 +1648,8 @@ public class AutoScalingService implements PassedRoleLookup { /** * Puts {@code instance} in service in the EKS group {@code name}, unless it is a member already, and registers - * it with the group's target groups. Does nothing when there is no EKS group of that name. + * it with the group's target groups and Classic Load Balancers. Does nothing when there is no EKS group of that + * name. */ public void addEksManagedInstance(String region, String name, Instance instance) { String key = asgKey(region, name); @@ -1618,14 +1670,16 @@ public class AutoScalingService implements PassedRoleLookup { groups.put(key, asg); registerWithTargetGroups(elbV2Service, asg, attachedTargetGroups(asg), member.getInstanceId(), false); + registerWithClassicLoadBalancers(elbClassicService, asg, attachedClassicLoadBalancers(asg), + List.of(member.getInstanceId()), false); } } } /** * Deletes the EKS group {@code name}, if there is one, as {@link #deleteAutoScalingGroup} deletes it: its - * instance, which EKS owns, is not terminated, and leaves the group's target groups except those another group - * holding it has attached. Does nothing when there is no EKS group of that name. + * instance, which EKS owns, is not terminated, and leaves the group's target groups and Classic Load Balancers + * except those another group holding it has attached. Does nothing when there is no EKS group of that name. */ public void deleteEksManagedGroup(String region, String name) { synchronized (lockFor(region)) { @@ -1637,11 +1691,12 @@ public class AutoScalingService implements PassedRoleLookup { } /** - * Applies {@code change} to the target groups and traffic sources attached to the group {@code name}, and - * 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. + * Applies {@code change} to the target groups, Classic Load Balancers and traffic sources attached to the group + * {@code name}, and stores it. The group's members are deregistered from the target groups and Classic Load + * Balancers 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 or + * Classic Load Balancer that other group still has attached. */ private void changeAttachments(String region, String name, Consumer change) { String key = asgKey(region, name); @@ -1649,32 +1704,58 @@ public class AutoScalingService implements PassedRoleLookup { synchronized (lockFor(key)) { AutoScalingGroup current = requireGroup(region, name); List targetGroupsBefore = new ArrayList<>(current.getTargetGroupARNs()); + List loadBalancersBefore = new ArrayList<>(current.getLoadBalancerNames()); Map trafficSourcesBefore = new LinkedHashMap<>(current.getTrafficSourceTypeByIdentifier()); Set attachedBefore = attachedTargetGroups(current); + Set classicBefore = attachedClassicLoadBalancers(current); change.accept(current); Set attached = attachedTargetGroups(current); Set detached = new LinkedHashSet<>(attachedBefore); detached.removeAll(attached); attached.removeAll(attachedBefore); - // 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. + Set classicAttached = attachedClassicLoadBalancers(current); + Set classicDetached = new LinkedHashSet<>(classicBefore); + classicDetached.removeAll(classicAttached); + classicAttached.removeAll(classicBefore); + List members = memberIds(current); + List inService = current.getInstances().stream() + .filter(member -> "InService".equals(member.getLifecycleState())) + .map(AsgInstance::getInstanceId).filter(Objects::nonNull).toList(); + // The members leave the target groups and Classic Load Balancers the change detached before the change + // is stored, one load balancer at a time. When one refuses, the in-service members rejoin those they + // had already left and the group keeps them all attached, as it was, so the detach can be sent again. + // An ordinary group's instances are its own, so they leave every one it detached. + List rejoin = new ArrayList<>(); try { - 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)); + for (String targetGroup : detached) { + if (current.isEksManaged()) { + deregisterFromUnsharedTargetGroups(current, members, Set.of(targetGroup)); + } else if (!members.isEmpty()) { + deregisterFromTargetGroups(elbV2Service, current, List.of(targetGroup), members); + } + rejoin.add(() -> registerWithTargetGroups(elbV2Service, current, List.of(targetGroup), + inService, false)); + } + for (String loadBalancer : classicDetached) { + if (current.isEksManaged()) { + deregisterFromUnsharedClassicLoadBalancers(current, members, Set.of(loadBalancer)); + } else { + deregisterFromClassicLoadBalancers(elbClassicService, current, List.of(loadBalancer), + members); + } + rejoin.add(() -> registerWithClassicLoadBalancers(elbClassicService, current, + List.of(loadBalancer), inService, false)); } } catch (RuntimeException e) { + rejoin.forEach(Runnable::run); current.setTargetGroupARNs(targetGroupsBefore); + current.setLoadBalancerNames(loadBalancersBefore); current.setTrafficSourceTypeByIdentifier(trafficSourcesBefore); throw e; } groups.put(key, current); - List inService = current.getInstances().stream() - .filter(member -> "InService".equals(member.getLifecycleState())) - .map(AsgInstance::getInstanceId).filter(Objects::nonNull).toList(); registerWithTargetGroups(elbV2Service, current, attached, inService, false); + registerWithClassicLoadBalancers(elbClassicService, current, classicAttached, inService, false); } } } @@ -1706,19 +1787,38 @@ public class AutoScalingService implements PassedRoleLookup { */ private void deregisterFromUnsharedTargetGroups(AutoScalingGroup asg, List instanceIds, Set targetGroupArns) { - if (targetGroupArns.isEmpty()) { + forEachUnshared(asg, instanceIds, targetGroupArns, AutoScalingService::attachedTargetGroups, + (instanceId, leaving) -> deregisterFromTargetGroups(elbV2Service, asg, leaving, List.of(instanceId))); + } + + /** As {@link #deregisterFromUnsharedTargetGroups}, from Classic Load Balancers. */ + private void deregisterFromUnsharedClassicLoadBalancers(AutoScalingGroup asg, List instanceIds, + Set loadBalancerNames) { + forEachUnshared(asg, instanceIds, loadBalancerNames, AutoScalingService::attachedClassicLoadBalancers, + (instanceId, leaving) -> deregisterFromClassicLoadBalancers(elbClassicService, asg, leaving, + List.of(instanceId))); + } + + /** + * Calls {@code deregister} for each of {@code instanceIds} with those of {@code loadBalancers} that no other group + * holding the instance has attached, as {@code attachedOf} reads a group's. + */ + private void forEachUnshared(AutoScalingGroup asg, List instanceIds, Set loadBalancers, + Function> attachedOf, + BiConsumer> deregister) { + if (loadBalancers.isEmpty()) { return; } for (String instanceId : instanceIds) { - Set leaving = new LinkedHashSet<>(targetGroupArns); + Set leaving = new LinkedHashSet<>(loadBalancers); forEachGroupInRegion(asg.getRegion(), other -> { if (!asg.getAutoScalingGroupName().equals(other.getAutoScalingGroupName()) && containsInstance(other, instanceId)) { - leaving.removeAll(attachedTargetGroups(other)); + leaving.removeAll(attachedOf.apply(other)); } }); if (!leaving.isEmpty()) { - deregisterFromTargetGroups(elbV2Service, asg, leaving, List.of(instanceId)); + deregister.accept(instanceId, leaving); } } } diff --git a/src/main/java/io/floci/aws/services/eks/EksService.java b/src/main/java/io/floci/aws/services/eks/EksService.java index bcc1a013f3..89ab663772 100644 --- a/src/main/java/io/floci/aws/services/eks/EksService.java +++ b/src/main/java/io/floci/aws/services/eks/EksService.java @@ -2011,8 +2011,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun /** * Deletes the Auto Scaling group {@code nodeGroup} reports, which takes the cluster's node out of its target - * groups, except those another node group's group has attached. A failure is logged, so the node group, and - * the other node groups of a cluster being deleted, are deleted all the same. + * groups and Classic Load Balancers, except those another node group's group has attached. A failure is logged, + * so the node group, and the other node groups of a cluster being deleted, are deleted all the same. */ private void deleteNodeGroupAutoScalingGroup(String accountId, String region, Nodegroup nodeGroup) { String groupName = autoScalingGroupName(nodeGroup); diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingClassicLoadBalancerAttachmentTest.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingClassicLoadBalancerAttachmentTest.java new file mode 100644 index 0000000000..a03f4e5813 --- /dev/null +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingClassicLoadBalancerAttachmentTest.java @@ -0,0 +1,212 @@ +package io.floci.aws.services.autoscaling; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.autoscaling.model.AutoScalingGroup; +import io.floci.aws.services.elb.ElbClassicService; +import io.floci.aws.services.elbv2.ElbV2Service; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.FIRST; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.GROUP; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.IN_SERVICE; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.NODE; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.REGION; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.SECOND; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.STANDBY; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.groupsSharingTheNode; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.node; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.nodeGroupTags; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.ordinaryGroup; +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.eq; +import static org.mockito.Mockito.clearInvocations; +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.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Attaching a Classic Load Balancer 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 and as {@link AutoScalingTargetGroupAttachmentTest} checks + * for target groups: by name and as {@code elb} traffic sources, for an ordinary group and for EKS groups sharing + * their cluster's node. + */ +class AutoScalingClassicLoadBalancerAttachmentTest { + + private final ElbV2Service targets = mock(ElbV2Service.class); + private final ElbClassicService classic = mock(ElbClassicService.class); + private final AutoScalingService service = AutoScalingGroupFixtures.service(targets, classic); + private final AutoScalingGroup group = ordinaryGroup(service); + + AutoScalingClassicLoadBalancerAttachmentTest() { + group.setLoadBalancerNames(new ArrayList<>(List.of("lb-attached"))); + } + + @Test + void attachingAClassicLoadBalancerRegistersTheGroupsInServiceInstancesWithIt() { + service.attachLoadBalancers(REGION, GROUP, List.of("lb-attached", "lb-new")); + + // Only the load balancer the attach added, and only the instance in service: one in standby is not. + verify(classic).registerInstances(REGION, "lb-new", List.of(IN_SERVICE)); + verifyNoMoreInteractions(classic); + assertEquals(List.of("lb-attached", "lb-new"), group.getLoadBalancerNames()); + } + + @Test + void detachingAClassicLoadBalancerDeregistersTheGroupsInstancesFromIt() { + group.getLoadBalancerNames().add("lb-kept"); + + service.detachLoadBalancers(REGION, GROUP, List.of("lb-attached")); + + verify(classic).deregisterInstances(REGION, "lb-attached", List.of(IN_SERVICE, STANDBY)); + verifyNoMoreInteractions(classic); + assertEquals(List.of("lb-kept"), group.getLoadBalancerNames()); + } + + @Test + void anElbTrafficSourceRegistersAndDeregistersTheInstancesAsAClassicLoadBalancerDoes() { + service.attachTrafficSources(REGION, GROUP, List.of( + new AutoScalingService.TrafficSourceIdentifier("lb-source", "elb"))); + verify(classic).registerInstances(REGION, "lb-source", List.of(IN_SERVICE)); + + service.detachTrafficSources(REGION, GROUP, List.of( + new AutoScalingService.TrafficSourceIdentifier("lb-source", "elb"))); + + verify(classic).deregisterInstances(REGION, "lb-source", List.of(IN_SERVICE, STANDBY)); + verifyNoMoreInteractions(classic); + assertEquals(Map.of(), group.getTrafficSourceTypeByIdentifier()); + } + + /** A group deleted with its instances takes them out of its {@code elb} traffic sources too. */ + @Test + void aForceDeleteDeregistersTheInstancesFromAnElbTrafficSource() { + group.getTrafficSourceTypeByIdentifier().put("lb-source", "elb"); + + service.deleteAutoScalingGroup(REGION, GROUP, true); + + verify(classic).deregisterInstances(REGION, "lb-attached", List.of(IN_SERVICE, STANDBY)); + verify(classic).deregisterInstances(REGION, "lb-source", List.of(IN_SERVICE, STANDBY)); + } + + @Test + void aDetachTheLoadBalancerRefusesLeavesItAttachedSoTheDetachCanBeSentAgain() { + AwsException refusal = new AwsException("Throttling", "Rate exceeded", 400); + when(classic.deregisterInstances(REGION, "lb-attached", List.of(IN_SERVICE, STANDBY))) + .thenThrow(refusal).thenReturn(List.of()); + + assertSame(refusal, assertThrows(AwsException.class, + () -> service.detachLoadBalancers(REGION, GROUP, List.of("lb-attached")))); + assertEquals(List.of("lb-attached"), group.getLoadBalancerNames()); + + service.detachLoadBalancers(REGION, GROUP, List.of("lb-attached")); + + verify(classic, times(2)).deregisterInstances(REGION, "lb-attached", List.of(IN_SERVICE, STANDBY)); + assertEquals(List.of(), group.getLoadBalancerNames()); + } + + @Test + void aClassicLoadBalancerDeletedBeforeItsDetachIsDetached() { + when(classic.deregisterInstances(REGION, "lb-attached", List.of(IN_SERVICE, STANDBY))) + .thenThrow(new AwsException("LoadBalancerNotFound", + "There is no ACTIVE Load Balancer named 'lb-attached'", 400)); + + service.detachLoadBalancers(REGION, GROUP, List.of("lb-attached")); + + assertEquals(List.of(), group.getLoadBalancerNames()); + } + + /** + * A detach whose Classic Load Balancer refuses after the members left the target group it also named puts the + * in-service member back in that target group and leaves both attached, as they were, and sending the detach + * again finishes it. + */ + @Test + void aDetachWhoseClassicLoadBalancerRefusesPutsTheMembersBackInWhatTheyAlreadyLeft() { + group.getTrafficSourceTypeByIdentifier().put("tg-source", "elbv2"); + group.getTrafficSourceTypeByIdentifier().put("lb-source", "elb"); + AwsException refusal = new AwsException("Throttling", "Rate exceeded", 400); + when(classic.deregisterInstances(REGION, "lb-source", List.of(IN_SERVICE, STANDBY))) + .thenThrow(refusal).thenReturn(List.of()); + List both = List.of( + new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"), + new AutoScalingService.TrafficSourceIdentifier("lb-source", "elb")); + + assertSame(refusal, assertThrows(AwsException.class, + () -> service.detachTrafficSources(REGION, GROUP, both))); + + assertEquals(Map.of("tg-source", "elbv2", "lb-source", "elb"), group.getTrafficSourceTypeByIdentifier()); + InOrder order = inOrder(targets); + order.verify(targets).deregisterTargets(eq(REGION), eq("tg-source"), exactlyTargets(IN_SERVICE, STANDBY)); + order.verify(targets).registerTargets(eq(REGION), eq("tg-source"), onlyTarget(IN_SERVICE)); + + service.detachTrafficSources(REGION, GROUP, both); + + verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-source"), exactlyTargets(IN_SERVICE, STANDBY)); + verify(classic, times(2)).deregisterInstances(REGION, "lb-source", List.of(IN_SERVICE, STANDBY)); + assertEquals(Map.of(), group.getTrafficSourceTypeByIdentifier()); + } + + /** The groups of a cluster's node groups share its node, which stays in a load balancer either has attached. */ + @Test + void detachingAClassicLoadBalancerLeavesTheSharedNodeInItWhileAnotherEksGroupHasItAttached() { + groupsSharingTheNode(service); + service.attachLoadBalancers(REGION, FIRST, List.of("lb-shared")); + service.attachTrafficSources(REGION, SECOND, List.of( + new AutoScalingService.TrafficSourceIdentifier("lb-shared", "elb"))); + verify(classic, times(2)).registerInstances(REGION, "lb-shared", List.of(NODE)); + clearInvocations(classic); + + service.detachLoadBalancers(REGION, FIRST, List.of("lb-shared")); + + verifyNoInteractions(classic); + + service.detachTrafficSources(REGION, SECOND, List.of( + new AutoScalingService.TrafficSourceIdentifier("lb-shared", "elb"))); + + verify(classic).deregisterInstances(REGION, "lb-shared", List.of(NODE)); + verifyNoMoreInteractions(classic); + } + + /** A node that joins an EKS group after a Classic Load Balancer was attached to it is registered with it. */ + @Test + void aNodeJoiningAnEksGroupIsRegisteredWithItsClassicLoadBalancers() { + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); + service.attachLoadBalancers(REGION, FIRST, List.of("lb-web")); + verifyNoInteractions(classic); + + service.addEksManagedInstance(REGION, FIRST, node()); + + verify(classic).registerInstances(REGION, "lb-web", List.of(NODE)); + } + + /** Deleting an EKS group, or detaching the node from it, leaves the node in what the other group has attached. */ + @Test + void deletingOrDetachingFromAnEksGroupLeavesTheNodeInTheLoadBalancersTheOtherGroupHasAttached() { + groupsSharingTheNode(service); + service.attachLoadBalancers(REGION, FIRST, List.of("lb-shared", "lb-first")); + service.attachLoadBalancers(REGION, SECOND, List.of("lb-shared")); + clearInvocations(classic); + + service.detachInstances(REGION, FIRST, List.of(NODE), false); + + verify(classic).deregisterInstances(REGION, "lb-first", List.of(NODE)); + verifyNoMoreInteractions(classic); + + service.deleteEksManagedGroup(REGION, SECOND); + + verify(classic).deregisterInstances(REGION, "lb-shared", List.of(NODE)); + verifyNoMoreInteractions(classic); + } +} diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingEksManagedGroupTest.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingEksManagedGroupTest.java index 349f7c42c6..06bf648d50 100644 --- a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingEksManagedGroupTest.java +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingEksManagedGroupTest.java @@ -1,13 +1,10 @@ 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.autoscaling.model.InstanceRefresh; import io.floci.aws.services.ec2.Ec2Service; -import io.floci.aws.services.ec2.model.Instance; -import io.floci.aws.services.ec2.model.Placement; import io.floci.aws.services.ec2.model.Subnet; import io.floci.aws.services.elbv2.ElbV2Service; import io.floci.aws.services.elbv2.model.TargetDescription; @@ -25,6 +22,13 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.FIRST; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.NODE; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.REGION; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.SECOND; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.groupsSharingTheNode; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.node; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.nodeGroupTags; import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -50,17 +54,11 @@ import static org.mockito.Mockito.when; */ class AutoScalingEksManagedGroupTest { - private static final String REGION = "us-east-1"; - private static final String FIRST = "eks-workers-1a2b3c4d"; - private static final String SECOND = "eks-batch-5e6f7a8b"; - private static final String NODE = "i-0123456789abcdef0"; - private final ElbV2Service targets = mock(ElbV2Service.class); private final Ec2Service ec2 = mock(Ec2Service.class); - private final AutoScalingService service = new AutoScalingService(targets, null); + private final AutoScalingService service = AutoScalingGroupFixtures.service(targets, null); AutoScalingEksManagedGroupTest() { - service.regionResolver = new RegionResolver(REGION, "000000000000"); service.ec2Service = ec2; } @@ -71,7 +69,7 @@ class AutoScalingEksManagedGroupTest { subnet.setAvailabilityZone("us-east-1a"); when(ec2.describeSubnets(REGION, List.of("subnet-a", "subnet-unknown"), null)).thenReturn(List.of(subnet)); - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of("subnet-a", "subnet-unknown"), tags("workers")); + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of("subnet-a", "subnet-unknown"), nodeGroupTags("workers")); AutoScalingGroup group = service.requireGroup(REGION, FIRST); assertTrue(group.isEksManaged()); @@ -82,7 +80,7 @@ class AutoScalingEksManagedGroupTest { assertEquals(2, group.getDesiredCapacity()); assertEquals(List.of("us-east-1a"), group.getAvailabilityZones()); assertEquals(List.of("subnet-a", "subnet-unknown"), group.getSubnetIds()); - assertEquals(tags("workers"), group.getTags()); + assertEquals(nodeGroupTags("workers"), group.getTags()); assertEquals(Map.of("eks:cluster-name", true, "eks:nodegroup-name", true, "k8s.io/cluster-autoscaler/enabled", true, "k8s.io/cluster-autoscaler/shop", true), group.getTagPropagateAtLaunch()); @@ -100,12 +98,12 @@ class AutoScalingEksManagedGroupTest { assertEquals(1, group.getMinSize()); assertEquals(3, group.getMaxSize()); assertEquals(2, group.getDesiredCapacity()); - assertEquals(tags("workers"), group.getTags()); + assertEquals(nodeGroupTags("workers"), group.getTags()); } @Test void anAddedNodeIsInServiceAndRegisteredWithTheTargetGroupsAlreadyAttached() { - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers")); + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-attached")); service.attachTrafficSources(REGION, FIRST, List.of( new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"), @@ -131,7 +129,7 @@ class AutoScalingEksManagedGroupTest { @Test void attachingAndDetachingTargetGroupsRegistersAndDeregistersTheNode() { - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers")); + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); service.addEksManagedInstance(REGION, FIRST, node()); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a")); @@ -158,7 +156,7 @@ class AutoScalingEksManagedGroupTest { @Test void aDetachElbV2RefusesLeavesTheTargetGroupAttachedSoTheDetachCanBeSentAgain() { - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers")); + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); service.addEksManagedInstance(REGION, FIRST, node()); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a")); service.attachTrafficSources(REGION, FIRST, List.of( @@ -186,7 +184,7 @@ class AutoScalingEksManagedGroupTest { @Test void detachingATargetGroupLeavesTheSharedNodeInItWhileAnotherGroupHasItAttached() { - groupsSharingTheNode(); + groupsSharingTheNode(service); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared")); service.attachTrafficSources(REGION, SECOND, List.of( new AutoScalingService.TrafficSourceIdentifier("tg-shared", "elbv2"))); @@ -205,7 +203,7 @@ class AutoScalingEksManagedGroupTest { @Test void detachingTheNodeLeavesTheTargetGroupsAnotherGroupHoldingItHasAttached() { - groupsSharingTheNode(); + groupsSharingTheNode(service); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared")); service.attachTrafficSources(REGION, FIRST, List.of( new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"))); @@ -229,7 +227,7 @@ class AutoScalingEksManagedGroupTest { @ValueSource(booleans = {false, true}) void deletingAGroupLeavesTheSharedNodeInTheTargetGroupsAnotherGroupHoldsAndTerminatesNothing( boolean throughAutoScaling) { - groupsSharingTheNode(); + groupsSharingTheNode(service); service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared")); service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared")); clearInvocations(targets); @@ -256,7 +254,7 @@ class AutoScalingEksManagedGroupTest { @Test void attachingWhileAnotherGroupDetachesTheSameTargetGroupLeavesTheSharedNodeRegistered() throws Exception { - groupsSharingTheNode(); + groupsSharingTheNode(service); // The target group's registered targets, as ELB keeps them. Set registered = ConcurrentHashMap.newKeySet(); CountDownLatch deregistering = new CountDownLatch(1); @@ -300,7 +298,7 @@ class AutoScalingEksManagedGroupTest { @Test void operationsThatWouldMoveOrReplaceTheNodeAreRefusedAndTheRestAreNot() { - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers")); + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); service.addEksManagedInstance(REGION, FIRST, node()); assertRefused(() -> service.terminateInstanceInAutoScalingGroup(REGION, NODE, false)); @@ -347,31 +345,7 @@ class AutoScalingEksManagedGroupTest { } } - /** FIRST and SECOND, the groups of two node groups of one cluster, both holding its node. */ - private void groupsSharingTheNode() { - service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers")); - service.createEksManagedGroup(REGION, SECOND, 1, 1, 1, List.of(), tags("batch")); - service.addEksManagedInstance(REGION, FIRST, node()); - service.addEksManagedInstance(REGION, SECOND, node()); - } - - private static Map tags(String nodegroupName) { - return Map.of( - "eks:cluster-name", "shop", - "eks:nodegroup-name", nodegroupName, - "k8s.io/cluster-autoscaler/enabled", "true", - "k8s.io/cluster-autoscaler/shop", "owned"); - } - private List memberIds(String group) { return service.requireGroup(REGION, group).getInstances().stream().map(AsgInstance::getInstanceId).toList(); } - - private static Instance node() { - Instance node = new Instance(); - node.setInstanceId(NODE); - node.setInstanceType("m5.large"); - node.setPlacement(new Placement("us-east-1b")); - return node; - } } diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingGroupFixtures.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingGroupFixtures.java new file mode 100644 index 0000000000..1d3ab9e754 --- /dev/null +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingGroupFixtures.java @@ -0,0 +1,88 @@ +package io.floci.aws.services.autoscaling; + +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.ec2.model.Instance; +import io.floci.aws.services.ec2.model.Placement; +import io.floci.aws.services.elb.ElbClassicService; +import io.floci.aws.services.elbv2.ElbV2Service; + +import java.util.List; +import java.util.Map; + +import static org.mockito.Mockito.mock; + +/** + * The groups the load balancer attachment tests share: an ordinary group with one member in service and one in + * standby, and the groups of two node groups of one EKS cluster, which both hold the cluster's one node, as Floci runs + * a cluster. + */ +final class AutoScalingGroupFixtures { + + static final String REGION = "us-east-1"; + static final String GROUP = "web"; + static final String IN_SERVICE = "i-0a1b2c3d4e5f60001"; + static final String STANDBY = "i-0a1b2c3d4e5f60002"; + static final String FIRST = "eks-workers-1a2b3c4d"; + static final String SECOND = "eks-batch-5e6f7a8b"; + static final String NODE = "i-0123456789abcdef0"; + + private AutoScalingGroupFixtures() { + } + + /** A service in {@link #REGION} on the given load balancer services, with EC2 mocked. */ + static AutoScalingService service(ElbV2Service targets, ElbClassicService classic) { + AutoScalingService service = new AutoScalingService(targets, classic); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.ec2Service = mock(Ec2Service.class); + return service; + } + + /** + * {@link #GROUP}, an ordinary group of {@link #REGION} holding {@link #IN_SERVICE} in service and {@link #STANDBY} + * in standby, stored in {@code service}. + */ + static AutoScalingGroup ordinaryGroup(AutoScalingService service) { + AutoScalingGroup group = new AutoScalingGroup(); + group.setAutoScalingGroupName(GROUP); + group.setRegion(REGION); + group.getInstances().addAll(List.of(member(IN_SERVICE, "InService"), member(STANDBY, "Standby"))); + service.groups.put(REGION + "::" + GROUP, group); + return group; + } + + static AsgInstance member(String id, String state) { + AsgInstance member = new AsgInstance(); + member.setInstanceId(id); + member.setLifecycleState(state); + return member; + } + + /** {@link #FIRST} and {@link #SECOND}, the groups of two node groups of one cluster, both holding its node. */ + static void groupsSharingTheNode(AutoScalingService service) { + service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), nodeGroupTags("workers")); + service.createEksManagedGroup(REGION, SECOND, 1, 1, 1, List.of(), nodeGroupTags("batch")); + service.addEksManagedInstance(REGION, FIRST, node()); + service.addEksManagedInstance(REGION, SECOND, node()); + } + + /** The tags EKS gives the group of the node group {@code nodegroupName} of the cluster {@code shop}. */ + static Map nodeGroupTags(String nodegroupName) { + return Map.of( + "eks:cluster-name", "shop", + "eks:nodegroup-name", nodegroupName, + "k8s.io/cluster-autoscaler/enabled", "true", + "k8s.io/cluster-autoscaler/shop", "owned"); + } + + /** {@link #NODE}, the cluster's node, as EKS adds it to a node group's group. */ + static Instance node() { + Instance node = new Instance(); + node.setInstanceId(NODE); + node.setInstanceType("m5.large"); + node.setPlacement(new Placement("us-east-1b")); + return node; + } +} 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 dcd05f30a9..33f48b7615 100644 --- a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingStandbyTest.java @@ -807,10 +807,9 @@ class AutoScalingStandbyTest { doThrow(failure).doNothing().when(elbV2).registerTargets(eq(REGION), eq(TARGET_GROUP), anyList()); } - // Target groups are registered through AutoScalingService.registerWithTargetGroups, which logs there. - List records = LogCapture.capture( - classicFailure ? AutoScalingReconciler.class : AutoScalingService.class, - () -> reconciler.reconcile(group())); + // Both are registered through AutoScalingService's registerWithTargetGroups and + // registerWithClassicLoadBalancers, which log there. + List records = LogCapture.capture(AutoScalingService.class, () -> reconciler.reconcile(group())); List warnings = records.stream() .filter(record -> record.getLevel().intValue() == Level.WARNING.intValue()).toList(); diff --git a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java index b0f2e6d781..d473589efd 100644 --- a/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java +++ b/src/test/java/io/floci/aws/services/autoscaling/AutoScalingTargetGroupAttachmentTest.java @@ -1,10 +1,7 @@ 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; @@ -16,6 +13,11 @@ import java.util.Arrays; import java.util.List; import java.util.Map; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.GROUP; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.IN_SERVICE; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.REGION; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.STANDBY; +import static io.floci.aws.services.autoscaling.AutoScalingGroupFixtures.ordinaryGroup; 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; @@ -39,23 +41,12 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ 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(); + private final AutoScalingService service = AutoScalingGroupFixtures.service(targets, mock(ElbClassicService.class)); + private final AutoScalingGroup group = ordinaryGroup(service); 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 @@ -149,11 +140,4 @@ class AutoScalingTargetGroupAttachmentTest { 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; - } }