mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
e901eb27b2
commit
74a9ea76d5
24 files changed
+1686
-272
No files matched your search
@@ -29,7 +29,7 @@ Floci implements the EC2 Auto Scaling API — stored-state management for launch
|
||||
| `CreateAutoScalingGroup` | Creates a group with min/max/desired capacity, AZs, tags, launch configuration, launch template, or mixed instances policy; starts capacity reconciliation loop |
|
||||
| `DescribeAutoScalingGroups` | Filtered by name list; returns all if no filter; includes current instance list with lifecycle state and mixed instances policy shape when configured |
|
||||
| `UpdateAutoScalingGroup` | Updates capacity bounds, cooldown, launch source, AZs |
|
||||
| `DeleteAutoScalingGroup` | `ForceDelete=true` terminates all instances before deletion |
|
||||
| `DeleteAutoScalingGroup` | `ForceDelete=true` terminates all instances before deletion, except in an [EKS nodegroup's group](eks.md#auto-scaling-group) |
|
||||
| `DescribeTags` | Group tags; filters `auto-scaling-group`, `key`, `value`, `propagate-at-launch` (values ORed, filters ANDed); `MaxRecords`/`NextToken` paging |
|
||||
| `CreateOrUpdateTags` | Creates or updates group tags and their propagate-at-launch setting |
|
||||
| `DeleteTags` | Removes named group tags |
|
||||
@@ -103,7 +103,7 @@ EC2 instance can use a default subnet in a different zone.
|
||||
| `SetInstanceProtection` | Enables or disables scale-in protection for named instances in a group |
|
||||
| `SetDesiredCapacity` | Updates desired count; reconciler handles scale-out / scale-in within 10 s |
|
||||
| `AttachInstances` | Attaches existing EC2 instances to a group; sets lifecycle state to `InService`. Refuses the whole batch with `ValidationError` when an instance already belongs to a group |
|
||||
| `DetachInstances` | Detaches instances from a group; optionally decrements desired capacity |
|
||||
| `DetachInstances` | Detaches instances from a group and deregisters them from its target groups; optionally decrements desired capacity |
|
||||
| `TerminateInstanceInAutoScalingGroup` | Terminates a specific instance; optionally decrements desired capacity |
|
||||
| `EnterStandby` | Moves `InService` instances to `EnteringStandby` and returns one `InProgress` activity (progress 50) per instance; the reconciler deregisters them from the group's target groups and Classic Load Balancers and sets `Standby` within 10 s. `ShouldDecrementDesiredCapacity=true` lowers desired capacity by the number of instances, refused with `ValidationError` below `MinSize`; `false` keeps it, so the group launches replacements |
|
||||
| `ExitStandby` | Moves `Standby` instances to `Pending`, raises desired capacity by the number of instances (refused with `ValidationError` above `MaxSize`) and returns one `PreInService` activity (progress 30) per instance; the reconciler registers them with the group's load balancers and sets `InService` within 10 s |
|
||||
@@ -180,8 +180,8 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash.
|
||||
|
||||
| Operation | Notes |
|
||||
|---|---|
|
||||
| `AttachLoadBalancerTargetGroups` | Attaches ELB v2 target group ARNs; new instances auto-registered on InService |
|
||||
| `DetachLoadBalancerTargetGroups` | Detaches target groups; instances deregistered |
|
||||
| `AttachLoadBalancerTargetGroups` | Attaches ELB v2 target group ARNs. The reconciler registers each instance with them as it comes into service; instances already in service stay unregistered, which AWS registers. An EKS nodegroup's group registers its node at once |
|
||||
| `DetachLoadBalancerTargetGroups` | Detaches target groups. The group's instances stay registered with them, which AWS deregisters; an EKS nodegroup's group deregisters its node at once |
|
||||
| `DescribeLoadBalancerTargetGroups` | Lists target groups attached to a group |
|
||||
| `AttachLoadBalancers` | Classic ELB attachment (stored; no ELB v1 routing) |
|
||||
| `DetachLoadBalancers` | Classic ELB detachment |
|
||||
@@ -191,8 +191,8 @@ imply an atomic transaction spanning Auto Scaling and EC2 after a process crash.
|
||||
|
||||
| Operation | Notes |
|
||||
|---|---|
|
||||
| `AttachTrafficSources` | Unified elb/elbv2/vpc-lattice attachment API; stored per identifier with its type |
|
||||
| `DetachTrafficSources` | Removes a traffic source by identifier |
|
||||
| `AttachTrafficSources` | Unified elb/elbv2/vpc-lattice attachment API; stored per identifier with its type. Instances are not registered with an `elbv2` source, which AWS does, except an EKS nodegroup's node, registered at once |
|
||||
| `DetachTrafficSources` | Removes a traffic source by identifier; an EKS nodegroup's group deregisters its node from an `elbv2` source at once |
|
||||
| `DescribeTrafficSources` | Lists attached sources, optionally filtered by type; every source reports `InService` |
|
||||
|
||||
### Lifecycle Hooks
|
||||
@@ -270,6 +270,7 @@ Floci runs a background reconciler (10 s fixed rate) that keeps each group's InS
|
||||
- **Scale-out**: calls `RunInstances` with the group's launch configuration; new instances are tracked as `Pending` until the EC2 state transitions to `running`, at which point they move to `InService` and are registered with all attached ELB v2 target groups.
|
||||
- **Scale-in**: selects InService instances not protected from scale-in, deregisters them from target groups, then calls `TerminateInstances`.
|
||||
- Activity records are written on each scale-out and scale-in event.
|
||||
- **EKS nodegroups**: the group EKS keeps for a managed nodegroup is left alone. Its instance is the cluster's node, which the reconciler never launches, terminates or replaces, so attaching a target group to such a group registers the node at once and detaching it deregisters the node, and operations that would terminate, replace or move the node are refused. See the [EKS nodegroup Auto Scaling group](eks.md#auto-scaling-group).
|
||||
|
||||
`SuspendProcesses` pauses desired-capacity scale-out for `Launch` and scale-in for
|
||||
`Terminate`. The desired count remains stored, and `ResumeProcesses` allows the
|
||||
|
||||
@@ -405,6 +405,22 @@ Floci runs one k3s container per cluster. The worker node reflects the metadata
|
||||
#### Timing and post-start nodegroups
|
||||
Kubelet flags are fixed when the cluster container starts. For nodegroups created while the cluster is already running, metadata is recorded in the EKS store and Floci logs an informational message that labels and taints are not applied to the running node. Surviving cluster containers are adopted as-is without rebuilding kubelet flags on restore.
|
||||
|
||||
#### Auto Scaling group
|
||||
|
||||
Each nodegroup has the Auto Scaling group that `DescribeNodegroup` names in `resources.autoScalingGroups`, in the nodegroup's account and Region. Its minimum, maximum and desired sizes are the nodegroup's `scalingConfig`, its subnets are the nodegroup's, and it is tagged `eks:cluster-name`, `eks:nodegroup-name`, `k8s.io/cluster-autoscaler/enabled=true` and `k8s.io/cluster-autoscaler/<cluster-name>=owned`. Its instance is the cluster's shared node, `InService` and `Healthy`. A node that registers after the nodegroup was created joins the group then.
|
||||
|
||||
- Attaching a target group to the group, with `AttachLoadBalancerTargetGroups` or as an `elbv2` traffic source with `AttachTrafficSources`, registers the node with it by instance id at once. Detaching it, or detaching the node with `DetachInstances`, deregisters the node, unless the group of another of the cluster's nodegroups still has that target group attached.
|
||||
- Deleting the nodegroup deletes its group and deregisters the node the same way, and so does `DeleteAutoScalingGroup` on the group, which still needs `ForceDelete` while the group holds the node and terminates nothing. Deleting the cluster deletes the groups of its nodegroups. A group that cannot be deleted is logged, and the nodegroup or cluster is deleted all the same.
|
||||
- Auto Scaling never launches, terminates, replaces or moves the group's instance. `TerminateInstanceInAutoScalingGroup`, `EnterStandby`, `ExitStandby`, `StartInstanceRefresh`, `AttachInstances`, and `SetInstanceHealth` with `Unhealthy`, are refused on the group with a `ValidationError` saying it is managed by EKS for a nodegroup. Its settings still change: `SetDesiredCapacity` and the sizes of `UpdateAutoScalingGroup` change only the capacity the group reports, and a `Healthy` status and scale-in protection are recorded.
|
||||
- `DescribeNodegroup` keeps the `scalingConfig` the nodegroup was created with. AWS copies sizes changed on the group directly back into the nodegroup from time to time; Floci does not, and does not implement `UpdateNodegroupConfig` either.
|
||||
- A nodegroup stored before Floci kept these groups gets its group when Floci's EKS service starts: at Floci's startup when clusters run in Docker, and in mock mode when Floci first uses EKS, at the latest with the first EKS request. The nodegroup records that its group was created, so this happens once: a group deleted through Auto Scaling is not created again.
|
||||
|
||||
Floci runs one node per cluster, so the groups of all of a cluster's nodegroups hold the same instance:
|
||||
|
||||
- `DescribeAutoScalingInstances` lists the node once for each nodegroup, with that nodegroup's group.
|
||||
- An operation that acts on the group of an instance, such as `SetInstanceHealth`, acts on the first group it finds holding the node. Those that would change the node are refused, as above.
|
||||
- The node stays registered with a target group as long as one of the groups holding it has that target group attached.
|
||||
|
||||
### Metadata only inputs
|
||||
|
||||
The remaining structured inputs are recorded as metadata:
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -49,8 +50,7 @@ class AutoScalingDetachLoadBalancersTest {
|
||||
verify(classic).deregisterInstances(REGION, "first", List.of("i-owned"));
|
||||
verify(classic).deregisterInstances(REGION, "second", List.of("i-owned"));
|
||||
verifyNoMoreInteractions(classic);
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("target-group"),
|
||||
argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId())));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("target-group"), onlyTarget("i-owned"));
|
||||
assertEquals(List.of(retained), group.getInstances());
|
||||
assertEquals(2, group.getDesiredCapacity());
|
||||
}
|
||||
@@ -120,8 +120,7 @@ class AutoScalingDetachLoadBalancersTest {
|
||||
|
||||
service.detachInstances(REGION, "group", List.of("i-owned", "i-other-group"), false);
|
||||
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"),
|
||||
argThat(values -> values.size() == 1 && "i-owned".equals(values.getFirst().getId())));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("shared-target-group"), onlyTarget("i-owned"));
|
||||
assertEquals(List.of(retained), group.getInstances());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
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;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.anyList;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.eq;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The groups EKS keeps for its managed node groups. Floci runs one node per cluster, so the groups of a cluster's
|
||||
* node groups all hold that node: Auto Scaling adds it, registers it with the target groups attached to each group,
|
||||
* and keeps it in a target group as long as one group holding it has that target group attached.
|
||||
*/
|
||||
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);
|
||||
|
||||
AutoScalingEksManagedGroupTest() {
|
||||
service.regionResolver = new RegionResolver(REGION, "000000000000");
|
||||
service.ec2Service = ec2;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theGroupMirrorsTheNodeGroupWithoutALaunchSourceAndIsCreatedOnce() {
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-a");
|
||||
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"));
|
||||
|
||||
AutoScalingGroup group = service.requireGroup(REGION, FIRST);
|
||||
assertTrue(group.isEksManaged());
|
||||
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:" + FIRST,
|
||||
group.getAutoScalingGroupArn());
|
||||
assertEquals(1, group.getMinSize());
|
||||
assertEquals(3, group.getMaxSize());
|
||||
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(Map.of("eks:cluster-name", true, "eks:nodegroup-name", true,
|
||||
"k8s.io/cluster-autoscaler/enabled", true, "k8s.io/cluster-autoscaler/shop", true),
|
||||
group.getTagPropagateAtLaunch());
|
||||
assertEquals(List.of("Default"), group.getTerminationPolicies());
|
||||
assertNull(group.getLaunchConfigurationName());
|
||||
assertNull(group.getLaunchTemplateId());
|
||||
assertNull(group.getLaunchTemplateName());
|
||||
assertNull(group.getMixedInstancesPolicy());
|
||||
assertEquals(List.of(), group.getInstances());
|
||||
|
||||
// Restoring a node group creates its group again; one that exists is left as it is.
|
||||
service.createEksManagedGroup(REGION, FIRST, 0, 5, 0, List.of(), Map.of());
|
||||
|
||||
assertSame(group, service.requireGroup(REGION, FIRST));
|
||||
assertEquals(1, group.getMinSize());
|
||||
assertEquals(3, group.getMaxSize());
|
||||
assertEquals(2, group.getDesiredCapacity());
|
||||
assertEquals(tags("workers"), group.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddedNodeIsInServiceAndRegisteredWithTheTargetGroupsAlreadyAttached() {
|
||||
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-attached"));
|
||||
service.attachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2"),
|
||||
new AutoScalingService.TrafficSourceIdentifier("lattice-service", "vpc-lattice")));
|
||||
verifyNoInteractions(targets);
|
||||
|
||||
service.addEksManagedInstance(REGION, FIRST, node());
|
||||
service.addEksManagedInstance(REGION, FIRST, node());
|
||||
|
||||
List<AsgInstance> members = service.requireGroup(REGION, FIRST).getInstances();
|
||||
assertEquals(1, members.size());
|
||||
AsgInstance member = members.getFirst();
|
||||
assertEquals(NODE, member.getInstanceId());
|
||||
assertEquals("InService", member.getLifecycleState());
|
||||
assertEquals("Healthy", member.getHealthStatus());
|
||||
assertEquals("us-east-1b", member.getAvailabilityZone());
|
||||
assertEquals("m5.large", member.getInstanceType());
|
||||
assertNull(member.getLaunchTemplateId());
|
||||
verify(targets).registerTargets(eq(REGION), eq("tg-attached"), onlyTarget(NODE));
|
||||
verify(targets).registerTargets(eq(REGION), eq("tg-source"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachingAndDetachingTargetGroupsRegistersAndDeregistersTheNode() {
|
||||
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
|
||||
service.addEksManagedInstance(REGION, FIRST, node());
|
||||
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
|
||||
service.attachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-b", null)));
|
||||
verify(targets).registerTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
|
||||
verify(targets).registerTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
|
||||
|
||||
// Attached both ways, tg-a stays attached when one of them is detached.
|
||||
service.attachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-a", "elbv2")));
|
||||
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
|
||||
verifyNoMoreInteractions(targets);
|
||||
|
||||
service.detachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-a", "elbv2"),
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-b", "elbv2")));
|
||||
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
assertEquals(List.of(NODE), memberIds(FIRST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDetachElbV2RefusesLeavesTheTargetGroupAttachedSoTheDetachCanBeSentAgain() {
|
||||
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
|
||||
service.addEksManagedInstance(REGION, FIRST, node());
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
|
||||
service.attachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-b", null)));
|
||||
AwsException refusal = new AwsException("InternalFailure", "ELBv2 could not deregister the target", 500);
|
||||
doThrow(refusal).doNothing().when(targets).deregisterTargets(eq(REGION), eq("tg-a"), anyList());
|
||||
doThrow(refusal).doNothing().when(targets).deregisterTargets(eq(REGION), eq("tg-b"), anyList());
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a")));
|
||||
assertEquals(List.of("tg-a"), service.describeLoadBalancerTargetGroups(REGION, FIRST));
|
||||
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-a"));
|
||||
assertEquals(List.of(), service.describeLoadBalancerTargetGroups(REGION, FIRST));
|
||||
|
||||
List<AutoScalingService.TrafficSourceIdentifier> trafficSource = List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-b", "elbv2"));
|
||||
assertThrows(AwsException.class, () -> service.detachTrafficSources(REGION, FIRST, trafficSource));
|
||||
assertEquals(Map.of("tg-b", "elbv2"), service.describeTrafficSources(REGION, FIRST, null));
|
||||
service.detachTrafficSources(REGION, FIRST, trafficSource);
|
||||
assertEquals(Map.of(), service.describeTrafficSources(REGION, FIRST, null));
|
||||
|
||||
verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-a"), onlyTarget(NODE));
|
||||
verify(targets, times(2)).deregisterTargets(eq(REGION), eq("tg-b"), onlyTarget(NODE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detachingATargetGroupLeavesTheSharedNodeInItWhileAnotherGroupHasItAttached() {
|
||||
groupsSharingTheNode();
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
|
||||
service.attachTrafficSources(REGION, SECOND, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-shared", "elbv2")));
|
||||
clearInvocations(targets);
|
||||
|
||||
service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
|
||||
|
||||
verifyNoInteractions(targets);
|
||||
|
||||
service.detachTrafficSources(REGION, SECOND, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-shared", "elbv2")));
|
||||
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-shared"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detachingTheNodeLeavesTheTargetGroupsAnotherGroupHoldingItHasAttached() {
|
||||
groupsSharingTheNode();
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared"));
|
||||
service.attachTrafficSources(REGION, FIRST, List.of(
|
||||
new AutoScalingService.TrafficSourceIdentifier("tg-source", "elbv2")));
|
||||
service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared"));
|
||||
clearInvocations(targets);
|
||||
|
||||
service.detachInstances(REGION, FIRST, List.of(NODE), false);
|
||||
|
||||
assertEquals(List.of(), memberIds(FIRST));
|
||||
assertEquals(List.of(NODE), memberIds(SECOND));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-first"), onlyTarget(NODE));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-source"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each group is deleted as EKS deletes it with its node group, or through DeleteAutoScalingGroup with
|
||||
* ForceDelete, which is refused without it while the group holds the node.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void deletingAGroupLeavesTheSharedNodeInTheTargetGroupsAnotherGroupHoldsAndTerminatesNothing(
|
||||
boolean throughAutoScaling) {
|
||||
groupsSharingTheNode();
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-first", "tg-shared"));
|
||||
service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared"));
|
||||
clearInvocations(targets);
|
||||
|
||||
AwsException inUse = assertThrows(AwsException.class,
|
||||
() -> service.deleteAutoScalingGroup(REGION, FIRST, false));
|
||||
assertEquals("ResourceInUse", inUse.getErrorCode());
|
||||
|
||||
delete(FIRST, throughAutoScaling);
|
||||
|
||||
assertEquals(List.of(), service.describeAutoScalingGroups(REGION, List.of(FIRST)));
|
||||
assertEquals(List.of(NODE), memberIds(SECOND));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-first"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
|
||||
delete(SECOND, throughAutoScaling);
|
||||
|
||||
assertEquals(List.of(), service.describeAutoScalingGroups(REGION, null));
|
||||
verify(targets).deregisterTargets(eq(REGION), eq("tg-shared"), onlyTarget(NODE));
|
||||
verifyNoMoreInteractions(targets);
|
||||
// The node is EKS's: deleting its groups terminates nothing.
|
||||
verifyNoInteractions(ec2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void attachingWhileAnotherGroupDetachesTheSameTargetGroupLeavesTheSharedNodeRegistered() throws Exception {
|
||||
groupsSharingTheNode();
|
||||
// The target group's registered targets, as ELB keeps them.
|
||||
Set<String> registered = ConcurrentHashMap.newKeySet();
|
||||
CountDownLatch deregistering = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
List<TargetDescription> described = invocation.getArgument(2);
|
||||
described.forEach(target -> registered.add(target.getId()));
|
||||
return null;
|
||||
}).when(targets).registerTargets(eq(REGION), eq("tg-shared"), anyList());
|
||||
doAnswer(invocation -> {
|
||||
deregistering.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS), "the parked deregistration was not released");
|
||||
List<TargetDescription> described = invocation.getArgument(2);
|
||||
described.forEach(target -> registered.remove(target.getId()));
|
||||
return null;
|
||||
}).when(targets).deregisterTargets(eq(REGION), eq("tg-shared"), anyList());
|
||||
service.attachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared"));
|
||||
assertEquals(Set.of(NODE), registered);
|
||||
|
||||
// FIRST's detach finds no other group with tg-shared and parks deregistering the node from it.
|
||||
FutureTask<Void> detach = new FutureTask<>(
|
||||
() -> service.detachLoadBalancerTargetGroups(REGION, FIRST, List.of("tg-shared")), null);
|
||||
FutureTask<Void> attach = new FutureTask<>(
|
||||
() -> service.attachLoadBalancerTargetGroups(REGION, SECOND, List.of("tg-shared")), null);
|
||||
Thread detaching = Thread.ofPlatform().daemon().start(detach);
|
||||
Thread attaching = Thread.ofPlatform().daemon().unstarted(attach);
|
||||
try {
|
||||
assertTrue(deregistering.await(5, TimeUnit.SECONDS), "the detach did not reach the deregistration");
|
||||
attaching.start();
|
||||
ThreadStates.awaitBlockedOrDone(attaching);
|
||||
assertEquals(Thread.State.BLOCKED, attaching.getState());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
detach.get(5, TimeUnit.SECONDS);
|
||||
attach.get(5, TimeUnit.SECONDS);
|
||||
detaching.join(5000);
|
||||
|
||||
assertEquals(Set.of(NODE), registered);
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsThatWouldMoveOrReplaceTheNodeAreRefusedAndTheRestAreNot() {
|
||||
service.createEksManagedGroup(REGION, FIRST, 1, 3, 2, List.of(), tags("workers"));
|
||||
service.addEksManagedInstance(REGION, FIRST, node());
|
||||
|
||||
assertRefused(() -> service.terminateInstanceInAutoScalingGroup(REGION, NODE, false));
|
||||
assertRefused(() -> service.enterStandby(REGION, FIRST, List.of(NODE), false));
|
||||
assertRefused(() -> service.exitStandby(REGION, FIRST, List.of(NODE)));
|
||||
assertRefused(() -> service.startInstanceRefresh(REGION, FIRST, new InstanceRefresh()));
|
||||
assertRefused(() -> service.setInstanceHealth(REGION, NODE, "Unhealthy", false));
|
||||
assertRefused(() -> service.attachInstances(REGION, FIRST, List.of("i-0fedcba9876543210")));
|
||||
|
||||
AutoScalingGroup group = service.requireGroup(REGION, FIRST);
|
||||
AsgInstance member = group.getInstances().getFirst();
|
||||
assertEquals(List.of(NODE), memberIds(FIRST));
|
||||
assertEquals("InService", member.getLifecycleState());
|
||||
assertEquals("Healthy", member.getHealthStatus());
|
||||
assertNull(member.getStandbyActivityId());
|
||||
assertEquals(2, group.getDesiredCapacity());
|
||||
assertEquals(List.of(), service.describeInstanceRefreshes(REGION, FIRST, null, null, null)
|
||||
.instanceRefreshes());
|
||||
|
||||
// Changes that leave the node where it is stay allowed.
|
||||
service.setInstanceHealth(REGION, NODE, "Healthy", false);
|
||||
service.setDesiredCapacity(REGION, FIRST, 3);
|
||||
service.setInstanceProtection(REGION, FIRST, List.of(NODE), true);
|
||||
|
||||
assertEquals(3, group.getDesiredCapacity());
|
||||
assertTrue(member.isProtectedFromScaleIn());
|
||||
verifyNoInteractions(targets, ec2);
|
||||
}
|
||||
|
||||
private static void assertRefused(Executable operation) {
|
||||
AwsException refused = assertThrows(AwsException.class, operation);
|
||||
assertEquals("ValidationError", refused.getErrorCode());
|
||||
assertEquals("Auto Scaling group '" + FIRST + "' is managed by Amazon EKS for a node group. Its instance is"
|
||||
+ " the cluster's node, which the cluster's node groups share.", refused.getMessage());
|
||||
assertEquals(400, refused.getHttpStatus());
|
||||
}
|
||||
|
||||
/** Deletes {@code group} as EKS does with its node group, or with DeleteAutoScalingGroup and ForceDelete. */
|
||||
private void delete(String group, boolean throughAutoScaling) {
|
||||
if (throughAutoScaling) {
|
||||
service.deleteAutoScalingGroup(REGION, group, true);
|
||||
} else {
|
||||
service.deleteEksManagedGroup(REGION, group);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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<String, String> 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<String> 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;
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.floci.aws.services.autoscaling.TargetMatchers.onlyTarget;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -51,6 +52,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AutoScalingReconcilerTest {
|
||||
@@ -83,7 +85,7 @@ class AutoScalingReconcilerTest {
|
||||
reconciler.reconcile(asg);
|
||||
assertEquals(List.of(), asg.getInstances());
|
||||
verify(elbV2Service, times(2)).deregisterTargets(eq("us-east-1"), eq("owned-target-group"),
|
||||
argThat(targets -> targets.size() == 1 && "i-cleanup".equals(targets.getFirst().getId())));
|
||||
onlyTarget("i-cleanup"));
|
||||
}
|
||||
|
||||
static Stream<Arguments> targetCleanupFailures() {
|
||||
@@ -848,6 +850,35 @@ class AutoScalingReconcilerTest {
|
||||
eq(asg.getRegion()), eq("classic-lb"), eq(List.of("i-dead")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconcileLeavesTheCapacityOfAnEksManagedGroupToEks() {
|
||||
AutoScalingService asgService = scalingService();
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
ElbV2Service elbV2Service = mock(ElbV2Service.class);
|
||||
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, elbV2Service);
|
||||
AutoScalingGroup asg = new AutoScalingGroup();
|
||||
asg.setRegion("us-east-1");
|
||||
asg.setAutoScalingGroupName("eks-workers-1a2b3c4d");
|
||||
asg.setEksManaged(true);
|
||||
asg.setMinSize(1);
|
||||
asg.setMaxSize(3);
|
||||
asg.setDesiredCapacity(2);
|
||||
asg.setTargetGroupARNs(List.of("node-target-group"));
|
||||
AsgInstance node = instance("i-0123456789abcdef0", "InService");
|
||||
asg.getInstances().add(node);
|
||||
// EC2 does not run the node's container, so the stale check of an ordinary group would drop it.
|
||||
when(ec2Service.isInstanceContainerRunning("i-0123456789abcdef0")).thenReturn(false);
|
||||
|
||||
reconciler.reconcile(asg);
|
||||
|
||||
assertEquals(List.of(node), asg.getInstances());
|
||||
assertEquals("InService", node.getLifecycleState());
|
||||
assertEquals("Healthy", node.getHealthStatus());
|
||||
assertEquals(2, asg.getDesiredCapacity());
|
||||
verifyNoInteractions(ec2Service, elbV2Service);
|
||||
verify(asgService, never()).reconcileIfPresent(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reconcilePromotesPendingAsgInstanceWhenEc2InstanceIsRunning() {
|
||||
AutoScalingService asgService = scalingService();
|
||||
|
||||
+8
-12
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.autoscaling;
|
||||
|
||||
import io.floci.aws.testing.AlbFixtures;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -22,8 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@QuarkusTest
|
||||
class AutoScalingStandbyIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "616161616161";
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=616161616161/20261028/us-east-1/autoscaling/aws4_request";
|
||||
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261028/us-east-1/autoscaling/aws4_request";
|
||||
private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/");
|
||||
private static final String ELB_AUTH = AUTH.replace("/autoscaling/", "/elasticloadbalancing/");
|
||||
private static final String GROUP_PATH = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
|
||||
@@ -73,7 +75,8 @@ class AutoScalingStandbyIntegrationTest {
|
||||
List<String> members = launched.getList(GROUP_PATH + ".Instances.member.InstanceId");
|
||||
String standby = members.get(0);
|
||||
String serving = members.get(1);
|
||||
assertEquals(List.copyOf(members).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
|
||||
assertEquals(List.copyOf(members).stream().sorted().toList(),
|
||||
AlbFixtures.targetIds(ACCOUNT, targetGroup).stream().sorted().toList());
|
||||
|
||||
// MinSize 2 leaves no room to decrement, so the client lowers it first.
|
||||
XmlPath refused = given().header("Authorization", AUTH).formParam("Action", "EnterStandby")
|
||||
@@ -113,7 +116,7 @@ class AutoScalingStandbyIntegrationTest {
|
||||
assertEquals("1", inStandby.getString(GROUP_PATH + ".DesiredCapacity"));
|
||||
assertEquals("Standby", member(inStandby, standby, "LifecycleState"));
|
||||
assertEquals("InService", member(inStandby, serving, "LifecycleState"));
|
||||
assertEquals(List.of(serving), targets(targetGroup));
|
||||
assertEquals(List.of(serving), AlbFixtures.targetIds(ACCOUNT, targetGroup));
|
||||
assertEquals(List.of(serving), classicInstances(loadBalancer));
|
||||
assertEquals("Successful", activity(name, enterActivity, "StatusCode"));
|
||||
assertEquals("The instance " + serving + " is not in Standby.", given().header("Authorization", AUTH)
|
||||
@@ -142,7 +145,8 @@ class AutoScalingStandbyIntegrationTest {
|
||||
XmlPath back = group(name);
|
||||
assertEquals("2", back.getString(GROUP_PATH + ".DesiredCapacity"));
|
||||
assertEquals(List.of("InService", "InService"), back.getList(GROUP_PATH + ".Instances.member.LifecycleState"));
|
||||
assertEquals(List.of(serving, standby).stream().sorted().toList(), targets(targetGroup).stream().sorted().toList());
|
||||
assertEquals(List.of(serving, standby).stream().sorted().toList(),
|
||||
AlbFixtures.targetIds(ACCOUNT, targetGroup).stream().sorted().toList());
|
||||
assertEquals(List.of(serving, standby).stream().sorted().toList(),
|
||||
classicInstances(loadBalancer).stream().sorted().toList());
|
||||
assertEquals("Successful", activity(name, exitActivity, "StatusCode"));
|
||||
@@ -186,14 +190,6 @@ class AutoScalingStandbyIntegrationTest {
|
||||
+ field);
|
||||
}
|
||||
|
||||
private static List<String> targets(String targetGroup) {
|
||||
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeTargetHealth")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", targetGroup)
|
||||
.post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getList("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions"
|
||||
+ ".member.Target.Id", String.class);
|
||||
}
|
||||
|
||||
private static List<String> classicInstances(String loadBalancer) {
|
||||
return given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeLoadBalancers")
|
||||
.formParam("Version", "2012-06-01").formParam("LoadBalancerNames.member.1", loadBalancer)
|
||||
|
||||
@@ -783,7 +783,9 @@ class AutoScalingStandbyTest {
|
||||
doThrow(failure).doNothing().when(elbV2).registerTargets(eq(REGION), eq(TARGET_GROUP), anyList());
|
||||
}
|
||||
|
||||
List<LogRecord> records = LogCapture.capture(AutoScalingReconciler.class,
|
||||
// Target groups are registered through AutoScalingService.registerWithTargetGroups, which logs there.
|
||||
List<LogRecord> records = LogCapture.capture(
|
||||
classicFailure ? AutoScalingReconciler.class : AutoScalingService.class,
|
||||
() -> reconciler.reconcile(group()));
|
||||
|
||||
List<LogRecord> warnings = records.stream()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package io.floci.aws.services.autoscaling;
|
||||
|
||||
import io.floci.aws.services.elbv2.model.TargetDescription;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
|
||||
/** Mockito matchers for the targets Auto Scaling registers with and deregisters from a target group. */
|
||||
final class TargetMatchers {
|
||||
|
||||
private TargetMatchers() {}
|
||||
|
||||
/** Matches a target list holding {@code instanceId} and nothing else. */
|
||||
static List<TargetDescription> onlyTarget(String instanceId) {
|
||||
return argThat(targets -> targets.size() == 1 && instanceId.equals(targets.getFirst().getId()));
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,17 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@QuarkusTest
|
||||
class EksAccessEntryIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void nodeEntryRoundTripUsesJsonAndEncodedPrincipalPaths() {
|
||||
String account = "135791357913";
|
||||
@@ -32,35 +37,35 @@ class EksAccessEntryIntegrationTest {
|
||||
try {
|
||||
Map<String, Object> request = Map.of("principalArn", principal, "type", "EC2_LINUX",
|
||||
"tags", Map.of("team", "platform"), "clientRequestToken", "retry-token");
|
||||
String arn = given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
String arn = eks(account, REGION)
|
||||
.body(request).post(path).then().statusCode(200)
|
||||
.body("accessEntry.username", equalTo("system:node:{{EC2PrivateDNSName}}"))
|
||||
.body("accessEntry.createdAt", instanceOf(Number.class))
|
||||
.body("accessEntry.tags.team", equalTo("platform"))
|
||||
.body("accessEntry.principalId", nullValue())
|
||||
.extract().path("accessEntry.accessEntryArn");
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(request).post(path).then().statusCode(200)
|
||||
.body("accessEntry.accessEntryArn", equalTo(arn));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(200).contentType(containsString("application/json"))
|
||||
.body("accessEntry.principalArn", equalTo(principal));
|
||||
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
|
||||
eks(account, REGION).get(path).then().statusCode(200)
|
||||
.body("accessEntries", contains(principal)).body("nextToken", nullValue());
|
||||
given().header("Authorization", auth("246802468024", "eks")).get(path).then().statusCode(404);
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks("246802468024", REGION).get(path).then().statusCode(404);
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(entryPath).then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(request).post(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
|
||||
eks(account, REGION).delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
createCluster(account, name, "API");
|
||||
given().header("Authorization", auth(account, "eks")).get(path).then().statusCode(200)
|
||||
eks(account, REGION).get(path).then().statusCode(200)
|
||||
.body("accessEntries", empty());
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
|
||||
eks(account, REGION).delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").then().statusCode(200);
|
||||
@@ -81,10 +86,10 @@ class EksAccessEntryIntegrationTest {
|
||||
.formParam("AssumeRolePolicyDocument", EMPTY_POLICY_DOCUMENT).post("/").then().statusCode(200);
|
||||
createCluster(account, name, "API");
|
||||
try {
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("principalArn", principal)).post("/clusters/" + name + "/access-entries")
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "cluster")))
|
||||
.post(policiesPath).then().statusCode(200).contentType(containsString("application/json"))
|
||||
@@ -95,44 +100,44 @@ class EksAccessEntryIntegrationTest {
|
||||
.body("associatedAccessPolicy.associatedAt", instanceOf(Number.class))
|
||||
.body("associatedAccessPolicy.modifiedAt", instanceOf(Number.class));
|
||||
String view = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy";
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", view, "accessScope",
|
||||
Map.of("type", "namespace", "namespaces", List.of("dev-*", "payments"))))
|
||||
.post(policiesPath).then().statusCode(200)
|
||||
.body("associatedAccessPolicy.accessScope.type", equalTo("namespace"))
|
||||
.body("associatedAccessPolicy.accessScope.namespaces", contains("dev-*", "payments"));
|
||||
given().header("Authorization", auth(account, "eks")).queryParam("associatedPolicyArn", view)
|
||||
eks(account, REGION).queryParam("associatedPolicyArn", view)
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
|
||||
.body("accessEntries", contains(principal));
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("associatedPolicyArn", "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy")
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(200)
|
||||
.body("accessEntries", empty());
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(policiesPath).then().statusCode(200)
|
||||
.body("clusterName", equalTo(name)).body("principalArn", equalTo(principal))
|
||||
.body("associatedAccessPolicies.policyArn", contains(policy, view))
|
||||
.body("associatedAccessPolicies[1].accessScope.namespaces", contains("dev-*", "payments"))
|
||||
.body("nextToken", nullValue());
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
|
||||
.then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(policiesPath + "/" + URLEncoder.encode(policy, StandardCharsets.UTF_8))
|
||||
.then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(policiesPath).then().statusCode(200).body("associatedAccessPolicies.policyArn", contains(view));
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.urlEncodingEnabled(false)
|
||||
.body(Map.of("policyArn", policy, "accessScope", Map.of("type", "namespace")))
|
||||
.post(policiesPath).then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(entryPath).then().statusCode(200);
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
|
||||
eks(account, REGION).delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "iam")).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteRole").formParam("RoleName", role).post("/").then().statusCode(200);
|
||||
@@ -146,13 +151,13 @@ class EksAccessEntryIntegrationTest {
|
||||
String name = "pagination-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
createCluster(account, name, "API");
|
||||
try {
|
||||
given().header("Authorization", auth(account, "eks")).queryParam("maxResults", maxResults)
|
||||
eks(account, REGION).queryParam("maxResults", maxResults)
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
|
||||
.contentType(containsString("application/json"))
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", not(emptyOrNullString()));
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
|
||||
eks(account, REGION).delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -163,14 +168,14 @@ class EksAccessEntryIntegrationTest {
|
||||
String account = "135791357913";
|
||||
createCluster(account, name, "CONFIG_MAP");
|
||||
try {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/clusters/" + name + "/access-entries").then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("name", name + "-invalid", "accessConfig", Map.of("authenticationMode", "invalid")))
|
||||
.post("/clusters").then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name)
|
||||
eks(account, REGION).delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -191,28 +196,28 @@ class EksAccessEntryIntegrationTest {
|
||||
try {
|
||||
for (String principal : List.of(midPath, named)) {
|
||||
String entryPath = path + "/" + URLEncoder.encode(principal, StandardCharsets.UTF_8);
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("principalArn", principal)).post(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(200).body("accessEntry.principalArn", equalTo(principal));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath + "/access-policies").then().statusCode(200)
|
||||
.body("principalArn", equalTo(principal)).body("associatedAccessPolicies", empty());
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(entryPath).then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(entryPath).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
// Unencoded, the slashes are the router's: a DELETE is a disassociate only when what follows
|
||||
// access-policies is a cluster access policy ARN, so this one still deletes the entry.
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("principalArn", midPath)).post(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.delete(path + "/" + midPath).then().statusCode(200).body(equalTo("{}"));
|
||||
given().header("Authorization", auth(account, "eks")).urlEncodingEnabled(false)
|
||||
eks(account, REGION).urlEncodingEnabled(false)
|
||||
.get(path + "/" + URLEncoder.encode(midPath, StandardCharsets.UTF_8)).then().statusCode(404);
|
||||
} finally {
|
||||
given().header("Authorization", auth(account, "eks")).delete("/clusters/" + name).then().statusCode(200);
|
||||
eks(account, REGION).delete("/clusters/" + name).then().statusCode(200);
|
||||
deleteRole(account, runner);
|
||||
deleteRole(account, "access-policies");
|
||||
}
|
||||
@@ -230,16 +235,11 @@ class EksAccessEntryIntegrationTest {
|
||||
}
|
||||
|
||||
private static void createCluster(String account, String name, String mode) {
|
||||
given().header("Authorization", auth(account, "eks")).contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster",
|
||||
"accessConfig", Map.of("authenticationMode", mode, "bootstrapClusterCreatorAdminPermissions", false)))
|
||||
.post("/clusters").then().statusCode(200)
|
||||
.body("cluster.accessConfig.authenticationMode", equalTo(mode))
|
||||
.body("cluster.accessConfig.bootstrapClusterCreatorAdminPermissions", equalTo(false));
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260916/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
@@ -14,6 +16,8 @@ import static org.hamcrest.Matchers.*;
|
||||
@QuarkusTest
|
||||
class EksAddonIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void addonLifecycleRoundTrip() {
|
||||
String account = "123456789012";
|
||||
@@ -36,8 +40,7 @@ class EksAddonIntegrationTest {
|
||||
"tags", Map.of("environment", "test")
|
||||
);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -59,8 +62,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.modifiedAt", instanceOf(Number.class));
|
||||
|
||||
// 2. Idempotent retry with same parameters and token
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -74,8 +76,7 @@ class EksAddonIntegrationTest {
|
||||
"clientRequestToken", "token-addon-1",
|
||||
"tags", Map.of("environment", "production")
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(conflictReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -88,8 +89,7 @@ class EksAddonIntegrationTest {
|
||||
"addonName", "vpc-cni",
|
||||
"clientRequestToken", "token-addon-2"
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(duplicateReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -98,7 +98,7 @@ class EksAddonIntegrationTest {
|
||||
.body("__type", equalTo("ResourceInUseException"));
|
||||
|
||||
// 5. Describe addon
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/vpc-cni")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -117,8 +117,7 @@ class EksAddonIntegrationTest {
|
||||
"serviceAccountRoleArn", updatedRoleArn,
|
||||
"configurationValues", "{\"env\":{\"ENABLE_PREFIX_DELEGATION\":\"false\"}}"
|
||||
);
|
||||
String updateId = given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
String updateId = eks(account, REGION)
|
||||
.body(updateReq)
|
||||
.post(basePath + "/vpc-cni/update")
|
||||
.then()
|
||||
@@ -130,7 +129,7 @@ class EksAddonIntegrationTest {
|
||||
.extract().path("update.id");
|
||||
|
||||
// Verify DescribeUpdate (called by Terraform aws_eks_addon waiter)
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "vpc-cni")
|
||||
.get("/clusters/" + name + "/updates/" + updateId)
|
||||
.then()
|
||||
@@ -141,7 +140,7 @@ class EksAddonIntegrationTest {
|
||||
.body("update.type", equalTo("AddonUpdate"));
|
||||
|
||||
// Verify describe shows updated values
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/vpc-cni")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -150,7 +149,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.configurationValues", equalTo("{\"env\":{\"ENABLE_PREFIX_DELEGATION\":\"false\"}}"));
|
||||
|
||||
// 7. List addons
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -159,7 +158,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addons[0]", equalTo("vpc-cni"));
|
||||
|
||||
// 8. Delete addon
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.delete(basePath + "/vpc-cni")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -168,7 +167,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.status", equalTo("DELETING"));
|
||||
|
||||
// 9. Describe after delete returns 404
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/vpc-cni")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
@@ -183,7 +182,7 @@ class EksAddonIntegrationTest {
|
||||
String account = "123456789012";
|
||||
|
||||
// Query all supported versions
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/addons/supported-versions")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -192,7 +191,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addons.addonName", hasItems("vpc-cni", "coredns", "kube-proxy", "eks-pod-identity-agent", "aws-ebs-csi-driver"));
|
||||
|
||||
// Query with addonName filter
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "vpc-cni")
|
||||
.get("/addons/supported-versions")
|
||||
.then()
|
||||
@@ -202,7 +201,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addons[0].addonVersions", not(empty()));
|
||||
|
||||
// Query with kubernetesVersion filter
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "vpc-cni")
|
||||
.queryParam("kubernetesVersion", "1.29")
|
||||
.get("/addons/supported-versions")
|
||||
@@ -213,7 +212,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addons[0].addonVersions.addonVersion", hasItem("v1.18.1-eksbuild.1"));
|
||||
|
||||
// Unknown addon name returns empty list 200
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "non-existent-addon")
|
||||
.get("/addons/supported-versions")
|
||||
.then()
|
||||
@@ -241,8 +240,7 @@ class EksAddonIntegrationTest {
|
||||
)
|
||||
);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -250,7 +248,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.podIdentityAssociations", hasSize(1));
|
||||
|
||||
// Verify the association was created under kube-system namespace
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/clusters/" + name + "/pod-identity-associations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -259,20 +257,19 @@ class EksAddonIntegrationTest {
|
||||
.body("associations[0].serviceAccount", equalTo("aws-node"));
|
||||
|
||||
// Delete addon with preserve=false (default) -> deletes association
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.delete(basePath + "/vpc-cni")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/clusters/" + name + "/pod-identity-associations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("associations", empty());
|
||||
|
||||
// Re-creating addon with same association succeeds (no ResourceInUseException)
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -293,8 +290,7 @@ class EksAddonIntegrationTest {
|
||||
createCluster(account, name, "1.40");
|
||||
try {
|
||||
// Create with no version resolves default version on cluster outside catalog range
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("addonName", "vpc-cni"))
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -304,8 +300,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.addonVersion", notNullValue());
|
||||
|
||||
// In-place update with catalog version succeeds
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("addonVersion", "v1.18.1-eksbuild.1"))
|
||||
.post(basePath + "/vpc-cni/update")
|
||||
.then()
|
||||
@@ -313,8 +308,7 @@ class EksAddonIntegrationTest {
|
||||
.body("update.status", equalTo("Successful"));
|
||||
|
||||
// In-place update with unknown version fails
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("addonVersion", "v99.0.0"))
|
||||
.post(basePath + "/vpc-cni/update")
|
||||
.then()
|
||||
@@ -333,8 +327,7 @@ class EksAddonIntegrationTest {
|
||||
|
||||
createCluster(account, name, "1.29");
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("addonName", "vpc-cni"))
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -347,7 +340,7 @@ class EksAddonIntegrationTest {
|
||||
createCluster(account, name, "1.29");
|
||||
try {
|
||||
// Addons must be empty on recreated cluster
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -362,7 +355,7 @@ class EksAddonIntegrationTest {
|
||||
String account = "123456789012";
|
||||
|
||||
// Missing cluster returns 404 JSON, not S3 NoSuchBucket XML
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/clusters/nonexistent-cluster/addons")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
@@ -373,8 +366,7 @@ class EksAddonIntegrationTest {
|
||||
String name = "addon-err-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
createCluster(account, name, "1.29");
|
||||
try {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("addonName", "unknown-addon"))
|
||||
.post("/clusters/" + name + "/addons")
|
||||
.then()
|
||||
@@ -404,8 +396,7 @@ class EksAddonIntegrationTest {
|
||||
"serviceAccountRoleArn", roleArn
|
||||
);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -420,7 +411,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.serviceAccountRoleArn", equalTo(roleArn));
|
||||
|
||||
// 2. Describe addon returns it
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/aws-ebs-csi-driver")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -430,7 +421,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addon.status", equalTo("ACTIVE"));
|
||||
|
||||
// 3. Filter describe-addon-versions by addonName
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "aws-ebs-csi-driver")
|
||||
.get("/addons/supported-versions")
|
||||
.then()
|
||||
@@ -442,7 +433,7 @@ class EksAddonIntegrationTest {
|
||||
.body("addons[0].publisher", equalTo("eks"));
|
||||
|
||||
// 4. Filter describe-addon-versions by addonName and kubernetesVersion
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("addonName", "aws-ebs-csi-driver")
|
||||
.queryParam("kubernetesVersion", "1.32")
|
||||
.get("/addons/supported-versions")
|
||||
@@ -457,11 +448,6 @@ class EksAddonIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260920/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=fake";
|
||||
}
|
||||
|
||||
private static void createRole(String account, String roleName) {
|
||||
given().header("Authorization", auth(account, "iam"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
@@ -494,8 +480,7 @@ class EksAddonIntegrationTest {
|
||||
"bootstrapClusterCreatorAdminPermissions", false
|
||||
)
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(req)
|
||||
.post("/clusters")
|
||||
.then()
|
||||
@@ -503,7 +488,7 @@ class EksAddonIntegrationTest {
|
||||
}
|
||||
|
||||
private static void deleteCluster(String account, String name) {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.delete("/clusters/" + name);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.testing.AlbFixtures;
|
||||
import io.floci.aws.testing.QueryRequests;
|
||||
import io.floci.aws.testing.TestAccounts;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A managed node group's Auto Scaling group, the one {@code DescribeNodegroup} names in
|
||||
* {@code resources.autoScalingGroups}, exists in Auto Scaling with the cluster's node in it. Attaching it to a target
|
||||
* group, as Terraform's {@code aws_autoscaling_attachment} does, registers the node there, and deleting the node
|
||||
* group deletes the group and deregisters the node.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EksNodegroupAutoScalingGroupIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SUBNET = "subnet-0123456789abcdef0";
|
||||
private static final String GROUP =
|
||||
"DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member";
|
||||
|
||||
@Inject
|
||||
EksService eksService;
|
||||
|
||||
@Inject
|
||||
EksClusterManager clusterManager;
|
||||
|
||||
private final String account = TestAccounts.randomId();
|
||||
|
||||
@Test
|
||||
void attachingTheNodeGroupsAutoScalingGroupToATargetGroupRegistersTheClusterNode() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String clusterName = "ng-asg-" + suffix;
|
||||
Cluster cluster = null;
|
||||
String targetGroupArn = null;
|
||||
try {
|
||||
eks(account, REGION).body(Map.of("name", clusterName, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200);
|
||||
cluster = eksService.findAuthenticationCluster(account, REGION, clusterName).orElseThrow();
|
||||
// EKS runs in mock mode here, so the node is registered as the k3s container's start registers it.
|
||||
clusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
|
||||
String nodeId = clusterManager.getRegisteredClusterNodeInstance(cluster).getInstanceId();
|
||||
|
||||
String groupName = eks(account, REGION).body(Map.of(
|
||||
"nodegroupName", "workers",
|
||||
"nodeRole", "arn:aws:iam::" + account + ":role/node",
|
||||
"subnets", List.of(SUBNET),
|
||||
"scalingConfig", Map.of("minSize", 1, "maxSize", 3, "desiredSize", 2)))
|
||||
.post("/clusters/" + clusterName + "/node-groups").then().statusCode(200)
|
||||
// Floci's record that it created the group is not part of the node group AWS describes.
|
||||
.body("nodegroup", not(hasKey("autoScalingGroupCreated")))
|
||||
.extract().path("nodegroup.resources.autoScalingGroups[0].name");
|
||||
eks(account, REGION).get("/clusters/" + clusterName + "/node-groups/workers").then().statusCode(200)
|
||||
.body("nodegroup", not(hasKey("autoScalingGroupCreated")));
|
||||
|
||||
XmlPath described = describeGroup(groupName);
|
||||
assertEquals(List.of(groupName), described.getList(GROUP + ".AutoScalingGroupName", String.class));
|
||||
assertEquals("1", described.getString(GROUP + ".MinSize"));
|
||||
assertEquals("3", described.getString(GROUP + ".MaxSize"));
|
||||
assertEquals("2", described.getString(GROUP + ".DesiredCapacity"));
|
||||
assertEquals(SUBNET, described.getString(GROUP + ".VPCZoneIdentifier"));
|
||||
assertEquals(List.of(nodeId), described.getList(GROUP + ".Instances.member.InstanceId", String.class));
|
||||
assertEquals("InService", described.getString(GROUP + ".Instances.member.LifecycleState"));
|
||||
assertEquals("Healthy", described.getString(GROUP + ".Instances.member.HealthStatus"));
|
||||
assertEquals(Map.of(
|
||||
"eks:cluster-name", clusterName,
|
||||
"eks:nodegroup-name", "workers",
|
||||
"k8s.io/cluster-autoscaler/enabled", "true",
|
||||
"k8s.io/cluster-autoscaler/" + clusterName, "owned"), tags(described));
|
||||
|
||||
targetGroupArn = AlbFixtures.createTargetGroup(account, clusterName, "instance", 80);
|
||||
query("autoscaling", "AttachLoadBalancerTargetGroups",
|
||||
"AutoScalingGroupName", groupName, "TargetGroupARNs.member.1", targetGroupArn)
|
||||
.post("/").then().statusCode(200);
|
||||
|
||||
assertEquals(List.of(nodeId), AlbFixtures.targetIds(account, targetGroupArn));
|
||||
|
||||
eks(account, REGION).delete("/clusters/" + clusterName + "/node-groups/workers").then().statusCode(200);
|
||||
|
||||
assertEquals(List.of(), describeGroup(groupName).getList(GROUP + ".AutoScalingGroupName", String.class));
|
||||
assertEquals(List.of(), AlbFixtures.targetIds(account, targetGroupArn));
|
||||
} finally {
|
||||
eks(account, REGION).delete("/clusters/" + clusterName + "/node-groups/workers");
|
||||
eks(account, REGION).delete("/clusters/" + clusterName);
|
||||
AlbFixtures.deleteTargetGroup(account, targetGroupArn);
|
||||
if (cluster != null) {
|
||||
clusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private RequestSpecification query(String service, String action, String... params) {
|
||||
return QueryRequests.request(account, REGION, service, action, params);
|
||||
}
|
||||
|
||||
private XmlPath describeGroup(String groupName) {
|
||||
return query("autoscaling", "DescribeAutoScalingGroups", "AutoScalingGroupNames.member.1", groupName)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static Map<String, String> tags(XmlPath described) {
|
||||
List<String> keys = described.getList(GROUP + ".Tags.member.Key", String.class);
|
||||
List<String> values = described.getList(GROUP + ".Tags.member.Value", String.class);
|
||||
assertEquals(List.of("true", "true", "true", "true"),
|
||||
described.getList(GROUP + ".Tags.member.PropagateAtLaunch", String.class));
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
tags.put(keys.get(i), values.get(i));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.autoscaling.AutoScalingService;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.testing.TestAccounts;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
|
||||
/**
|
||||
* EKS changes a node group's Auto Scaling group in the node group's account and Region, also outside a request:
|
||||
* when the cluster's node registers, when the startup backfill creates the group, and when a cluster is deleted
|
||||
* from Floci's own code. Auto Scaling reads the account and Region from the request scope, so each call is
|
||||
* recorded with the ones it was made in.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EksNodegroupAutoScalingGroupScopeIntegrationTest {
|
||||
|
||||
private static final String REGION = "eu-west-1";
|
||||
|
||||
@InjectMock
|
||||
AutoScalingService autoScaling;
|
||||
|
||||
@Inject
|
||||
EksService eksService;
|
||||
|
||||
@Inject
|
||||
EksClusterManager clusterManager;
|
||||
|
||||
@Inject
|
||||
RegionResolver regionResolver;
|
||||
|
||||
/** An Auto Scaling call EKS made, with the account and Region it was made in. */
|
||||
private record Call(String operation, String groupName, String accountId, String region) {}
|
||||
|
||||
@Test
|
||||
void everyCallToANodeGroupsAutoScalingGroupIsInTheNodeGroupsAccountAndRegion() {
|
||||
String account = TestAccounts.randomId();
|
||||
String clusterName = "ng-asg-scope-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
List<Call> calls = new CopyOnWriteArrayList<>();
|
||||
doAnswer(invocation -> record(calls, "create", invocation.getArgument(1)))
|
||||
.when(autoScaling).createEksManagedGroup(any(), any(), anyInt(), anyInt(), anyInt(), any(), any());
|
||||
doAnswer(invocation -> record(calls, "add", invocation.getArgument(1)))
|
||||
.when(autoScaling).addEksManagedInstance(any(), any(), any());
|
||||
doAnswer(invocation -> record(calls, "delete", invocation.getArgument(1)))
|
||||
.when(autoScaling).deleteEksManagedGroup(any(), any());
|
||||
Cluster cluster = null;
|
||||
try {
|
||||
eks(account, REGION).body(Map.of("name", clusterName, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200);
|
||||
cluster = eksService.findAuthenticationCluster(account, REGION, clusterName).orElseThrow();
|
||||
String first = createNodeGroup(account, clusterName, "first");
|
||||
String second = createNodeGroup(account, clusterName, "second");
|
||||
Set<String> groups = Set.of(first, second);
|
||||
|
||||
assertEquals(List.of(new Call("create", first, account, REGION), new Call("create", second, account, REGION)),
|
||||
callsTo(calls, groups));
|
||||
|
||||
// The node registers outside any request, as it does when its container starts in the background.
|
||||
calls.clear();
|
||||
clusterManager.registerClusterNodeInstance(cluster, "mock-container-id");
|
||||
|
||||
assertEquals(Set.of(new Call("add", first, account, REGION), new Call("add", second, account, REGION)),
|
||||
Set.copyOf(callsTo(calls, groups)));
|
||||
|
||||
// The startup backfill runs outside any request too, for a node group stored without its group.
|
||||
calls.clear();
|
||||
RequestScopes.callAs(account, REGION, () -> eksService.describeNodeGroup(clusterName, "first"))
|
||||
.setAutoScalingGroupCreated(false);
|
||||
eksService.restoreNodeGroupAutoScalingGroups();
|
||||
|
||||
assertEquals(List.of(new Call("create", first, account, REGION), new Call("add", first, account, REGION)),
|
||||
callsTo(calls, groups));
|
||||
assertTrue(RequestScopes.callAs(account, REGION,
|
||||
() -> eksService.describeNodeGroup(clusterName, "first")).isAutoScalingGroupCreated());
|
||||
|
||||
// Floci's own code deletes a cluster outside any request.
|
||||
calls.clear();
|
||||
eksService.deleteClusterForAccount(account, clusterName);
|
||||
|
||||
assertEquals(Set.of(new Call("delete", first, account, REGION), new Call("delete", second, account, REGION)),
|
||||
Set.copyOf(callsTo(calls, groups)));
|
||||
} finally {
|
||||
if (eksService.findAuthenticationCluster(account, REGION, clusterName).isPresent()) {
|
||||
eksService.deleteClusterForAccount(account, clusterName);
|
||||
}
|
||||
if (cluster != null) {
|
||||
clusterManager.unregisterMetadataEndpoint(cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Object record(List<Call> calls, String operation, String groupName) {
|
||||
calls.add(new Call(operation, groupName, regionResolver.getAccountId(), regionResolver.getRegion()));
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The calls to this test's groups: the backfill also visits every other cluster the application holds. */
|
||||
private static List<Call> callsTo(List<Call> calls, Set<String> groups) {
|
||||
return calls.stream().filter(call -> groups.contains(call.groupName())).toList();
|
||||
}
|
||||
|
||||
private static String createNodeGroup(String account, String clusterName, String nodegroupName) {
|
||||
return eks(account, REGION).body(Map.of(
|
||||
"nodegroupName", nodegroupName,
|
||||
"nodeRole", "arn:aws:iam::" + account + ":role/node",
|
||||
"subnets", List.of("subnet-0123456789abcdef0")))
|
||||
.post("/clusters/" + clusterName + "/node-groups").then().statusCode(200)
|
||||
.extract().path("nodegroup.resources.autoScalingGroups[0].name");
|
||||
}
|
||||
}
|
||||
+26
-36
@@ -6,6 +6,8 @@ import org.junit.jupiter.api.Test;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
@@ -13,6 +15,8 @@ import static org.hamcrest.Matchers.*;
|
||||
@QuarkusTest
|
||||
class EksPodIdentityAssociationIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void associationLifecycleRoundTrip() {
|
||||
String account = "123456789012";
|
||||
@@ -34,8 +38,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
"tags", Map.of("env", "test")
|
||||
);
|
||||
|
||||
String associationId = given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
String associationId = eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -53,8 +56,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.extract().path("association.associationId");
|
||||
|
||||
// 2. Idempotent retry with same parameters and token
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(createReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -68,8 +70,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
"roleArn", roleArn,
|
||||
"clientRequestToken", "token-abc"
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(conflictReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -82,8 +83,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
"serviceAccount", "my-service-account",
|
||||
"roleArn", roleArn
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(duplicateReq)
|
||||
.post(basePath)
|
||||
.then()
|
||||
@@ -91,7 +91,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("__type", equalTo("ResourceInUseException"));
|
||||
|
||||
// 5. Describe association
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -109,8 +109,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
"roleArn", updatedRoleArn,
|
||||
"disableSessionTags", true
|
||||
);
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(updateReq)
|
||||
.post(basePath + "/" + associationId)
|
||||
.then()
|
||||
@@ -121,7 +120,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("association.disableSessionTags", equalTo(true));
|
||||
|
||||
// 7. List associations
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -132,7 +131,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("associations[0].serviceAccount", equalTo("my-service-account"));
|
||||
|
||||
// List with filter matching
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("namespace", "default")
|
||||
.get(basePath)
|
||||
.then()
|
||||
@@ -140,7 +139,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("associations", hasSize(1));
|
||||
|
||||
// List with filter non-matching
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("namespace", "other-namespace")
|
||||
.get(basePath)
|
||||
.then()
|
||||
@@ -148,7 +147,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("associations", hasSize(0));
|
||||
|
||||
// 8. Delete association
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.delete(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -156,7 +155,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("association.associationId", equalTo(associationId));
|
||||
|
||||
// 9. Describe after delete returns 404
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath + "/" + associationId)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
@@ -170,7 +169,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
void routeCollisionsAndMissingCluster() {
|
||||
String account = "123456789012";
|
||||
// Missing cluster returns 404 JSON, not S3 NoSuchBucket XML
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get("/clusters/nonexistent-cluster/pod-identity-associations")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
@@ -191,18 +190,16 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
|
||||
try {
|
||||
// Create two associations
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("namespace", "ns1", "serviceAccount", "sa1", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("namespace", "ns2", "serviceAccount", "sa2", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
// maxResults = 1 returns first item and nextToken
|
||||
String nextToken = given().header("Authorization", auth(account, "eks"))
|
||||
String nextToken = eks(account, REGION)
|
||||
.queryParam("maxResults", "1")
|
||||
.get(basePath)
|
||||
.then()
|
||||
@@ -212,7 +209,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.extract().path("nextToken");
|
||||
|
||||
// Fetch next page
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("maxResults", "1")
|
||||
.queryParam("nextToken", nextToken)
|
||||
.get(basePath)
|
||||
@@ -222,14 +219,14 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
.body("nextToken", nullValue());
|
||||
|
||||
// Invalid maxResults returns 400 InvalidParameterException
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("maxResults", "0")
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"));
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.queryParam("maxResults", "invalid")
|
||||
.get(basePath)
|
||||
.then()
|
||||
@@ -251,8 +248,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
createRole(account, roleName);
|
||||
createCluster(account, name);
|
||||
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("namespace", "default", "serviceAccount", "sa", "roleArn", roleArn))
|
||||
.post(basePath).then().statusCode(200);
|
||||
|
||||
@@ -263,7 +259,7 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
createCluster(account, name);
|
||||
try {
|
||||
// Associations must be empty
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.get(basePath)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
@@ -284,19 +280,13 @@ class EksPodIdentityAssociationIntegrationTest {
|
||||
}
|
||||
|
||||
private static void createCluster(String account, String name) {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
.contentType("application/json")
|
||||
eks(account, REGION)
|
||||
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + account + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteCluster(String account, String name) {
|
||||
given().header("Authorization", auth(account, "eks"))
|
||||
eks(account, REGION)
|
||||
.delete("/clusters/" + name).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account
|
||||
+ "/20260920/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static io.floci.aws.testing.EksRequests.eks;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
@@ -28,27 +28,27 @@ class EksRegionScopingIntegrationTest {
|
||||
|
||||
@Test
|
||||
void clusterIsOnlyVisibleInTheRegionItWasCreatedIn() {
|
||||
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
|
||||
eks(ACCOUNT, "eu-west-1")
|
||||
.body(Map.of("name", CLUSTER, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200)
|
||||
.body("cluster.arn", equalTo("arn:aws:eks:eu-west-1:" + ACCOUNT + ":cluster/" + CLUSTER));
|
||||
|
||||
try {
|
||||
given().header("Authorization", auth("eu-west-1")).get("/clusters")
|
||||
eks(ACCOUNT, "eu-west-1").get("/clusters")
|
||||
.then().statusCode(200).body("clusters", hasItem(CLUSTER));
|
||||
given().header("Authorization", auth("eu-west-1")).get("/clusters/" + CLUSTER)
|
||||
eks(ACCOUNT, "eu-west-1").get("/clusters/" + CLUSTER)
|
||||
.then().statusCode(200).body("cluster.name", equalTo(CLUSTER));
|
||||
|
||||
given().header("Authorization", auth("eu-central-1")).get("/clusters")
|
||||
eks(ACCOUNT, "eu-central-1").get("/clusters")
|
||||
.then().statusCode(200).body("clusters", not(hasItem(CLUSTER)));
|
||||
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + CLUSTER)
|
||||
eks(ACCOUNT, "eu-central-1").get("/clusters/" + CLUSTER)
|
||||
.then().statusCode(404);
|
||||
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + CLUSTER + "/node-groups")
|
||||
eks(ACCOUNT, "eu-central-1").get("/clusters/" + CLUSTER + "/node-groups")
|
||||
.then().statusCode(404);
|
||||
given().header("Authorization", auth("eu-central-1")).delete("/clusters/" + CLUSTER)
|
||||
eks(ACCOUNT, "eu-central-1").delete("/clusters/" + CLUSTER)
|
||||
.then().statusCode(404);
|
||||
} finally {
|
||||
given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + CLUSTER)
|
||||
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + CLUSTER)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ class EksRegionScopingIntegrationTest {
|
||||
String name = "region-shared";
|
||||
Map<String, String> issuers = new HashMap<>();
|
||||
for (String region : new String[] {"eu-west-1", "eu-central-1"}) {
|
||||
issuers.put(region, given().header("Authorization", auth(region)).contentType("application/json")
|
||||
issuers.put(region, eks(ACCOUNT, region)
|
||||
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(200)
|
||||
.body("cluster.arn", equalTo("arn:aws:eks:" + region + ":" + ACCOUNT + ":cluster/" + name))
|
||||
@@ -67,33 +67,33 @@ class EksRegionScopingIntegrationTest {
|
||||
}
|
||||
|
||||
try {
|
||||
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
|
||||
eks(ACCOUNT, "eu-west-1")
|
||||
.body(Map.of("name", name, "roleArn", "arn:aws:iam::" + ACCOUNT + ":role/cluster"))
|
||||
.post("/clusters").then().statusCode(409)
|
||||
.body("__type", equalTo("ResourceInUseException"));
|
||||
|
||||
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
|
||||
eks(ACCOUNT, "eu-west-1")
|
||||
.body(Map.of("nodegroupName", "workers",
|
||||
"nodeRole", "arn:aws:iam::" + ACCOUNT + ":role/node",
|
||||
"subnets", List.of("subnet-0123456789abcdef0")))
|
||||
.post("/clusters/" + name + "/node-groups").then().statusCode(200);
|
||||
given().header("Authorization", auth("eu-west-1")).get("/clusters/" + name + "/node-groups")
|
||||
eks(ACCOUNT, "eu-west-1").get("/clusters/" + name + "/node-groups")
|
||||
.then().statusCode(200).body("nodegroups", hasItem("workers"));
|
||||
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + name + "/node-groups")
|
||||
eks(ACCOUNT, "eu-central-1").get("/clusters/" + name + "/node-groups")
|
||||
.then().statusCode(200).body("nodegroups", empty());
|
||||
|
||||
// OIDC discovery resolves the Region it is asked for, and advertises a key route that
|
||||
// names it, since a verifier follows that route without the discovery request's context.
|
||||
String westKeyId = null;
|
||||
for (String region : new String[] {"eu-west-1", "eu-central-1"}) {
|
||||
String jwksUri = given().header("Authorization", auth(region))
|
||||
String jwksUri = eks(ACCOUNT, region)
|
||||
.queryParam("region", region)
|
||||
.get("/_floci/eks/clusters/" + name + "/oidc/.well-known/openid-configuration")
|
||||
.then().statusCode(200)
|
||||
.body("issuer", equalTo(issuers.get(region)))
|
||||
.extract().path("jwks_uri");
|
||||
assertTrue(jwksUri.endsWith("/oidc/keys?region=" + region), jwksUri);
|
||||
String keyId = given().header("Authorization", auth(region))
|
||||
String keyId = eks(ACCOUNT, region)
|
||||
.queryParam("region", region)
|
||||
.get("/_floci/eks/clusters/" + name + "/oidc/keys")
|
||||
.then().statusCode(200).extract().path("keys[0].kid");
|
||||
@@ -107,33 +107,28 @@ class EksRegionScopingIntegrationTest {
|
||||
// Minting takes the same ?region=, which wins over the request's Region, so an
|
||||
// unsigned caller can pick either cluster.
|
||||
for (String region : new String[] {"eu-west-1", "eu-central-1"}) {
|
||||
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
|
||||
eks(ACCOUNT, "eu-west-1")
|
||||
.queryParam("region", region)
|
||||
.body(Map.of("namespace", "default", "serviceAccount", "app"))
|
||||
.post("/_floci/eks/clusters/" + name + "/oidc-token")
|
||||
.then().statusCode(200)
|
||||
.body("issuer", equalTo(issuers.get(region)));
|
||||
}
|
||||
given().header("Authorization", auth("eu-west-1")).contentType("application/json")
|
||||
eks(ACCOUNT, "eu-west-1")
|
||||
.queryParam("region", "ap-south-1")
|
||||
.body(Map.of("namespace", "default", "serviceAccount", "app"))
|
||||
.post("/_floci/eks/clusters/" + name + "/oidc-token")
|
||||
.then().statusCode(404);
|
||||
|
||||
given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + name)
|
||||
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + name)
|
||||
.then().statusCode(200);
|
||||
given().header("Authorization", auth("eu-central-1")).get("/clusters/" + name)
|
||||
eks(ACCOUNT, "eu-central-1").get("/clusters/" + name)
|
||||
.then().statusCode(200)
|
||||
.body("cluster.arn", equalTo("arn:aws:eks:eu-central-1:" + ACCOUNT + ":cluster/" + name))
|
||||
.body("cluster", not(hasKey("dockerNameRegion")));
|
||||
} finally {
|
||||
given().header("Authorization", auth("eu-west-1")).delete("/clusters/" + name);
|
||||
given().header("Authorization", auth("eu-central-1")).delete("/clusters/" + name);
|
||||
eks(ACCOUNT, "eu-west-1").delete("/clusters/" + name);
|
||||
eks(ACCOUNT, "eu-central-1").delete("/clusters/" + name);
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20261110/" + region
|
||||
+ "/eks/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,13 @@ import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.core.storage.PersistentStorage;
|
||||
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.AmiImageResolver;
|
||||
import io.floci.aws.services.ec2.Ec2ContainerManager;
|
||||
import io.floci.aws.services.ec2.Ec2ImageCatalog;
|
||||
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.LaunchTemplate;
|
||||
import io.floci.aws.services.ec2.model.LaunchTemplateData;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
@@ -47,6 +49,8 @@ import io.floci.aws.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
@@ -67,6 +71,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -74,11 +79,14 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
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;
|
||||
|
||||
class EksServiceTest {
|
||||
@@ -1258,6 +1266,192 @@ class EksServiceTest {
|
||||
assertEquals(List.of("nodegroup-b"), eksService.listNodeGroups("my-eks-cluster"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeGroupGetsTheAutoScalingGroupItReportsHoldingTheClusterNode() {
|
||||
EksClusterManager clusterManager = mock(EksClusterManager.class);
|
||||
AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
EksService service = serviceWithAutoScaling(clusterManager, autoScaling);
|
||||
service.createCluster(createTestClusterRequest("asg-cluster"));
|
||||
Instance node = clusterNode("i-0123456789abcdef0", "asg-cluster");
|
||||
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
|
||||
NodegroupScalingConfig scalingConfig = new NodegroupScalingConfig();
|
||||
scalingConfig.setMinSize(1);
|
||||
scalingConfig.setMaxSize(3);
|
||||
scalingConfig.setDesiredSize(2);
|
||||
CreateNodeGroupRequest request = nodeGroupRequest("workers");
|
||||
request.setScalingConfig(scalingConfig);
|
||||
|
||||
String groupName = reportedAutoScalingGroup(service.createNodeGroup("asg-cluster", request));
|
||||
|
||||
InOrder order = inOrder(autoScaling);
|
||||
order.verify(autoScaling).createEksManagedGroup("us-east-1", groupName, 1, 3, 2,
|
||||
List.of("subnet-0e2907431c9988b72", "subnet-04ad87f71c6e5ab4d"),
|
||||
nodeGroupAutoScalingTags("asg-cluster", "workers"));
|
||||
order.verify(autoScaling).addEksManagedInstance("us-east-1", groupName, node);
|
||||
verifyNoMoreInteractions(autoScaling);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeRegisteringAfterItsNodeGroupsJoinsEachOfTheirAutoScalingGroups() {
|
||||
EksClusterManager clusterManager = mock(EksClusterManager.class);
|
||||
AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
EksService service = serviceWithAutoScaling(clusterManager, autoScaling);
|
||||
service.init();
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Consumer<Instance>> listener = ArgumentCaptor.forClass(Consumer.class);
|
||||
verify(clusterManager).addNodeRegistrationListener(listener.capture());
|
||||
service.createCluster(createTestClusterRequest("late-node"));
|
||||
String first = reportedAutoScalingGroup(service.createNodeGroup("late-node", nodeGroupRequest("first")));
|
||||
String second = reportedAutoScalingGroup(service.createNodeGroup("late-node", nodeGroupRequest("second")));
|
||||
Instance node = clusterNode("i-0123456789abcdef0", "late-node");
|
||||
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
|
||||
|
||||
// An EC2 instance joining the cluster is in no managed node group, even tagged with the cluster's name.
|
||||
listener.getValue().accept(clusterNode("i-0fedcba9876543210", "late-node"));
|
||||
// Only the cluster the node names, in the node's Region, is read.
|
||||
listener.getValue().accept(clusterNode("i-0123456789abcdef0", "other-cluster"));
|
||||
Instance inAnotherRegion = clusterNode("i-0123456789abcdef0", "late-node");
|
||||
inAnotherRegion.setRegion("eu-west-1");
|
||||
listener.getValue().accept(inAnotherRegion);
|
||||
verify(autoScaling, never()).addEksManagedInstance(any(), any(), any());
|
||||
|
||||
// A group that fails to take the node does not keep it from the other node groups' groups.
|
||||
doThrow(new IllegalStateException("group storage write failed"))
|
||||
.when(autoScaling).addEksManagedInstance("us-east-1", first, node);
|
||||
listener.getValue().accept(node);
|
||||
|
||||
verify(autoScaling).addEksManagedInstance("us-east-1", first, node);
|
||||
verify(autoScaling).addEksManagedInstance("us-east-1", second, node);
|
||||
verify(autoScaling, times(2)).addEksManagedInstance(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingANodeGroupOrItsClusterDeletesTheirAutoScalingGroups() {
|
||||
AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
EksService service = serviceWithAutoScaling(mock(EksClusterManager.class), autoScaling);
|
||||
service.createCluster(createTestClusterRequest("asg-delete"));
|
||||
String first = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("first")));
|
||||
String second = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("second")));
|
||||
String third = reportedAutoScalingGroup(service.createNodeGroup("asg-delete", nodeGroupRequest("third")));
|
||||
|
||||
service.deleteNodeGroup("asg-delete", "first");
|
||||
|
||||
verify(autoScaling).deleteEksManagedGroup("us-east-1", first);
|
||||
verify(autoScaling, times(1)).deleteEksManagedGroup(any(), any());
|
||||
|
||||
service.deleteCluster("asg-delete");
|
||||
|
||||
verify(autoScaling).deleteEksManagedGroup("us-east-1", second);
|
||||
verify(autoScaling).deleteEksManagedGroup("us-east-1", third);
|
||||
verify(autoScaling, times(3)).deleteEksManagedGroup(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAutoScalingGroupThatFailsToDeleteLeavesTheNodeGroupAndClusterDeletionsToFinish() {
|
||||
AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
EksService service = serviceWithAutoScaling(mock(EksClusterManager.class), autoScaling);
|
||||
service.createCluster(createTestClusterRequest("asg-delete-failure"));
|
||||
String first = reportedAutoScalingGroup(
|
||||
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("first")));
|
||||
String second = reportedAutoScalingGroup(
|
||||
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("second")));
|
||||
String third = reportedAutoScalingGroup(
|
||||
service.createNodeGroup("asg-delete-failure", nodeGroupRequest("third")));
|
||||
RuntimeException failure = new IllegalStateException("target group storage write failed");
|
||||
doThrow(failure).when(autoScaling).deleteEksManagedGroup("us-east-1", first);
|
||||
doThrow(failure).when(autoScaling).deleteEksManagedGroup("us-east-1", second);
|
||||
|
||||
service.deleteNodeGroup("asg-delete-failure", "first");
|
||||
|
||||
assertEquals(List.of("second", "third"), service.listNodeGroups("asg-delete-failure").stream().sorted().toList());
|
||||
|
||||
service.deleteCluster("asg-delete-failure");
|
||||
|
||||
verify(autoScaling).deleteEksManagedGroup("us-east-1", second);
|
||||
verify(autoScaling).deleteEksManagedGroup("us-east-1", third);
|
||||
assertThrows(AwsException.class, () -> service.describeCluster("asg-delete-failure"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNodeGroupStoredBeforeTheseGroupsGetsItsGroupAtOneStartOnly(@TempDir Path directory) {
|
||||
// A node group stored by a Floci that did not keep these groups.
|
||||
EksService legacy = persistentEksService(directory);
|
||||
legacy.init();
|
||||
legacy.createCluster(createTestClusterRequest("backfill-once"));
|
||||
String legacyGroup = reportedAutoScalingGroup(
|
||||
legacy.createNodeGroup("backfill-once", nodeGroupRequest("legacy")));
|
||||
AutoScalingService firstStart = mock(AutoScalingService.class);
|
||||
|
||||
EksService upgraded = persistentEksService(directory, ec2Service, null, firstStart);
|
||||
upgraded.init();
|
||||
String createdGroup = reportedAutoScalingGroup(
|
||||
upgraded.createNodeGroup("backfill-once", nodeGroupRequest("created")));
|
||||
|
||||
List<String> subnets = List.of("subnet-0e2907431c9988b72", "subnet-04ad87f71c6e5ab4d");
|
||||
verify(firstStart).createEksManagedGroup("us-east-1", legacyGroup, 1, 1, 1, subnets,
|
||||
nodeGroupAutoScalingTags("backfill-once", "legacy"));
|
||||
verify(firstStart).createEksManagedGroup("us-east-1", createdGroup, 1, 1, 1, subnets,
|
||||
nodeGroupAutoScalingTags("backfill-once", "created"));
|
||||
|
||||
// Both groups were created, so a group deleted through Auto Scaling since is not created again.
|
||||
AutoScalingService secondStart = mock(AutoScalingService.class);
|
||||
persistentEksService(directory, ec2Service, null, secondStart).init();
|
||||
|
||||
verifyNoInteractions(secondStart);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestartedNodeJoinsTheGroupItsNodeGroupAlreadyHas(@TempDir Path directory) {
|
||||
EksService before = persistentEksService(directory, ec2Service, null, mock(AutoScalingService.class));
|
||||
before.init();
|
||||
before.createCluster(createTestClusterRequest("restarted-node"));
|
||||
String groupName = reportedAutoScalingGroup(
|
||||
before.createNodeGroup("restarted-node", nodeGroupRequest("workers")));
|
||||
EksClusterManager clusterManager = mock(EksClusterManager.class);
|
||||
AutoScalingService autoScaling = mock(AutoScalingService.class);
|
||||
EksService after = persistentEksService(directory, null, clusterManager, autoScaling);
|
||||
|
||||
after.init();
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Consumer<Instance>> listener = ArgumentCaptor.forClass(Consumer.class);
|
||||
verify(clusterManager).addNodeRegistrationListener(listener.capture());
|
||||
Instance node = clusterNode("i-0123456789abcdef0", "restarted-node");
|
||||
when(clusterManager.getRegisteredClusterNodeInstance(any())).thenReturn(node);
|
||||
listener.getValue().accept(node);
|
||||
|
||||
verify(autoScaling).addEksManagedInstance("us-east-1", groupName, node);
|
||||
verifyNoMoreInteractions(autoScaling);
|
||||
}
|
||||
|
||||
private EksService serviceWithAutoScaling(EksClusterManager clusterManager, AutoScalingService autoScaling) {
|
||||
return new EksService(storageFactory, testConfig(true), regionResolver, clusterManager, null,
|
||||
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class),
|
||||
mock(EksPodIdentityAssociationService.class), null, autoScaling);
|
||||
}
|
||||
|
||||
/** The tags EKS puts on a node group's Auto Scaling group. */
|
||||
private static Map<String, String> nodeGroupAutoScalingTags(String clusterName, String nodegroupName) {
|
||||
return Map.of(
|
||||
"eks:cluster-name", clusterName,
|
||||
"eks:nodegroup-name", nodegroupName,
|
||||
"k8s.io/cluster-autoscaler/enabled", "true",
|
||||
"k8s.io/cluster-autoscaler/" + clusterName, "owned");
|
||||
}
|
||||
|
||||
private static String reportedAutoScalingGroup(Nodegroup nodeGroup) {
|
||||
List<?> autoScalingGroups = (List<?>) ((Map<?, ?>) nodeGroup.getResources()).get("autoScalingGroups");
|
||||
return (String) ((Map<?, ?>) autoScalingGroups.getFirst()).get("name");
|
||||
}
|
||||
|
||||
/** An instance in us-east-1 tagged, as a cluster's node is, with its cluster's name. */
|
||||
private static Instance clusterNode(String instanceId, String clusterName) {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(instanceId);
|
||||
instance.setRegion("us-east-1");
|
||||
instance.setTags(List.of(new Tag("eks:cluster-name", clusterName)));
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNodeGroupRecordsLabelsAndTaints() {
|
||||
createTestCluster("metadata-cluster");
|
||||
@@ -2788,6 +2982,11 @@ class EksServiceTest {
|
||||
}
|
||||
|
||||
private EksService persistentEksService(Path directory, Ec2Service ec2) {
|
||||
return persistentEksService(directory, ec2, null, null);
|
||||
}
|
||||
|
||||
private EksService persistentEksService(Path directory, Ec2Service ec2, EksClusterManager clusterManager,
|
||||
AutoScalingService autoScaling) {
|
||||
StorageFactory storageFactory = new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
|
||||
@@ -2799,9 +2998,9 @@ class EksServiceTest {
|
||||
}
|
||||
};
|
||||
return new EksService(storageFactory, testConfig(true),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, ec2,
|
||||
new RegionResolver("us-east-1", "000000000000"), clusterManager, ec2,
|
||||
new EksOidcService(storageFactory, new ObjectMapper()), mock(EksAccessEntryService.class),
|
||||
mock(EksPodIdentityAssociationService.class));
|
||||
mock(EksPodIdentityAssociationService.class), null, autoScaling);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.testing;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -93,6 +94,22 @@ public final class AlbFixtures {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
/** The ids of the targets registered with {@code targetGroupArn}, in the order DescribeTargetHealth lists them. */
|
||||
public static List<String> targetIds(String account, String targetGroupArn) {
|
||||
return given()
|
||||
.formParam("Action", "DescribeTargetHealth")
|
||||
.formParam("TargetGroupArn", targetGroupArn)
|
||||
.header("Authorization", auth(account))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.xmlPath()
|
||||
.getList("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member"
|
||||
+ ".Target.Id", String.class);
|
||||
}
|
||||
|
||||
/** An HTTP listener on {@code port} that forwards every request to {@code targetGroupArn}. */
|
||||
public static String createListener(String loadBalancerArn, String targetGroupArn, int port) {
|
||||
return createListener(DEFAULT_ACCOUNT, loadBalancerArn, targetGroupArn, port);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** One EKS REST JSON request, signed for {@code account} in {@code region}. */
|
||||
public final class EksRequests {
|
||||
|
||||
private EksRequests() {}
|
||||
|
||||
public static RequestSpecification eks(String account, String region) {
|
||||
return given().header("Authorization", EnforcementFixtures.auth(account, region, "eks"))
|
||||
.contentType("application/json");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user