feat(eks): give each managed node group the Auto Scaling group it reports (#8432)

* refactor(autoscaling): register target group members next to their deregistration
* feat(autoscaling): keep the groups EKS manages for its node groups
* feat(eks): give each managed node group the Auto Scaling group it reports
* refactor(autoscaling): build groups and read a Region's groups through shared helpers
* fix(autoscaling): change an EKS group's node and target groups under the Region's lock
* fix(autoscaling): refuse moving or replacing an EKS group's node
* fix(eks): create a node group's Auto Scaling group once, and delete the others past a failure
* docs(eks): what an EKS node group's Auto Scaling group allows, and what ordinary groups register
* fix(autoscaling): keep an EKS group's target group attached when ELBv2 refuses to deregister its node
* test(eks): build the node group Auto Scaling tests' EKS requests with one EksRequests helper
* test(eks): build the access entry, add-on, Pod Identity and Region scoping tests' EKS requests with EksRequests
* test: read a target group's registered targets with one AlbFixtures.targetIds
* test(autoscaling): match a single deregistered or registered target with one onlyTarget matcher
* test(autoscaling): delete a group sharing the node through EKS and through Auto Scaling in one test
* perf(eks): read only the registering node's cluster when adding it to its node groups' Auto Scaling groups
* docs(autoscaling): say an EKS group's node is registered with an elbv2 traffic source
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-15 09:06:23 -04:00
1 parent e901eb27b2
commit 74a9ea76d5
24 files changed
+1686 -272

No files matched your search

@@ -22,7 +22,6 @@ import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.elb.ElbClassicService;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.services.ssm.SsmCommandService;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.PostConstruct;
@@ -140,6 +139,11 @@ public class AutoScalingReconciler {
}
public void reconcile(AutoScalingGroup asg) {
// EKS owns the capacity of a managed node group's group. Its instance is the cluster's node, which
// Auto Scaling never launches, terminates or replaces.
if (asg.isEksManaged()) {
return;
}
asgService.reconcileIfPresent(asg, () -> {
settleStandbyMoves(asg);
removeTerminatingInstances(asg);
@@ -295,7 +299,8 @@ public class AutoScalingReconciler {
if ("running".equals(ec2State)) {
String standbyActivityId = asgInst.getStandbyActivityId();
boolean returningFromStandby = standbyActivityId != null;
registerWithTargetGroups(asg, asgInst, returningFromStandby);
AutoScalingService.registerWithTargetGroups(elbV2Service, asg, asg.getTargetGroupARNs(),
asgInst.getInstanceId(), returningFromStandby);
registerWithClassicLoadBalancers(asg, asgInst, returningFromStandby);
asgInst.setLifecycleState("InService");
changed = true;
@@ -905,26 +910,6 @@ public class AutoScalingReconciler {
}
}
private void registerWithTargetGroups(AutoScalingGroup asg, AsgInstance asgInst,
boolean returningFromStandby) {
for (String tgArn : asg.getTargetGroupARNs()) {
try {
TargetDescription td = new TargetDescription();
td.setId(asgInst.getInstanceId());
elbV2Service.registerTargets(asg.getRegion(), tgArn, List.of(td));
LOG.debugv("ASG {0}: registered {1} with TG {2}",
asg.getAutoScalingGroupName(), asgInst.getInstanceId(), tgArn);
} catch (Exception e) {
LOG.warnv(e, "ASG {0}: could not register {1} with TG {2}: {3}",
asg.getAutoScalingGroupName(), asgInst.getInstanceId(), tgArn, e.getMessage());
if (returningFromStandby && !(e instanceof AwsException aws
&& "TargetGroupNotFound".equals(aws.getErrorCode()))) {
throw e;
}
}
}
}
private LaunchSource resolveLaunchSource(AutoScalingGroup asg) {
LaunchConfiguration lc = resolveLaunchConfiguration(asg);
if (lc != null) {
@@ -409,26 +409,43 @@ public class AutoScalingService implements PassedRoleLookup {
optionalFields != null ? optionalFields.desiredCapacityType() : null,
mixedInstancesPolicy);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setAutoScalingGroupName(name);
asg.setAutoScalingGroupArn(
AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(),
"autoScalingGroup:" + name).toString());
AutoScalingGroup asg = newGroup(region, name, minSize, maxSize, desiredCapacity,
resolveAvailabilityZones(region, availabilityZones, subnetIds), subnetIds, terminationPolicies,
tags, tagPropagateAtLaunch);
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
asg.setMinSize(minSize);
asg.setMaxSize(maxSize);
asg.setDesiredCapacity(desiredCapacity);
asg.setDefaultCooldown(defaultCooldown > 0 ? defaultCooldown : 300);
asg.setAvailabilityZones(new ArrayList<>(resolveAvailabilityZones(region, availabilityZones, subnetIds)));
asg.setSubnetIds(subnetIds != null ? new ArrayList<>(subnetIds) : new ArrayList<>());
asg.setTargetGroupARNs(targetGroupArns != null ? new ArrayList<>(targetGroupArns) : new ArrayList<>());
asg.setLoadBalancerNames(lbNames != null ? new ArrayList<>(lbNames) : new ArrayList<>());
asg.setHealthCheckType(healthCheckType != null ? healthCheckType : "EC2");
asg.setHealthCheckGracePeriod(healthCheckGracePeriod);
if (optionalFields != null) {
optionalFields.applyToNewGroup(asg);
}
groups.put(key, asg);
return asg;
}
/**
* A new group {@code name} in {@code region} with what every group is created with: its sizes, zones, subnets,
* termination policies, {@code Default} when none are given, and tags. The launch source is the caller's.
*/
private AutoScalingGroup newGroup(String region, String name, int minSize, int maxSize, int desiredCapacity,
List<String> availabilityZones, List<String> subnetIds,
List<String> terminationPolicies, Map<String, String> tags,
Map<String, Boolean> tagPropagateAtLaunch) {
AutoScalingGroup asg = new AutoScalingGroup();
asg.setAutoScalingGroupName(name);
asg.setAutoScalingGroupArn(AwsArnUtils.Arn.of("autoscaling", region, regionResolver.getAccountId(),
"autoScalingGroup:" + name).toString());
asg.setMinSize(minSize);
asg.setMaxSize(maxSize);
asg.setDesiredCapacity(desiredCapacity);
asg.setAvailabilityZones(new ArrayList<>(availabilityZones));
asg.setSubnetIds(subnetIds != null ? new ArrayList<>(subnetIds) : new ArrayList<>());
asg.setTerminationPolicies(terminationPolicies != null ? new ArrayList<>(terminationPolicies) : List.of("Default"));
asg.setCreatedTime(Instant.now());
asg.setRegion(region);
@@ -438,10 +455,6 @@ public class AutoScalingService implements PassedRoleLookup {
if (tagPropagateAtLaunch != null) {
asg.getTagPropagateAtLaunch().putAll(tagPropagateAtLaunch);
}
if (optionalFields != null) {
optionalFields.applyToNewGroup(asg);
}
groups.put(key, asg);
return asg;
}
@@ -523,18 +536,31 @@ public class AutoScalingService implements PassedRoleLookup {
private List<String> resolveAvailabilityZones(String region, List<String> availabilityZones, List<String> subnetIds) {
if ((availabilityZones == null || availabilityZones.isEmpty()) && subnetIds != null && !subnetIds.isEmpty()) {
List<Subnet> subnets = ec2Service.describeSubnets(region, subnetIds, null);
Set<String> foundIds = subnets.stream().map(Subnet::getSubnetId).collect(Collectors.toSet());
Map<String, String> zones = subnetZones(region, subnetIds);
for (String subnetId : subnetIds) {
if (!foundIds.contains(subnetId)) {
if (!zones.containsKey(subnetId)) {
throw new AwsException("ValidationError", "The subnet ID '" + subnetId + "' does not exist", 400);
}
}
return subnets.stream().map(Subnet::getAvailabilityZone).distinct().toList();
return zones.values().stream().distinct().toList();
}
return availabilityZones != null ? availabilityZones : List.of();
}
/**
* The zone of each subnet EC2 has among {@code subnetIds}, by subnet ID, in the order EC2 lists them. An ID EC2
* does not have is left out.
*/
private Map<String, String> subnetZones(String region, List<String> subnetIds) {
Map<String, String> zones = new LinkedHashMap<>();
if (!subnetIds.isEmpty()) {
for (Subnet subnet : ec2Service.describeSubnets(region, subnetIds, null)) {
zones.put(subnet.getSubnetId(), subnet.getAvailabilityZone());
}
}
return zones;
}
/**
* EnableMetricsCollection: {@code Granularity} is required and 1Minute is its only valid value.
* Naming no metrics enables all of them.
@@ -588,6 +614,10 @@ public class AutoScalingService implements PassedRoleLookup {
}
public void deleteAutoScalingGroup(String region, String name, boolean forceDelete) {
withRegionLockForEksGroup(region, name, () -> deleteGroup(region, name, forceDelete));
}
private void deleteGroup(String region, String name, boolean forceDelete) {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
@@ -599,7 +629,11 @@ public class AutoScalingService implements PassedRoleLookup {
"Auto Scaling group '" + name + "' has " + active.size()
+ " instance(s). Set ForceDelete=true to delete anyway.", 400);
}
if (forceDelete && ec2Service != null && !active.isEmpty()) {
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.
deregisterFromUnsharedTargetGroups(asg, memberIds(asg), attachedTargetGroups(asg));
} else if (forceDelete && ec2Service != null && !active.isEmpty()) {
active.stream()
.map(AsgInstance::getInstanceId)
.filter(Objects::nonNull)
@@ -870,10 +904,16 @@ public class AutoScalingService implements PassedRoleLookup {
throw new AwsException("ValidationError",
"HealthStatus must be Healthy or Unhealthy.", 400);
}
updateGroupOfInstance(region, instanceId, asg -> asg.getInstances().stream()
.filter(instance -> instanceId.equals(instance.getInstanceId()))
.findFirst()
.ifPresent(instance -> instance.setHealthStatus(healthStatus)));
updateGroupOfInstance(region, instanceId, asg -> {
// Auto Scaling replaces an unhealthy instance.
if ("Unhealthy".equals(healthStatus)) {
refuseForEksGroup(asg);
}
asg.getInstances().stream()
.filter(instance -> instanceId.equals(instance.getInstanceId()))
.findFirst()
.ifPresent(instance -> instance.setHealthStatus(healthStatus));
});
}
/** Applies {@code update} to the group holding {@code instanceId}, under that group's lock. */
@@ -896,6 +936,19 @@ public class AutoScalingService implements PassedRoleLookup {
}
}
/**
* Refuses an operation that would launch, terminate, replace or move an instance of {@code asg} when it is an
* EKS group: its instance is the cluster's node, which Floci runs once for all of the cluster's node groups,
* and which the reconciler never acts on. DetachInstances and changes to the group's settings stay allowed.
*/
private static void refuseForEksGroup(AutoScalingGroup asg) {
if (asg.isEksManaged()) {
throw new AwsException("ValidationError", "Auto Scaling group '" + asg.getAutoScalingGroupName()
+ "' is managed by Amazon EKS for a node group. Its instance is the cluster's node,"
+ " which the cluster's node groups share.", 400);
}
}
private static AwsException instanceNotFound(String instanceId) {
return new AwsException("ValidationError",
"Instance '" + instanceId + "' not found in any Auto Scaling group.", 400);
@@ -929,22 +982,17 @@ public class AutoScalingService implements PassedRoleLookup {
synchronized (lockFor(region)) {
synchronized (lockFor(asgKey(region, name))) {
AutoScalingGroup asg = requireGroup(region, name);
refuseForEksGroup(asg);
// An instance belongs to one group at a time, so the whole batch fails before any tag changes.
List<String> conflicts = new ArrayList<>();
for (AutoScalingGroup group : groups.values()) {
if (group == null || !region.equals(group.getRegion())) {
continue;
}
// Under the group's own lock, which guards its member list against the reconciler.
synchronized (lockFor(asgKey(region, group.getAutoScalingGroupName()))) {
for (AsgInstance member : group.getInstances()) {
if (requested.contains(member.getInstanceId())) {
conflicts.add("The Instance: " + member.getInstanceId()
+ " is already part of AutoScalingGroup:" + group.getAutoScalingGroupName());
}
forEachGroupInRegion(region, group -> {
for (AsgInstance member : group.getInstances()) {
if (requested.contains(member.getInstanceId())) {
conflicts.add("The Instance: " + member.getInstanceId()
+ " is already part of AutoScalingGroup:" + group.getAutoScalingGroupName());
}
}
}
});
if (!conflicts.isEmpty()) {
throw new AwsException("ValidationError", conflicts.toString(), 400);
}
@@ -982,13 +1030,60 @@ public class AutoScalingService implements PassedRoleLookup {
}
}
/**
* Registers {@code instanceId} with each of {@code targetGroupArns}. A target group that refuses it is logged
* and skipped, unless {@code strict}: then only a target group that is gone is skipped, and any other failure
* is thrown.
*/
static void registerWithTargetGroups(ElbV2Service elb, AutoScalingGroup asg, Collection<String> targetGroupArns,
String instanceId, boolean strict) {
for (String tgArn : targetGroupArns) {
try {
TargetDescription td = new TargetDescription();
td.setId(instanceId);
elb.registerTargets(asg.getRegion(), tgArn, List.of(td));
LOG.debugv("ASG {0}: registered {1} with TG {2}",
asg.getAutoScalingGroupName(), instanceId, tgArn);
} catch (Exception e) {
LOG.warnv(e, "ASG {0}: could not register {1} with TG {2}: {3}",
asg.getAutoScalingGroupName(), instanceId, tgArn, e.getMessage());
if (strict && !(e instanceof AwsException aws
&& "TargetGroupNotFound".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
* runs meanwhile.
*/
private void forEachGroupInRegion(String region, Consumer<AutoScalingGroup> action) {
for (AutoScalingGroup group : groups.values()) {
if (group == null || !region.equals(group.getRegion())) {
continue;
}
synchronized (lockFor(asgKey(region, group.getAutoScalingGroupName()))) {
action.accept(group);
}
}
}
static void deregisterFromTargetGroups(ElbV2Service elb, AutoScalingGroup asg, List<String> instanceIds) {
deregisterFromTargetGroups(elb, asg, asg.getTargetGroupARNs(), instanceIds);
}
/** As above, from {@code targetGroupArns} rather than from every target group the group has attached. */
static void deregisterFromTargetGroups(ElbV2Service elb, AutoScalingGroup asg, Collection<String> targetGroupArns,
List<String> instanceIds) {
List<TargetDescription> targets = instanceIds.stream().map(id -> {
TargetDescription target = new TargetDescription();
target.setId(id);
return target;
}).toList();
for (String targetGroup : asg.getTargetGroupARNs()) {
for (String targetGroup : targetGroupArns) {
try {
elb.deregisterTargets(asg.getRegion(), targetGroup, targets);
} catch (AwsException e) {
@@ -1017,6 +1112,12 @@ public class AutoScalingService implements PassedRoleLookup {
public void detachInstances(String region, String name, List<String> instanceIds,
boolean decrementDesiredCapacity) {
withRegionLockForEksGroup(region, name,
() -> detachMembers(region, name, instanceIds, decrementDesiredCapacity));
}
private void detachMembers(String region, String name, List<String> instanceIds,
boolean decrementDesiredCapacity) {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
@@ -1035,7 +1136,12 @@ public class AutoScalingService implements PassedRoleLookup {
.filter(instanceIds::contains).toList();
InstanceRefresh refresh = activeInstanceRefresh(asg);
if (!detached.isEmpty()) {
deregisterFromTargetGroups(elbV2Service, asg, detached);
if (asg.isEksManaged()) {
// The node stays in the target groups another group holding it has attached.
deregisterFromUnsharedTargetGroups(asg, detached, attachedTargetGroups(asg));
} else {
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);
@@ -1054,6 +1160,7 @@ public class AutoScalingService implements PassedRoleLookup {
public void terminateInstanceInAutoScalingGroup(String region, String instanceId,
boolean decrementDesiredCapacity) {
updateGroupOfInstance(region, instanceId, asg -> {
refuseForEksGroup(asg);
InstanceRefresh refresh = activeInstanceRefresh(asg);
completeInstanceRefreshIfSettled(region, asg.getAutoScalingGroupName(), asg);
releaseRefreshOwnership(refresh, List.of(instanceId));
@@ -1080,6 +1187,7 @@ public class AutoScalingService implements PassedRoleLookup {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
refuseForEksGroup(asg);
List<AsgInstance> moving = membersInState(asg, instanceIds, "InService");
int desired = asg.getDesiredCapacity();
int newDesired = shouldDecrementDesiredCapacity ? desired - moving.size() : desired;
@@ -1114,6 +1222,7 @@ public class AutoScalingService implements PassedRoleLookup {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
refuseForEksGroup(asg);
List<AsgInstance> moving = membersInState(asg, instanceIds, "Standby");
int desired = asg.getDesiredCapacity();
int newDesired = desired + moving.size();
@@ -1218,6 +1327,7 @@ public class AutoScalingService implements PassedRoleLookup {
public InstanceRefresh startInstanceRefresh(String region, String asgName, InstanceRefresh requestedRefresh) {
synchronized (lockFor(asgKey(region, asgName))) {
AutoScalingGroup asg = requireGroup(region, asgName);
refuseForEksGroup(asg);
boolean activeRefresh = instanceRefreshes.values().stream()
.filter(r -> region.equals(r.getRegion()))
.filter(r -> asgName.equals(r.getAutoScalingGroupName()))
@@ -1347,19 +1457,17 @@ public class AutoScalingService implements PassedRoleLookup {
// ── Load balancer attachment ───────────────────────────────────────────────
public void attachLoadBalancerTargetGroups(String region, String name, List<String> tgArns) {
AutoScalingGroup asg = requireGroup(region, name);
for (String arn : tgArns) {
if (!asg.getTargetGroupARNs().contains(arn)) {
asg.getTargetGroupARNs().add(arn);
changeAttachments(region, name, asg -> {
for (String arn : tgArns) {
if (!asg.getTargetGroupARNs().contains(arn)) {
asg.getTargetGroupARNs().add(arn);
}
}
}
groups.put(asgKey(region, name), asg);
});
}
public void detachLoadBalancerTargetGroups(String region, String name, List<String> tgArns) {
AutoScalingGroup asg = requireGroup(region, name);
asg.getTargetGroupARNs().removeAll(tgArns);
groups.put(asgKey(region, name), asg);
changeAttachments(region, name, asg -> asg.getTargetGroupARNs().removeAll(tgArns));
}
public List<String> describeLoadBalancerTargetGroups(String region, String name) {
@@ -1386,27 +1494,28 @@ public class AutoScalingService implements PassedRoleLookup {
// AttachTrafficSources/DetachTrafficSources/DescribeTrafficSources is the modern,
// unified ASG-to-load-balancer wiring API (elb, elbv2, vpc-lattice), which
// aws_autoscaling_traffic_source_attachment uses instead of the older
// AttachLoadBalancerTargetGroups. "accept and remember" like the target-group
// attachment above - Floci has no real health-checking loop, so every attached
// traffic source is reported InService immediately.
// AttachLoadBalancerTargetGroups. Like the target-group attachment above, each source is
// stored with its type, and only an EKS group's node is registered with an elbv2 source as
// it is attached and deregistered as it is detached. Floci has no real health-checking loop,
// so every attached traffic source is reported InService immediately.
public record TrafficSourceIdentifier(String identifier, String type) {}
public void attachTrafficSources(String region, String name, List<TrafficSourceIdentifier> sources) {
AutoScalingGroup asg = requireGroup(region, name);
for (TrafficSourceIdentifier source : sources) {
asg.getTrafficSourceTypeByIdentifier().put(source.identifier(),
source.type() != null ? source.type() : "elbv2");
}
groups.put(asgKey(region, name), asg);
changeAttachments(region, name, asg -> {
for (TrafficSourceIdentifier source : sources) {
asg.getTrafficSourceTypeByIdentifier().put(source.identifier(),
source.type() != null ? source.type() : "elbv2");
}
});
}
public void detachTrafficSources(String region, String name, List<TrafficSourceIdentifier> sources) {
AutoScalingGroup asg = requireGroup(region, name);
for (TrafficSourceIdentifier source : sources) {
asg.getTrafficSourceTypeByIdentifier().remove(source.identifier());
}
groups.put(asgKey(region, name), asg);
changeAttachments(region, name, asg -> {
for (TrafficSourceIdentifier source : sources) {
asg.getTrafficSourceTypeByIdentifier().remove(source.identifier());
}
});
}
public Map<String, String> describeTrafficSources(String region, String name, String trafficSourceType) {
@@ -1423,6 +1532,176 @@ public class AutoScalingService implements PassedRoleLookup {
return filtered;
}
/** The target groups attached to {@code asg}: as target groups, and as {@code elbv2} traffic sources. */
private static Set<String> attachedTargetGroups(AutoScalingGroup asg) {
Set<String> attached = new LinkedHashSet<>(asg.getTargetGroupARNs());
asg.getTrafficSourceTypeByIdentifier().forEach((identifier, type) -> {
if ("elbv2".equals(type)) {
attached.add(identifier);
}
});
return attached;
}
// ── 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.
/**
* Creates the group EKS keeps for a managed node group, unless a group of that name exists. It has no launch
* source: its instances are added with {@link #addEksManagedInstance}. Its zones are those of the subnets EC2
* knows, since CreateNodegroup does not check its subnets.
*/
public void createEksManagedGroup(String region, String name, int minSize, int maxSize, int desiredCapacity,
List<String> subnetIds, Map<String, String> tags) {
String key = asgKey(region, name);
synchronized (lockFor(key)) {
if (groups.containsKey(key)) {
return;
}
Map<String, Boolean> propagateAtLaunch = new LinkedHashMap<>();
tags.keySet().forEach(tagKey -> propagateAtLaunch.put(tagKey, true));
AutoScalingGroup asg = newGroup(region, name, minSize, maxSize, desiredCapacity,
subnetZones(region, subnetIds).values().stream().distinct().toList(), subnetIds, null,
tags, propagateAtLaunch);
asg.setEksManaged(true);
groups.put(key, asg);
}
}
/**
* 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.
*/
public void addEksManagedInstance(String region, String name, Instance instance) {
String key = asgKey(region, name);
synchronized (lockFor(region)) {
synchronized (lockFor(key)) {
AutoScalingGroup asg = groups.get(key);
if (asg == null || !asg.isEksManaged() || containsInstance(asg, instance.getInstanceId())) {
return;
}
AsgInstance member = new AsgInstance();
member.setInstanceId(instance.getInstanceId());
member.setLifecycleState("InService");
member.setHealthStatus("Healthy");
member.setAvailabilityZone(instance.getPlacement() != null
? instance.getPlacement().getAvailabilityZone() : null);
member.setInstanceType(instance.getInstanceType());
asg.getInstances().add(member);
groups.put(key, asg);
registerWithTargetGroups(elbV2Service, asg, attachedTargetGroups(asg), 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.
*/
public void deleteEksManagedGroup(String region, String name) {
synchronized (lockFor(region)) {
AutoScalingGroup asg = groups.get(asgKey(region, name));
if (asg != null && asg.isEksManaged()) {
deleteAutoScalingGroup(region, name, true);
}
}
}
/**
* Applies {@code change} to the target groups and traffic sources attached to the group {@code name}, and
* stores it. An EKS group's in-service members are then registered with the target groups the change attached
* and deregistered from those it detached, as AWS does, all under the Region's lock and then the group's, like
* every change to an EKS group's members or target groups. Other groups' members are left as they are: the
* reconciler registers them as they come into service.
*/
private void changeAttachments(String region, String name, Consumer<AutoScalingGroup> change) {
String key = asgKey(region, name);
AutoScalingGroup asg = requireGroup(region, name);
if (!asg.isEksManaged()) {
change.accept(asg);
groups.put(key, asg);
return;
}
synchronized (lockFor(region)) {
synchronized (lockFor(key)) {
AutoScalingGroup current = requireGroup(region, name);
List<String> targetGroupsBefore = new ArrayList<>(current.getTargetGroupARNs());
Map<String, String> trafficSourcesBefore = new LinkedHashMap<>(current.getTrafficSourceTypeByIdentifier());
Set<String> attachedBefore = attachedTargetGroups(current);
change.accept(current);
Set<String> attached = attachedTargetGroups(current);
Set<String> detached = new LinkedHashSet<>(attachedBefore);
detached.removeAll(attached);
attached.removeAll(attachedBefore);
// The node leaves the target groups the change detached before the change is stored: when ELBv2
// refuses, the group keeps them attached, so the detach can be sent again.
try {
deregisterFromUnsharedTargetGroups(current, memberIds(current), detached);
} catch (RuntimeException e) {
current.setTargetGroupARNs(targetGroupsBefore);
current.setTrafficSourceTypeByIdentifier(trafficSourcesBefore);
throw e;
}
groups.put(key, current);
for (AsgInstance member : current.getInstances()) {
if ("InService".equals(member.getLifecycleState())) {
registerWithTargetGroups(elbV2Service, current, attached, member.getInstanceId(), false);
}
}
}
}
}
/**
* Runs {@code body} holding the Region's lock when {@code name} is an EKS group, so it takes that lock before
* the group's own, as every change to an EKS group's members or target groups does.
*/
private void withRegionLockForEksGroup(String region, String name, Runnable body) {
AutoScalingGroup asg = groups.get(asgKey(region, name));
if (asg == null || !asg.isEksManaged()) {
body.run();
return;
}
synchronized (lockFor(region)) {
body.run();
}
}
private static List<String> memberIds(AutoScalingGroup asg) {
return asg.getInstances().stream().map(AsgInstance::getInstanceId).filter(Objects::nonNull).toList();
}
/**
* Deregisters each of {@code instanceIds}, members of {@code asg}, from those of {@code targetGroupArns} that no
* other group holding the instance has attached: the groups of a cluster's node groups share its node. Called
* holding the Region's lock and the group's, so no other group gains or loses the instance or a target group
* meanwhile, and the other groups' members are read under their own locks.
*/
private void deregisterFromUnsharedTargetGroups(AutoScalingGroup asg, List<String> instanceIds,
Set<String> targetGroupArns) {
if (targetGroupArns.isEmpty()) {
return;
}
for (String instanceId : instanceIds) {
Set<String> leaving = new LinkedHashSet<>(targetGroupArns);
forEachGroupInRegion(asg.getRegion(), other -> {
if (!asg.getAutoScalingGroupName().equals(other.getAutoScalingGroupName())
&& containsInstance(other, instanceId)) {
leaving.removeAll(attachedTargetGroups(other));
}
});
if (!leaving.isEmpty()) {
deregisterFromTargetGroups(elbV2Service, asg, leaving, List.of(instanceId));
}
}
}
// ── Lifecycle hooks ────────────────────────────────────────────────────────
public void putLifecycleHook(String region, String asgName, String hookName,
@@ -59,6 +59,9 @@ public class AutoScalingGroup {
// Set only by EnableMetricsCollection/DisableMetricsCollection. 1Minute is the only granularity
// the model allows, so the metric names are all that needs storing.
private List<String> enabledMetrics = new ArrayList<>();
// The group EKS keeps for a managed node group. EKS owns its capacity: Auto Scaling never launches,
// terminates or replaces its instances, which are the cluster's node.
private boolean eksManaged;
public AutoScalingGroup() {}
@@ -186,4 +189,7 @@ public class AutoScalingGroup {
public List<String> getEnabledMetrics() { return enabledMetrics; }
public void setEnabledMetrics(List<String> v) { this.enabledMetrics = v != null ? new ArrayList<>(v) : new ArrayList<>(); }
public boolean isEksManaged() { return eksManaged; }
public void setEksManaged(boolean v) { this.eksManaged = v; }
}
@@ -115,6 +115,8 @@ public class EksClusterManager
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final int K3S_API_SERVER_PORT = 6443;
static final String DEFAULT_NODE_INSTANCE_TYPE = "m5.large";
/** The tag naming the cluster, on the cluster's node and on its node groups' Auto Scaling groups. */
static final String CLUSTER_NAME_TAG = "eks:cluster-name";
private static final String NODE_CAPACITY_LABEL = "io.floci.eks.node-capacity";
private static final String DEFAULT_STORAGE_CLASS_LABEL = "io.floci.eks.default-storage-class";
private static final String ENDPOINT_HOST_LABEL = "io.floci.eks.endpoint-host";
@@ -3283,7 +3285,7 @@ public class EksClusterManager
List<Tag> tags = new ArrayList<>();
tags.add(new Tag("Name", safeClusterName + "-node"));
tags.add(new Tag("kubernetes.io/cluster/" + safeClusterName, "owned"));
tags.add(new Tag("eks:cluster-name", safeClusterName));
tags.add(new Tag(CLUSTER_NAME_TAG, safeClusterName));
inst.setTags(tags);
return inst;
}
@@ -152,7 +152,7 @@ public class EksController {
public Response createNodeGroup(@PathParam("name") String name, CreateNodeGroupRequest request) {
eksService.requireClusterInRequestRegion(name);
Nodegroup nodeGroup = eksService.createNodeGroup(name, request);
return Response.ok(Map.of("nodegroup", nodeGroup)).build();
return Response.ok(Map.of("nodegroup", toNodegroupResponse(nodeGroup))).build();
}
@GET
@@ -169,7 +169,7 @@ public class EksController {
@PathParam("nodegroupName") String nodegroupName) {
eksService.requireClusterInRequestRegion(name);
Nodegroup nodeGroup = eksService.describeNodeGroup(name, nodegroupName);
return Response.ok(Map.of("nodegroup", nodeGroup)).build();
return Response.ok(Map.of("nodegroup", toNodegroupResponse(nodeGroup))).build();
}
@DELETE
@@ -178,7 +178,17 @@ public class EksController {
@PathParam("nodegroupName") String nodegroupName) {
eksService.requireClusterInRequestRegion(name);
Nodegroup nodeGroup = eksService.deleteNodeGroup(name, nodegroupName);
return Response.ok(Map.of("nodegroup", nodeGroup)).build();
return Response.ok(Map.of("nodegroup", toNodegroupResponse(nodeGroup))).build();
}
/** The node group without {@link Nodegroup#isAutoScalingGroupCreated()}, which is Floci's own record. */
private static Nodegroup toNodegroupResponse(Nodegroup nodeGroup) {
if (!nodeGroup.isAutoScalingGroupCreated()) {
return nodeGroup;
}
Nodegroup response = nodeGroup.copy();
response.setAutoScalingGroupCreated(false);
return response;
}
@POST
@@ -17,6 +17,7 @@ import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.autoscaling.AutoScalingService;
import io.floci.aws.services.ec2.Ec2InstanceLaunchListener;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.Ipv4Cidrs;
@@ -64,6 +65,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -112,6 +114,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
private final EksAccessEntryService accessEntries;
private final EksPodIdentityAssociationService podIdentityAssociations;
private final EksAddonService addons;
private final AutoScalingService autoScaling;
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
private final Map<String, UserDataClaim> appliedClusterUserData = new ConcurrentHashMap<>();
private final Map<String, Object> nodeGroupCapacityLocks = new ConcurrentHashMap<>();
@@ -127,7 +130,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons) {
EksAddonService addons, AutoScalingService autoScaling) {
this.storage = storageFactory.create("eks", "eks-clusters.json",
new TypeReference<Map<String, Cluster>>() {
});
@@ -145,11 +148,21 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
this.accessEntries = accessEntries;
this.podIdentityAssociations = podIdentityAssociations;
this.addons = addons;
this.autoScaling = autoScaling;
if (this.clusterManager != null) {
this.clusterManager.setEc2Service(this.ec2Service);
}
}
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries,
EksPodIdentityAssociationService podIdentityAssociations,
EksAddonService addons) {
this(storageFactory, config, regionResolver, clusterManager, ec2Service,
oidcService, accessEntries, podIdentityAssociations, addons, null);
}
public EksService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver, EksClusterManager clusterManager, Ec2Service ec2Service,
EksOidcService oidcService, EksAccessEntryService accessEntries,
@@ -185,6 +198,10 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
ec2Service.restoreAttachedVolumesForInstance(reg, nodeInst);
});
}
if (clusterManager != null && autoScaling != null) {
clusterManager.addNodeRegistrationListener(this::addNodeToNodeGroupAutoScalingGroups);
}
restoreNodeGroupAutoScalingGroups();
if (!config.services().eks().mock()) {
restorePersistedClusters();
} else {
@@ -272,6 +289,14 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
.toList();
}
/** Every account's cluster stored under {@code key}, read with one get per account rather than a scan. */
private List<AccountAwareStorageBackend.AccountEntry<Cluster>> clusterEntries(String key) {
if (storage instanceof AccountAwareStorageBackend<Cluster> aware) {
return aware.findAllAccountEntries(key);
}
return allClusterEntries().stream().filter(entry -> key.equals(clusterKey(entry.value()))).toList();
}
private boolean isClusterDeleting(String accountId, Cluster cluster) {
return cluster != null && cluster.getName() != null
&& (cluster.getStatus() == ClusterStatus.DELETING
@@ -430,6 +455,9 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
try {
clearAppliedClusterUserData(cluster, clusterName);
if (cluster != null) {
deleteNodeGroupAutoScalingGroups(accountId, cluster);
}
if (cluster == null || cluster.getArn() == null) {
String fallbackArn = AwsArnUtils.Arn.of("eks", regionOfKey(clusterKey), accountId,
"cluster/" + clusterName).toString();
@@ -1113,6 +1141,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
}
}
deleteClusterSecurityGroup(cluster);
deleteNodeGroupAutoScalingGroups(cluster.getAccountId(), cluster);
accessEntries.deleteClusterEntries(cluster);
if (podIdentityAssociations != null) {
podIdentityAssociations.deleteClusterAssociations(cluster);
@@ -1306,6 +1335,8 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
nodeGroup.setStatus(NodegroupStatus.ACTIVE);
}
}
// The node group is already stored, so a node registering meanwhile finds it.
createNodeGroupAutoScalingGroup(accountId, currentCluster, nodeGroup);
nodeGroupStorage.put(storageKey, nodeGroup);
stored = true;
}
@@ -1416,6 +1447,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
Object capacityLock = capacityLock(regionResolver.getAccountId(), clusterKey);
synchronized (capacityLock) {
Nodegroup nodeGroup = describeNodeGroup(clusterName, nodegroupName);
deleteNodeGroupAutoScalingGroup(regionResolver.getAccountId(), regionOfKey(clusterKey), nodeGroup);
nodeGroup.setStatus(NodegroupStatus.DELETING);
nodeGroup.setModifiedAt(Instant.now());
nodeGroupStorage.delete(nodeGroupKey(clusterKey, nodegroupName));
@@ -1847,6 +1879,162 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
return resources;
}
/** The name of the Auto Scaling group {@code nodeGroup} reports in its resources, or null when it reports none. */
private static String autoScalingGroupName(Nodegroup nodeGroup) {
if (nodeGroup.getResources() instanceof Map<?, ?> resources
&& resources.get("autoScalingGroups") instanceof List<?> autoScalingGroups
&& !autoScalingGroups.isEmpty()
&& autoScalingGroups.getFirst() instanceof Map<?, ?> autoScalingGroup
&& autoScalingGroup.get("name") instanceof String name) {
return name;
}
return null;
}
/**
* The tags EKS puts on a managed node group's Auto Scaling group: the cluster and node group it belongs to, and
* the two the Kubernetes Cluster Autoscaler discovers a cluster's groups by.
*/
private static Map<String, String> nodeGroupAutoScalingTags(String clusterName, String nodegroupName) {
return Map.of(
EksClusterManager.CLUSTER_NAME_TAG, clusterName,
"eks:nodegroup-name", nodegroupName,
"k8s.io/cluster-autoscaler/enabled", "true",
"k8s.io/cluster-autoscaler/" + clusterName, "owned");
}
/**
* Creates the Auto Scaling group {@code nodeGroup} reports, in its account and Region, unless it exists, with
* the cluster's node in it once the node is registered, and records on the node group that it was created; the
* caller stores the node group. Floci runs one node per cluster, so every node group's group holds that node.
* The node is looked up after the group exists: a node registering meanwhile is added by
* {@link #addNodeToNodeGroupAutoScalingGroups}, which finds the group, since the node group is stored first.
*/
private void createNodeGroupAutoScalingGroup(String accountId, Cluster cluster, Nodegroup nodeGroup) {
String groupName = autoScalingGroupName(nodeGroup);
if (autoScaling == null || groupName == null) {
return;
}
String region = resolveClusterRegion(cluster);
NodegroupScalingConfig defaults = defaultScalingConfig();
NodegroupScalingConfig scaling = nodeGroup.getScalingConfig() != null ? nodeGroup.getScalingConfig() : defaults;
List<String> subnets = nodeGroup.getSubnets() != null ? nodeGroup.getSubnets() : List.of();
try {
RequestScopes.runAs(accountId, region, () -> {
autoScaling.createEksManagedGroup(region, groupName,
Objects.requireNonNullElse(scaling.getMinSize(), defaults.getMinSize()),
Objects.requireNonNullElse(scaling.getMaxSize(), defaults.getMaxSize()),
Objects.requireNonNullElse(scaling.getDesiredSize(), defaults.getDesiredSize()),
subnets, nodeGroupAutoScalingTags(cluster.getName(), nodeGroup.getNodegroupName()));
Instance node = clusterManager != null ? clusterManager.getRegisteredClusterNodeInstance(cluster) : null;
if (node != null) {
autoScaling.addEksManagedInstance(region, groupName, node);
}
});
nodeGroup.setAutoScalingGroupCreated(true);
} catch (RuntimeException e) {
// The node group stands without it, as it did before Floci kept these groups, and the next start
// tries again.
LOG.warnv("Could not create Auto Scaling group {0} of EKS node group {1} in cluster {2}: {3}",
groupName, nodeGroup.getNodegroupName(), cluster.getName(), e.getMessage());
}
}
/**
* Adds a cluster's node, once it registers, to the Auto Scaling group of each of the cluster's node groups. The
* node carries its cluster's Region and, in its {@code eks:cluster-name} tag, its name, so only the clusters
* stored under that Region and name are read. An instance that joins a cluster from EC2 is in no managed node
* group, and is not added.
*/
private void addNodeToNodeGroupAutoScalingGroups(Instance node) {
String clusterName = node.getTags() == null ? null : node.getTags().stream()
.filter(tag -> EksClusterManager.CLUSTER_NAME_TAG.equals(tag.getKey()))
.map(Tag::getValue).findFirst().orElse(null);
if (clusterName == null || node.getRegion() == null) {
return;
}
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry
: clusterEntries(clusterKey(node.getRegion(), clusterName))) {
Cluster cluster = entry.value();
Instance registered = clusterManager.getRegisteredClusterNodeInstance(cluster);
if (registered == null || !registered.getInstanceId().equals(node.getInstanceId())) {
continue;
}
String region = resolveClusterRegion(cluster);
for (Nodegroup nodeGroup : listNodeGroupsForCluster(clusterKey(cluster), entry.accountId())) {
String groupName = autoScalingGroupName(nodeGroup);
if (groupName == null) {
continue;
}
try {
RequestScopes.runAs(entry.accountId(), region,
() -> autoScaling.addEksManagedInstance(region, groupName, node));
} catch (RuntimeException e) {
LOG.warnv("Could not add the node of EKS cluster {0} to Auto Scaling group {1} of node group {2}: {3}",
cluster.getName(), groupName, nodeGroup.getNodegroupName(), e.getMessage());
}
}
}
}
/**
* Gives each node group stored before Floci kept their Auto Scaling groups the group it reports, once: a node
* group whose group was created is skipped, so a group deleted through Auto Scaling stays deleted. Runs as this
* bean is created, from {@link #init()}.
*/
void restoreNodeGroupAutoScalingGroups() {
if (autoScaling == null) {
return;
}
for (AccountAwareStorageBackend.AccountEntry<Cluster> entry : allClusterEntries()) {
Cluster cluster = entry.value();
for (Nodegroup nodeGroup : listNodeGroupsForCluster(clusterKey(cluster), entry.accountId())) {
if (nodeGroup.isAutoScalingGroupCreated()) {
continue;
}
createNodeGroupAutoScalingGroup(entry.accountId(), cluster, nodeGroup);
if (nodeGroup.isAutoScalingGroupCreated()) {
putNodeGroupForAccount(entry.accountId(),
nodeGroupKey(clusterKey(cluster), nodeGroup.getNodegroupName()), nodeGroup);
}
}
}
}
private void putNodeGroupForAccount(String accountId, String key, Nodegroup nodeGroup) {
if (nodeGroupStorage instanceof AccountAwareStorageBackend<Nodegroup> aware) {
aware.putForAccount(accountId, key, nodeGroup);
return;
}
nodeGroupStorage.put(key, nodeGroup);
}
/**
* 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.
*/
private void deleteNodeGroupAutoScalingGroup(String accountId, String region, Nodegroup nodeGroup) {
String groupName = autoScalingGroupName(nodeGroup);
if (autoScaling == null || groupName == null) {
return;
}
try {
RequestScopes.runAs(accountId, region, () -> autoScaling.deleteEksManagedGroup(region, groupName));
} catch (RuntimeException e) {
LOG.warnv("Could not delete Auto Scaling group {0} of EKS node group {1} in cluster {2}: {3}",
groupName, nodeGroup.getNodegroupName(), nodeGroup.getClusterName(), e.getMessage());
}
}
/** Deletes the Auto Scaling groups of {@code cluster}'s node groups, as deleting each node group does. */
private void deleteNodeGroupAutoScalingGroups(String accountId, Cluster cluster) {
String region = resolveClusterRegion(cluster);
for (Nodegroup nodeGroup : listNodeGroupsForCluster(clusterKey(cluster), accountId)) {
deleteNodeGroupAutoScalingGroup(accountId, region, nodeGroup);
}
}
private Map<String, List<Object>> defaultNodeGroupHealth() {
Map<String, List<Object>> health = new LinkedHashMap<>();
health.put("issues", new ArrayList<>());
@@ -107,8 +107,51 @@ public class Nodegroup {
@JsonIgnore
private String accountId;
/**
* Whether Floci created this node group's Auto Scaling group. Set once the group exists, so the startup backfill
* creates one only for a node group stored before Floci kept these groups, and a group deleted through Auto
* Scaling stays deleted. Stored with the node group, and left out of every response by EksController.
*/
@JsonProperty("autoScalingGroupCreated")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private boolean autoScalingGroupCreated;
public Nodegroup() {}
/** A copy sharing this node group's nested values, for a response that leaves out Floci's own fields. */
public Nodegroup copy() {
Nodegroup c = new Nodegroup();
c.nodegroupName = this.nodegroupName;
c.nodegroupArn = this.nodegroupArn;
c.clusterName = this.clusterName;
c.version = this.version;
c.releaseVersion = this.releaseVersion;
c.createdAt = this.createdAt;
c.modifiedAt = this.modifiedAt;
c.status = this.status;
c.capacityType = this.capacityType;
c.scalingConfig = this.scalingConfig;
c.instanceTypes = this.instanceTypes;
c.subnets = this.subnets;
c.remoteAccess = this.remoteAccess;
c.amiType = this.amiType;
c.nodeRole = this.nodeRole;
c.labels = this.labels;
c.taints = this.taints;
c.resources = this.resources;
c.diskSize = this.diskSize;
c.health = this.health;
c.updateConfig = this.updateConfig;
c.nodeRepairConfig = this.nodeRepairConfig;
c.launchTemplate = this.launchTemplate;
c.warmPoolConfig = this.warmPoolConfig;
c.tags = this.tags;
c.clientRequestToken = this.clientRequestToken;
c.accountId = this.accountId;
c.autoScalingGroupCreated = this.autoScalingGroupCreated;
return c;
}
public String getNodegroupName() { return nodegroupName; }
public void setNodegroupName(String nodegroupName) { this.nodegroupName = nodegroupName; }
@@ -189,4 +232,9 @@ public class Nodegroup {
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public boolean isAutoScalingGroupCreated() { return autoScalingGroupCreated; }
public void setAutoScalingGroupCreated(boolean autoScalingGroupCreated) {
this.autoScalingGroupCreated = autoScalingGroupCreated;
}
}