diff --git a/docs/services/eks.md b/docs/services/eks.md index 8b1d8a6592..95a9e1c371 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -470,12 +470,13 @@ launches nodes on AWS. Floci checks every 10 seconds. - **Pool.** The pod goes to the first NodePool, by `weight` then name, with an instance type the pool's requirements allow, whose node the pod's `nodeSelector`, required node affinity and tolerations accept, and that fits its CPU and - memory requests. A type whose node would take the pool's nodes, joined or joining, past its `limits` (`cpu`, + memory requests in what a node of the type offers pods: its CPU less the EKS AMI's kube reservation tiers, its + memory less 11 MiB per pod plus 255 MiB and the 100 MiB eviction threshold, as Karpenter sizes it. A type whose node would take the pool's nodes, joined or joining, past its `limits` (`cpu`, `memory`, `nodes`) is left out, as AWS stopped at two 2-vCPU nodes for a pool limited to 4 vCPUs, so a pod such a pool can't take goes to the next pool, or waits. A requirement on a label Floci doesn't give its nodes (a GPU count, say) is left out. A pod one of the pool's schedulable nodes has room for, joined or still joining, waits for the scheduler instead. A joined node's room is its `status.allocatable` CPU, memory and pods less its pods' requests (sidecars included); one still - joining has its instance type's whole size and 110 pods. A cordoned node, one with a taint of its own the pod + joining has what its instance type offers pods and 110 pods. A cordoned node, one with a taint of its own the pod doesn't tolerate, or one with a pod that the pod's required anti-affinity on `kubernetes.io/hostname` keeps it apart from (either pod's, counting pods placed on it in the same pass) has none; anti-affinity on another topology key isn't modelled; the taints a node carries while it starts (`node.kubernetes.io/not-ready` and the @@ -497,7 +498,11 @@ launches nodes on AWS. Floci checks every 10 seconds. the node's `certificateAuthority` carries both the cluster's CA and the client CA k3s signs the API server's kubelet certificate with (EKS's one CA signs both), and Floci approves the kubelet's `kubernetes.io/kubelet-serving` CertificateSigningRequest when it names only that node and its instance's ID, - private DNS name or private address, as EKS approves it. Otherwise the instance joins with the Ready node Floci registers and keeps Ready for + private DNS name or private address, as EKS approves it. Such a node offers its instance type's CPU and memory, as + an Auto Mode node does: a guest shares the Docker host's kernel, so its kubelet sees the host's CPUs and memory, + and the node's `NodeConfig` reserves the difference as `systemReserved` (Floci's own setting, read from the Docker + host, less what nodeadm's CPU tiers take from the host's cores beyond the type's own; none when the host is no + bigger than the type), with nodeadm's usual reservations on top. Otherwise the instance joins with the Ready node Floci registers and keeps Ready for every joined instance (see [Node metadata](#node-metadata-and-aws-outcome-alignment)), and pods are scheduled to it but don't start. - **Node.** The instance joins the cluster through its EKS bootstrap user data (a nodeadm `NodeConfig`), as any diff --git a/src/main/java/io/floci/aws/services/eks/EksAutoModeCompute.java b/src/main/java/io/floci/aws/services/eks/EksAutoModeCompute.java index 9cf0f1d62b..35f60a1c39 100644 --- a/src/main/java/io/floci/aws/services/eks/EksAutoModeCompute.java +++ b/src/main/java/io/floci/aws/services/eks/EksAutoModeCompute.java @@ -269,13 +269,14 @@ public class EksAutoModeCompute implements EksAutoModeCleanup { }); } boolean schedulable = node == null || !node.path("spec").path("unschedulable").asBoolean(false); - // A joined node offers what its kubelet says is allocatable, less what it reserves; one joining, its - // instance type's whole size. + // A joined node offers what its kubelet says is allocatable, less what it reserves; one joining, what a + // node of its instance type offers pods. JsonNode allocatable = node == null ? MAPPER.createObjectNode() : node.path("status").path("allocatable"); + EksNodeCapacity.Allocatable offered = EksNodeCapacity.allocatable(type.get()); long cpu = allocatable.hasNonNull("cpu") ? EksAutoModeNodes.cpuMillis(allocatable.path("cpu").asText()) - : type.get().vcpu * 1000L; + : offered.cpuMillis(); long memory = allocatable.hasNonNull("memory") ? EksAutoModeNodes.bytes(allocatable.path("memory").asText()) - : type.get().memoryMib * 1024L * 1024L; + : offered.memoryBytes(); int podSlots = allocatable.path("pods").asInt(EksAutoModeNodes.MAX_PODS); if (node == null) { // A node still joining runs none of its DaemonSet pods yet; they take its room once it does. @@ -740,7 +741,8 @@ public class EksAutoModeCompute implements EksAutoModeCleanup { // The instance joins over the cluster's VPC, where the endpoint published on the host isn't reachable. String userData = nodeConfig(cluster, launch, clusterManager.vpcApiServerEndpoint(cluster).orElse(cluster.getEndpoint()), - certificateAuthorities(cluster, clusterManager.kubeletClientCertificateAuthority(cluster).orElse(null))); + certificateAuthorities(cluster, clusterManager.kubeletClientCertificateAuthority(cluster).orElse(null)), + clusterManager.hostReservation(launch.instanceType()).orElse(null)); Reservation reservation = ec2.runInstances(region, imageId, launch.instanceType().instanceType, 1, 1, null, ids(nodeClass.path("securityGroupSelectorTerms")), subnet, UUID.randomUUID().toString(), tags(cluster, launch.pool()), userData, profileArn, null, null, 0, null, null, null, @@ -1351,9 +1353,12 @@ public class EksAutoModeCompute implements EksAutoModeCleanup { * the node under the instance ID with its pool's labels and taints, so a pod the pool's taints keep off never * lands there first. Its {@code apiServerEndpoint} is the one given, the API server's address in the cluster's * VPC when it has one, and its {@code certificateAuthority} the base64 encoded PEM given, which the kubelet trusts - * for the API server and for the clients it serves. + * for the API server and for the clients it serves. Its kubelet reserves {@code reserved} for the system, the + * Docker host's size beyond the instance type's (none when null), so the node offers the type's CPU and memory, + * as an Auto Mode node does; nodeadm adds its own reservations for the kubelet, as on AWS. */ - static String nodeConfig(Cluster cluster, Launch launch, String apiServerEndpoint, String certificateAuthority) { + static String nodeConfig(Cluster cluster, Launch launch, String apiServerEndpoint, String certificateAuthority, + EksNodeCapacity.Reserved reserved) { StringBuilder yaml = new StringBuilder(""" apiVersion: node.eks.aws/v1alpha1 kind: NodeConfig @@ -1372,7 +1377,13 @@ public class EksAutoModeCompute implements EksAutoModeCleanup { } // nodeadm names the node by its instance ID, as Auto Mode's are named and authenticated, not its private DNS name. yaml.append(" featureGates:\n InstanceIdNodeName: true\n"); - yaml.append(" kubelet:\n flags:\n"); + yaml.append(" kubelet:\n"); + if (reserved != null && (reserved.cpuMilli() > 0 || reserved.memoryMib() > 0)) { + yaml.append(" config:\n systemReserved:\n"); + yaml.append(" cpu: ").append(reserved.cpuMilli()).append("m\n"); + yaml.append(" memory: ").append(reserved.memoryMib()).append("Mi\n"); + } + yaml.append(" flags:\n"); yaml.append(" - --node-labels=").append(String.join(",", launch.labels().entrySet().stream() .map(e -> e.getKey() + "=" + e.getValue()).toList())).append('\n'); if (!launch.pool().taints().isEmpty()) { diff --git a/src/main/java/io/floci/aws/services/eks/EksAutoModeConsolidation.java b/src/main/java/io/floci/aws/services/eks/EksAutoModeConsolidation.java index 582f19325a..1e86ac18a5 100644 --- a/src/main/java/io/floci/aws/services/eks/EksAutoModeConsolidation.java +++ b/src/main/java/io/floci/aws/services/eks/EksAutoModeConsolidation.java @@ -121,14 +121,13 @@ final class EksAutoModeConsolidation { /** * Whether a node of {@code launch}'s type, pool and zone has room for every one of {@code pods}, besides the - * {@code daemons} that would run there too. + * {@code daemons} that would run there too: what the node offers pods, as a node still joining has. */ static boolean holds(Launch launch, List pods, List daemons, String region) { CatalogInstanceType type = launch.instanceType(); long[] daemon = EksAutoModeNodes.daemonRequests(daemons, EksAutoModeNodes.withRegion( EksAutoModeNodes.labels(type, launch.pool(), launch.zone()), region), launch.pool().taints()); - PoolNode node = new PoolNode("replacement", launch.pool(), type, launch.zone(), type.vcpu * 1000L - daemon[0], - type.memoryMib * 1024L * 1024L - daemon[1], EksAutoModeNodes.MAX_PODS, true, List.of()); + PoolNode node = new PoolNode("replacement", launch.pool(), type, launch.zone(), daemon[0], daemon[1]); return EksAutoModeNodes.withoutRoom(pods, List.of(node)).left().isEmpty(); } diff --git a/src/main/java/io/floci/aws/services/eks/EksAutoModeNodes.java b/src/main/java/io/floci/aws/services/eks/EksAutoModeNodes.java index 5de8e55fe6..70f69364d4 100644 --- a/src/main/java/io/floci/aws/services/eks/EksAutoModeNodes.java +++ b/src/main/java/io/floci/aws/services/eks/EksAutoModeNodes.java @@ -275,13 +275,16 @@ final class EksAutoModeNodes { } /** - * A node still joining, with its pods' requests: it has its instance type's whole CPU and memory, as no - * kubelet has said what it reserves yet, all its pod slots, and no taints but its pool's. + * A node still joining, with its pods' requests: it has what a node of its instance type offers pods + * ({@link EksNodeCapacity#allocatable}), as no kubelet has said yet, all its pod slots, and no taints but its + * pool's. */ PoolNode(String instanceId, NodePool pool, CatalogInstanceType instanceType, String zone, long usedCpuMillis, long usedMemoryBytes) { - this(instanceId, pool, instanceType, zone, instanceType.vcpu * 1000L - usedCpuMillis, - instanceType.memoryMib * 1024L * 1024L - usedMemoryBytes, MAX_PODS, true, List.of()); + this(instanceId, pool, instanceType, zone, + EksNodeCapacity.allocatable(instanceType).cpuMillis() - usedCpuMillis, + EksNodeCapacity.allocatable(instanceType).memoryBytes() - usedMemoryBytes, MAX_PODS, true, + List.of()); } /** The taints a pod must tolerate there: the pool's and any the node carries besides. */ @@ -488,8 +491,9 @@ final class EksAutoModeNodes { for (String zone : zones) { Map labels = labels(type, pool, zone); long[] daemon = daemonRequests(daemons, withRegion(labels, region), pool.taints()); - if (type.vcpu * 1000L < cpuMillis + daemon[0] - || type.memoryMib * 1024L * 1024L < memoryBytes + daemon[1]) { + // Sized by what the node offers pods once its kubelet reserves its share, as Karpenter sizes it. + EksNodeCapacity.Allocatable offered = EksNodeCapacity.allocatable(type); + if (offered.cpuMillis() < cpuMillis + daemon[0] || offered.memoryBytes() < memoryBytes + daemon[1]) { continue; } if (poolAllows(pool, labels) && pod.fits(labels, pool.taints())) { diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index dfa38f827e..1e8754f353 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -1640,6 +1640,24 @@ public class EksClusterManager return DEFAULT_NODE_INSTANCE_TYPE; } + /** + * What the kubelet of an instance of {@code type} on the Docker host reserves to offer the type's size + * ({@link EksNodeCapacity#hostGap}); empty when the host's size can't be read. + */ + Optional hostReservation(CatalogInstanceType type) { + try { + Info host = lifecycleManager.getDockerClient().infoCmd().exec(); + if (host.getMemTotal() == null || host.getNCPU() == null) { + return Optional.empty(); + } + return Optional.of(EksNodeCapacity.hostGap(type, host.getMemTotal(), host.getNCPU())); + } catch (RuntimeException e) { + LOG.warnv("Docker host capacity unavailable for an instance of {0}: {1}", type.instanceType, + e.getMessage()); + return Optional.empty(); + } + } + private EksNodeCapacity.Limits resolveNodeCapacity(Cluster cluster) { try { Info host = lifecycleManager.getDockerClient().infoCmd().exec(); diff --git a/src/main/java/io/floci/aws/services/eks/EksNodeCapacity.java b/src/main/java/io/floci/aws/services/eks/EksNodeCapacity.java index 361d2fff00..91602aba6f 100644 --- a/src/main/java/io/floci/aws/services/eks/EksNodeCapacity.java +++ b/src/main/java/io/floci/aws/services/eks/EksNodeCapacity.java @@ -7,6 +7,8 @@ import java.util.List; /** The one calculation shared by the Docker limit and the kubelet's node budget. */ final class EksNodeCapacity { private static final long MIB = 1024L * 1024L; + /** The EKS AMI's {@code memory.available} hard eviction threshold. */ + private static final long EVICTION_MIB = 100; private EksNodeCapacity() {} @@ -26,6 +28,55 @@ final class EksNodeCapacity { } } + /** CPU (millicores) and memory (MiB) a kubelet reserves for the system. */ + record Reserved(int cpuMilli, long memoryMib) { + } + + /** + * What a kubelet on a node of {@code type} reserves so it offers what the type does ({@link #allocatable}): a + * guest shares the Docker host's kernel, so its kubelet sees the host's CPUs and memory as its capacity, and the + * difference to the type is the system's. nodeadm takes its CPU tiers from the cores it sees, the host's, so the + * CPU reserved leaves out what those tiers take beyond the type's own. A host smaller than the type reserves + * nothing. + */ + static Reserved hostGap(CatalogInstanceType type, long hostMemoryBytes, int hostCpus) { + int beyondTiers = cpuReservationMilli(hostCpus) - cpuReservationMilli(type.vcpu); + return new Reserved(Math.max(0, (hostCpus - type.vcpu) * 1000 - beyondTiers), + Math.max(0, hostMemoryBytes / MIB - type.memoryMib)); + } + + /** A node's CPU (millicores) and memory (bytes) for pods. */ + record Allocatable(long cpuMillis, long memoryBytes) { + } + + /** + * What a node of {@code type} offers pods, as nodeadm leaves it and Karpenter counts it when it picks a type: the + * type's CPU less the EKS AMI's kube reservation tiers, and its memory less 11 MiB per pod plus 255 MiB and the + * 100 MiB {@code memory.available} eviction threshold. + */ + static Allocatable allocatable(CatalogInstanceType type) { + long memoryMib = type.memoryMib - kubeMemoryMib(type) - EVICTION_MIB; + return new Allocatable(Math.max(0, type.vcpu * 1000L - cpuReservationMilli(type.vcpu)), + Math.max(0, memoryMib) * MIB); + } + + /** The EKS AMI's kube reservation of memory for a node of {@code type}: 11 MiB per pod plus 255 MiB. */ + private static long kubeMemoryMib(CatalogInstanceType type) { + return 11L * maxPods(type) + 255; + } + + /** The pods a node of {@code type} runs, as the EKS AMI's max-pods: from its interfaces and addresses. */ + private static int maxPods(CatalogInstanceType type) { + int interfaces = type.networkCards == null ? 0 : type.networkCards.stream() + .filter(card -> card.networkCardIndex != null && card.networkCardIndex == 0 + && card.maximumNetworkInterfaces != null) + .mapToInt(card -> card.maximumNetworkInterfaces) + .findFirst().orElse(0); + int addresses = type.ipv4AddressesPerInterface == null ? 0 : type.ipv4AddressesPerInterface; + int podCap = type.vcpu > 30 ? 250 : 110; + return interfaces > 0 && addresses > 0 ? Math.min(podCap, interfaces * (addresses - 1) + 2) : podCap; + } + static Limits explicitCeilingWithoutHostInfo(int maxMemoryMib, int vcpus) { return new Limits((long) Math.max(0, maxMemoryMib) * MIB, vcpus, 0, 0, 0, 0, 0, false, false); @@ -58,18 +109,9 @@ final class EksNodeCapacity { return null; } - int interfaces = type.networkCards.stream() - .filter(card -> card.networkCardIndex != null && card.networkCardIndex == 0 - && card.maximumNetworkInterfaces != null) - .mapToInt(card -> card.maximumNetworkInterfaces) - .findFirst().orElse(0); - int addresses = type.ipv4AddressesPerInterface == null ? 0 : type.ipv4AddressesPerInterface; - int podCap = type.vcpu > 30 ? 250 : 110; - int maxPods = interfaces > 0 && addresses > 0 - ? Math.min(podCap, interfaces * (addresses - 1) + 2) : podCap; - long kubeMemoryMib = 11L * maxPods + 255; + long kubeMemoryMib = kubeMemoryMib(type); long systemMemoryMib = Math.max(128, memoryMib / 10); - long evictionBufferMib = Math.min(100, memoryMib / 4); + long evictionBufferMib = Math.min(EVICTION_MIB, memoryMib / 4); // Only an undersized host with no explicit ceiling falls back to the old unbounded mode. // An operator's ceiling must remain a hard bound, even if it leaves few resources for pods. if (maxMemoryMib == 0 && memoryMib < kubeMemoryMib + systemMemoryMib + evictionBufferMib + 256) { diff --git a/src/test/java/io/floci/aws/services/eks/EksAutoModeComputeTest.java b/src/test/java/io/floci/aws/services/eks/EksAutoModeComputeTest.java index 40b377edc5..4fcaafe41c 100644 --- a/src/test/java/io/floci/aws/services/eks/EksAutoModeComputeTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksAutoModeComputeTest.java @@ -33,6 +33,7 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -147,6 +148,36 @@ class EksAutoModeComputeTest { .filter(line -> line.contains("certificateAuthority")).toList()); } + /** + * An instance's kubelet reserves the Docker host's size beyond its instance type for the system, so the node + * offers the type's CPU and memory, as an Auto Mode node does; on a host whose size can't be read, nothing. + */ + @Test + void anInstancesKubeletReservesTheHostsSizeBeyondItsType() { + Cluster cluster = cluster("prod"); + when(clusterManager.hostReservation(any())).thenReturn(Optional.of(new EksNodeCapacity.Reserved(6000, 20480))); + + compute.reconcile(cluster, REGION); + + assertTrue(verifyInstanceLaunched().contains(""" + kubelet: + config: + systemReserved: + cpu: 6000m + memory: 20480Mi + flags: + """)); + } + + @Test + void anInstanceOnAHostOfUnknownSizeReservesNothing() { + compute.reconcile(cluster("prod"), REGION); + + String userData = verifyInstanceLaunched(); + assertTrue(userData.contains(" kubelet:\n flags:\n"), userData); + assertFalse(userData.contains("systemReserved"), userData); + } + /** * A node's request for its kubelet serving certificate is approved when it names only its own instance, as EKS * approves it; one naming another address stays pending. diff --git a/src/test/java/io/floci/aws/services/eks/EksAutoModeNodesTest.java b/src/test/java/io/floci/aws/services/eks/EksAutoModeNodesTest.java index 69595193be..a687c0f3b8 100644 --- a/src/test/java/io/floci/aws/services/eks/EksAutoModeNodesTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksAutoModeNodesTest.java @@ -91,6 +91,31 @@ class EksAutoModeNodesTest { EksAutoModeNodes.labels(TYPES.get(2), pools().getFirst(), null), List.of())[0]); } + /** + * A node is sized by what it offers pods once its kubelet reserves its share, as Karpenter sizes it: a 2000m pod + * doesn't fit the 1930m a 2-vCPU node offers, so it gets a 4-vCPU node; a 1900m one fits a 2-vCPU node. + */ + @Test + void aNodeIsSizedByWhatItOffersPodsNotItsWholeType() throws Exception { + assertEquals("c7a.xlarge", EksAutoModeNodes.plan(pools(), List.of(pod("whole", "2000m", "64Mi")), TYPES, + Map.of()).getFirst().instanceType().instanceType); + assertEquals("c7a.large", EksAutoModeNodes.plan(pools(), List.of(pod("fits", "1900m", "64Mi")), TYPES, + Map.of()).getFirst().instanceType().instanceType); + } + + /** + * A consolidation's replacement is sized the same way: a 2-vCPU node doesn't hold a 1950m pod, which fits its + * whole size but not the 1930m it offers pods. + */ + @Test + void aReplacementHoldsOnlyWhatItsNodeOffersPods() throws Exception { + CatalogInstanceType large = TYPES.get(2); + Launch launch = new Launch(pools().getFirst(), large, null, Map.of(), List.of()); + + assertFalse(EksAutoModeConsolidation.holds(launch, List.of(pod("web", "1950m", "64Mi")), List.of(), null)); + assertTrue(EksAutoModeConsolidation.holds(launch, List.of(pod("web", "1900m", "64Mi")), List.of(), null)); + } + /** A DaemonSet selecting on the region, which a joined node carries, counts on a new node in that region. */ @Test void aDaemonSetSelectingTheRegionCountsOnANodeThere() throws Exception { diff --git a/src/test/java/io/floci/aws/services/eks/EksNodeCapacityTest.java b/src/test/java/io/floci/aws/services/eks/EksNodeCapacityTest.java index 61f2fce1a4..107163b030 100644 --- a/src/test/java/io/floci/aws/services/eks/EksNodeCapacityTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksNodeCapacityTest.java @@ -17,6 +17,36 @@ class EksNodeCapacityTest { private static final long MIB = 1024L * 1024L; private final Ec2InstanceTypeCatalog catalog = new Ec2InstanceTypeCatalog(); + /** + * A node reserves the host's size beyond its instance type's, less what nodeadm's CPU tiers take from the host's 8 + * cores beyond a c7a.large's 2 (90m against 70m), so it offers the 1930m a c7a.large does; nothing on a host + * smaller than the type. + */ + @Test + void hostGapIsTheHostsSizeBeyondTheInstanceTypes() { + CatalogInstanceType type = catalog.find("c7a.large").orElseThrow(); + EksNodeCapacity.Reserved reserved = EksNodeCapacity.hostGap(type, 24576 * MIB, 8); + + assertEquals(new EksNodeCapacity.Reserved(5980, 24576 - type.memoryMib), reserved); + // What nodeadm leaves: the host's 8000m less this, less its tiers on 8 cores. + assertEquals(EksNodeCapacity.allocatable(type).cpuMillis(), 8000 - reserved.cpuMilli() - 90); + assertEquals(new EksNodeCapacity.Reserved(0, 0), EksNodeCapacity.hostGap(type, 2048 * MIB, 1)); + } + + /** + * A node offers pods its type less the EKS AMI's kube reservation and eviction threshold: a c7a.large keeps 1930m + * (6% of the first core, 1% of the second) and its memory less 11 MiB per pod plus 255 MiB and 100 MiB. + */ + @Test + void allocatableIsTheTypeLessTheKubeletsReservations() { + CatalogInstanceType type = catalog.find("c7a.large").orElseThrow(); + int maxPods = type.networkCards.getFirst().maximumNetworkInterfaces + * (type.ipv4AddressesPerInterface - 1) + 2; + + assertEquals(new EksNodeCapacity.Allocatable(1930, (type.memoryMib - (11L * maxPods + 255) - 100) * MIB), + EksNodeCapacity.allocatable(type)); + } + @Test void reservationsFollowTheAppliedLimitAndTheInstancePodDensity() { CatalogInstanceType type = catalog.find("m5.large").orElseThrow();