mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): give an EKS Auto Mode cluster its node pools, default node class and Auto Mode node label (#9425)
This commit is contained in:
1 parent
47e554680b
commit
017b687567
9 files changed
+507
-9
No files matched your search
@@ -444,13 +444,19 @@ With IAM enforcement on, `CreateCluster` checks `iam:PassRole` on the cluster ro
|
||||
Floci acts on the configuration as EKS does:
|
||||
|
||||
- **Compute.** Turning it on gives the node role its `EC2` access entry with `AmazonEKSAutoNodePolicy` (see
|
||||
[Access-entry management](#access-entry-management)).
|
||||
[Access-entry management](#access-entry-management)). While it is on, the cluster has the `NodePool`
|
||||
(`karpenter.sh/v1`) and `NodeClass` (`eks.amazonaws.com/v1`) kinds, the `default` NodeClass (the node role's name,
|
||||
the cluster's subnets and security group) and the built-in `general-purpose` and `system` NodePools
|
||||
`computeConfig.nodePools` names, as Auto Mode makes them: on-demand c, m and r instances of generation 5 and later,
|
||||
`amd64` (`system` also `arm64`, with a `CriticalAddonsOnly` `NoSchedule` taint), expiring after 336 hours. A pool
|
||||
`UpdateClusterConfig` drops is removed. The cluster's node carries Auto Mode's `eks.amazonaws.com/compute-type: auto`
|
||||
label, so workloads that select Auto Mode nodes run on it.
|
||||
- **Block storage.** While it is on, claims of a StorageClass naming `ebs.csi.eks.amazonaws.com` are provisioned
|
||||
(see [Storage classes](#storage-classes)).
|
||||
- **Load balancing.** While it is on, Services get Network Load Balancers (see
|
||||
[Auto Mode load balancing for Services](#auto-mode-load-balancing-for-services)).
|
||||
|
||||
It doesn't install the built-in node pools or launch nodes for them: workloads run on the cluster's k3s node.
|
||||
Floci launches no nodes for the pools: workloads run on the cluster's k3s node.
|
||||
[#8914](https://github.com/floci-io/floci/issues/8914) plans the rest.
|
||||
|
||||
### Auto Mode load balancing for Services
|
||||
|
||||
@@ -117,6 +117,7 @@ import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -184,6 +185,18 @@ public class EksClusterManager
|
||||
# EKS Auto Mode block storage is off for this cluster.
|
||||
# k3s deletes the provisioner an earlier version of this file created.
|
||||
""";
|
||||
static final String COMPUTE_MANIFEST_FILE = "floci-eks-auto-mode-compute.yaml";
|
||||
static final String COMPUTE_MANIFEST_TAR_ENTRY = "server/manifests/" + COMPUTE_MANIFEST_FILE;
|
||||
// The manifest once compute is off: no objects, so k3s deletes the node pools, node class and their kinds.
|
||||
static final String COMPUTE_MANIFEST_REMOVED = """
|
||||
# EKS Auto Mode compute is off for this cluster.
|
||||
# k3s deletes the node pools, node class and kinds an earlier version of this file created.
|
||||
""";
|
||||
/** The comment in the compute manifest that starts the {@code default} NodeClass. */
|
||||
private static final String DEFAULT_NODE_CLASS_MARKER = "# The default NodeClass";
|
||||
/** The label EKS Auto Mode's nodes carry, given to the cluster's node while compute is on. */
|
||||
static final String AUTO_COMPUTE_LABEL_KEY = "eks.amazonaws.com/compute-type"; // partition-literal: a label
|
||||
static final String AUTO_COMPUTE_LABEL = AUTO_COMPUTE_LABEL_KEY + "=auto";
|
||||
private static final String ENDPOINT_MODE_NETWORK = "network";
|
||||
public static final String DEFAULT_POD_CIDR = "10.42.0.0/16";
|
||||
|
||||
@@ -814,6 +827,10 @@ public class EksClusterManager
|
||||
if (!serviceLb) {
|
||||
serverArgs.add("--disable=servicelb");
|
||||
}
|
||||
if (computeOn(cluster)) {
|
||||
// Auto Mode's nodes carry this label, which workloads select them by.
|
||||
serverArgs.add("--node-label=" + AUTO_COMPUTE_LABEL);
|
||||
}
|
||||
|
||||
EksNodeCapacity.Limits nodeLimits = resolveNodeCapacity(cluster);
|
||||
if (nodeLimits != null) {
|
||||
@@ -1025,6 +1042,7 @@ public class EksClusterManager
|
||||
linkContainerdCertsDir(containerId, cluster.getName());
|
||||
registerPodIdentityWebhook(containerId, cluster);
|
||||
applyBlockStorage(containerId, cluster);
|
||||
applyCompute(containerId, cluster);
|
||||
if (signingKeyFiles != null) {
|
||||
copySigningKeysIntoContainer(containerId, signingKeyFiles, cluster.getName());
|
||||
}
|
||||
@@ -1187,6 +1205,8 @@ public class EksClusterManager
|
||||
registerPodIdentityWebhook(info.containerId(), cluster,
|
||||
() -> survivingNodeResolvesThroughFloci(info.containerId()));
|
||||
applyBlockStorage(info.containerId(), cluster);
|
||||
applyCompute(info.containerId(), cluster);
|
||||
applyComputeLabel(cluster, info.containerId());
|
||||
activeClusters.put(clusterResourceName(cluster), cluster);
|
||||
attachClusterLogs(cluster, true, true, false);
|
||||
|
||||
@@ -1473,6 +1493,8 @@ public class EksClusterManager
|
||||
|
||||
registerAllJoinedNodes(cluster, containerId);
|
||||
|
||||
applyComputeLabel(cluster, containerId);
|
||||
|
||||
LOG.infov("Finalized EKS cluster {0} with CA data extracted", cluster.getName());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not extract kubeconfig for cluster {0}: {1}",
|
||||
@@ -3080,19 +3102,124 @@ public class EksClusterManager
|
||||
* the manifest lives on the cluster's data volume, which outlives a restart, and k3s prunes what it created.
|
||||
*/
|
||||
void applyBlockStorage(String containerId, Cluster cluster) {
|
||||
boolean enabled = StorageConfig.blockStorageOn(cluster.getStorageConfig());
|
||||
applyAutoModeManifest(containerId, cluster, StorageConfig.blockStorageOn(cluster.getStorageConfig()),
|
||||
BLOCK_STORAGE_MANIFEST_FILE, BLOCK_STORAGE_MANIFEST_TAR_ENTRY, this::blockStorageManifest,
|
||||
BLOCK_STORAGE_MANIFEST_REMOVED, "block storage provisioner");
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs an EKS Auto Mode capability's manifest while it is {@code enabled}, or, if it was installed before,
|
||||
* replaces it with {@code removed}, which holds no objects: the manifest lives on the cluster's data volume,
|
||||
* which outlives a restart, and k3s prunes what it created.
|
||||
*/
|
||||
private void applyAutoModeManifest(String containerId, Cluster cluster, boolean enabled, String fileName,
|
||||
String tarEntry, Supplier<String> manifest, String removed, String what) {
|
||||
try {
|
||||
if (!enabled && !Files.exists(localClusterFile(cluster, "auto-mode", BLOCK_STORAGE_MANIFEST_FILE))) {
|
||||
if (!enabled && !Files.exists(localClusterFile(cluster, "auto-mode", fileName))) {
|
||||
return;
|
||||
}
|
||||
installManifest(containerId, cluster, "auto-mode", BLOCK_STORAGE_MANIFEST_FILE,
|
||||
BLOCK_STORAGE_MANIFEST_TAR_ENTRY, enabled ? blockStorageManifest() : BLOCK_STORAGE_MANIFEST_REMOVED);
|
||||
installManifest(containerId, cluster, "auto-mode", fileName, tarEntry, enabled ? manifest.get() : removed);
|
||||
if (enabled) {
|
||||
LOG.infov("Installed the EKS Auto Mode block storage provisioner for cluster {0}", cluster.getName());
|
||||
LOG.infov("Installed the EKS Auto Mode {0} for cluster {1}", what, cluster.getName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("EKS cluster {0} gets no Auto Mode block storage: could not install {1} into the k3s "
|
||||
+ "container: {2}", cluster.getName(), BLOCK_STORAGE_MANIFEST_FILE, e.getMessage());
|
||||
LOG.warnv("EKS cluster {0} gets no Auto Mode {1}: could not install {2} into the k3s container: {3}",
|
||||
cluster.getName(), what, fileName, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs, while the cluster's EKS Auto Mode compute is on, the NodePool and NodeClass kinds, the {@code default}
|
||||
* NodeClass and the built-in node pools its {@code computeConfig.nodePools} names, as Auto Mode does (measured), and
|
||||
* removes what it no longer names; otherwise removes them all. Floci launches no nodes for them.
|
||||
*/
|
||||
void applyCompute(String containerId, Cluster cluster) {
|
||||
applyAutoModeManifest(containerId, cluster, computeOn(cluster), COMPUTE_MANIFEST_FILE, COMPUTE_MANIFEST_TAR_ENTRY,
|
||||
() -> computeManifest(cluster), COMPUTE_MANIFEST_REMOVED, "node pools");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the cluster's running node the label EKS Auto Mode's nodes carry while compute is on, and takes it off
|
||||
* once compute is off. k3s's {@code --node-label} adds a label when the node starts but never removes one, and a
|
||||
* node started before Floci set it has none until it restarts. A cluster that never had Auto Mode compute is left
|
||||
* alone.
|
||||
*/
|
||||
void applyComputeLabel(Cluster cluster, String containerId) {
|
||||
if (cluster.getComputeConfig() == null || containerId == null) {
|
||||
return;
|
||||
}
|
||||
String label = computeOn(cluster) ? AUTO_COMPUTE_LABEL : AUTO_COMPUTE_LABEL_KEY + "-";
|
||||
try {
|
||||
ContainerExec.Result result = execInContainerForResult(containerId, new String[]{"kubectl", "label",
|
||||
"node", deriveClusterNodePrivateDnsName(cluster), "--overwrite", label}, 15);
|
||||
if (result.exitCode() != 0) {
|
||||
LOG.warnv("Could not set the Auto Mode label of EKS cluster {0}''s node: {1}", cluster.getName(),
|
||||
result.summary());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not set the Auto Mode label of EKS cluster {0}''s node: {1}", cluster.getName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static boolean computeOn(Cluster cluster) {
|
||||
return cluster != null && cluster.getComputeConfig() != null
|
||||
&& Boolean.TRUE.equals(cluster.getComputeConfig().enabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* The kinds and the {@code default} NodeClass, with the node role's name, the cluster's subnets and its security
|
||||
* group as Auto Mode sets them, then the pools the cluster names. Without a node role there are no pools, and no
|
||||
* NodeClass is written.
|
||||
*/
|
||||
String computeManifest(Cluster cluster) {
|
||||
String manifest = resource(EksClusterManager.class.getResourceAsStream("/eks/auto-mode-compute.yaml"),
|
||||
"/eks/auto-mode-compute.yaml");
|
||||
String roleArn = cluster.getComputeConfig().nodeRoleArn();
|
||||
if (roleArn == null || roleArn.isBlank()) {
|
||||
return manifest.substring(0, manifest.indexOf(DEFAULT_NODE_CLASS_MARKER));
|
||||
}
|
||||
ResourcesVpcConfig vpc = cluster.getResourcesVpcConfig();
|
||||
List<String> subnets = vpc == null || vpc.getSubnetIds() == null ? List.of() : vpc.getSubnetIds();
|
||||
String securityGroup = vpc == null ? null : vpc.getClusterSecurityGroupId();
|
||||
StringBuilder out = new StringBuilder(manifest
|
||||
.replace("%ROLE%", roleArn.substring(roleArn.lastIndexOf('/') + 1))
|
||||
.replace("%SUBNET_TERMS%", selectorTerms(subnets))
|
||||
.replace("%SECURITY_GROUP_TERMS%", selectorTerms(securityGroup == null ? List.of() : List.of(securityGroup))));
|
||||
List<String> pools = cluster.getComputeConfig().nodePools() == null ? List.of()
|
||||
: cluster.getComputeConfig().nodePools();
|
||||
if (pools.contains("general-purpose")) {
|
||||
out.append(resource(EksClusterManager.class.getResourceAsStream("/eks/auto-mode-nodepool-general-purpose.yaml"),
|
||||
"/eks/auto-mode-nodepool-general-purpose.yaml"));
|
||||
}
|
||||
if (pools.contains("system")) {
|
||||
out.append(resource(EksClusterManager.class.getResourceAsStream("/eks/auto-mode-nodepool-system.yaml"),
|
||||
"/eks/auto-mode-nodepool-system.yaml"));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** The rest of a selector terms key's line: {@code []} for none, else one {@code - id:} term a line. */
|
||||
private static String selectorTerms(List<String> ids) {
|
||||
if (ids.isEmpty()) {
|
||||
return " []";
|
||||
}
|
||||
StringBuilder terms = new StringBuilder();
|
||||
for (String id : ids) {
|
||||
terms.append("\n - id: ").append(id);
|
||||
}
|
||||
return terms.toString();
|
||||
}
|
||||
|
||||
/** A packaged resource the caller opened with an inline literal, which the native image build finds. */
|
||||
private static String resource(InputStream in, String path) {
|
||||
try (in) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("missing resource " + path);
|
||||
}
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1339,6 +1339,14 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
|
||||
&& !config.services().eks().mock() && clusterManager != null && cluster.getContainerId() != null) {
|
||||
replaceNodeForServiceLb(requireClusterInRequestRegion(name));
|
||||
}
|
||||
if (nextAutoMode != null && !config.services().eks().mock() && clusterManager != null) {
|
||||
// The node pools the update names, or none once compute is off, as Auto Mode keeps them. A node replaced
|
||||
// above got them as it started; this one, or the replacement, gets the same again.
|
||||
Cluster updated = requireClusterInRequestRegion(name);
|
||||
if (updated.getContainerId() != null) {
|
||||
clusterManager.applyCompute(updated.getContainerId(), updated);
|
||||
}
|
||||
}
|
||||
if ((nextAutoMode != null && nextAutoMode.computeOn()) || requestedMode != null) {
|
||||
// Turning compute on, or moving off CONFIG_MAP while it is on, gives the node role its entry.
|
||||
ensureAutoModeNodeEntry(requireClusterInRequestRegion(name));
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# EKS Auto Mode compute on a Floci cluster: the NodePool and NodeClass kinds Auto Mode installs, its default
|
||||
# NodeClass, and the built-in node pools the cluster's computeConfig.nodePools names (appended by Floci).
|
||||
# Floci launches no nodes for them; workloads run on the cluster's node.
|
||||
apiVersion: apiextensions.k8s.io/v1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: nodepools.karpenter.sh
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: floci
|
||||
spec:
|
||||
group: karpenter.sh
|
||||
scope: Cluster
|
||||
names:
|
||||
kind: NodePool
|
||||
listKind: NodePoolList
|
||||
plural: nodepools
|
||||
singular: nodepool
|
||||
versions:
|
||||
- name: v1
|
||||
served: true
|
||||
storage: true
|
||||
subresources:
|
||||
status: {}
|
||||
schema:
|
||||
openAPIV3Schema:
|
||||
type: object
|
||||
properties:
|
||||
spec:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
status:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
---
|
||||
apiVersion: apiextensions.k8s.io/v1
|
||||
kind: CustomResourceDefinition
|
||||
metadata:
|
||||
name: nodeclasses.eks.amazonaws.com
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: floci
|
||||
spec:
|
||||
group: eks.amazonaws.com
|
||||
scope: Cluster
|
||||
names:
|
||||
kind: NodeClass
|
||||
listKind: NodeClassList
|
||||
plural: nodeclasses
|
||||
singular: nodeclass
|
||||
versions:
|
||||
- name: v1
|
||||
served: true
|
||||
storage: true
|
||||
subresources:
|
||||
status: {}
|
||||
schema:
|
||||
openAPIV3Schema:
|
||||
type: object
|
||||
properties:
|
||||
spec:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
status:
|
||||
type: object
|
||||
x-kubernetes-preserve-unknown-fields: true
|
||||
# The default NodeClass, which Floci leaves out without a node role.
|
||||
---
|
||||
apiVersion: eks.amazonaws.com/v1
|
||||
kind: NodeClass
|
||||
metadata:
|
||||
name: default
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: eks
|
||||
spec:
|
||||
role: "%ROLE%"
|
||||
subnetSelectorTerms:%SUBNET_TERMS%
|
||||
securityGroupSelectorTerms:%SECURITY_GROUP_TERMS%
|
||||
ephemeralStorage:
|
||||
size: 80Gi
|
||||
iops: 3000
|
||||
throughput: 125
|
||||
networkPolicy: DefaultAllow
|
||||
networkPolicyEventLogs: Disabled
|
||||
snatPolicy: Random
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
apiVersion: karpenter.sh/v1
|
||||
kind: NodePool
|
||||
metadata:
|
||||
name: general-purpose
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: eks
|
||||
spec:
|
||||
disruption:
|
||||
budgets:
|
||||
- nodes: 10%
|
||||
consolidateAfter: 30s
|
||||
consolidationPolicy: Balanced
|
||||
template:
|
||||
metadata: {}
|
||||
spec:
|
||||
expireAfter: 336h
|
||||
nodeClassRef:
|
||||
group: eks.amazonaws.com
|
||||
kind: NodeClass
|
||||
name: default
|
||||
requirements:
|
||||
- key: karpenter.sh/capacity-type
|
||||
operator: In
|
||||
values: ["on-demand"]
|
||||
- key: eks.amazonaws.com/instance-category
|
||||
operator: In
|
||||
values: ["c", "m", "r"]
|
||||
- key: eks.amazonaws.com/instance-generation
|
||||
operator: Gt
|
||||
values: ["4"]
|
||||
- key: kubernetes.io/arch
|
||||
operator: In
|
||||
values: ["amd64"]
|
||||
- key: kubernetes.io/os
|
||||
operator: In
|
||||
values: ["linux"]
|
||||
terminationGracePeriod: 24h0m0s
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
apiVersion: karpenter.sh/v1
|
||||
kind: NodePool
|
||||
metadata:
|
||||
name: system
|
||||
labels:
|
||||
app.kubernetes.io/managed-by: eks
|
||||
spec:
|
||||
disruption:
|
||||
budgets:
|
||||
- nodes: 10%
|
||||
consolidateAfter: 30s
|
||||
consolidationPolicy: Balanced
|
||||
template:
|
||||
metadata: {}
|
||||
spec:
|
||||
expireAfter: 336h
|
||||
nodeClassRef:
|
||||
group: eks.amazonaws.com
|
||||
kind: NodeClass
|
||||
name: default
|
||||
requirements:
|
||||
- key: karpenter.sh/capacity-type
|
||||
operator: In
|
||||
values: ["on-demand"]
|
||||
- key: eks.amazonaws.com/instance-category
|
||||
operator: In
|
||||
values: ["c", "m", "r"]
|
||||
- key: eks.amazonaws.com/instance-generation
|
||||
operator: Gt
|
||||
values: ["4"]
|
||||
- key: kubernetes.io/arch
|
||||
operator: In
|
||||
values: ["amd64", "arm64"]
|
||||
- key: kubernetes.io/os
|
||||
operator: In
|
||||
values: ["linux"]
|
||||
taints:
|
||||
- effect: NoSchedule
|
||||
key: CriticalAddonsOnly
|
||||
terminationGracePeriod: 24h0m0s
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.floci.aws.services.eks.model.BlockStorage;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ComputeConfig;
|
||||
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
|
||||
import io.floci.aws.services.eks.model.KubernetesNetworkConfig;
|
||||
import io.floci.aws.services.eks.model.StorageConfig;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.EksTestNode;
|
||||
import io.floci.aws.testing.RdsMockProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* EKS Auto Mode compute on a real k3s node: with compute on, the cluster has the NodePool and NodeClass kinds, the
|
||||
* {@code default} NodeClass and the built-in node pools it names, as Auto Mode installs them, and its node carries
|
||||
* Auto Mode's {@code eks.amazonaws.com/compute-type: auto} label. Runs on {@link RdsMockProfile} with the other
|
||||
* classes that run a real cluster.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(RdsMockProfile.class)
|
||||
class EksAutoModeComputeDockerNightlyIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksAutoModeComputeDockerNightlyIntegrationTest.class);
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
EksClusterManager eksClusterManager;
|
||||
|
||||
private Cluster cluster;
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
boolean dockerAvailable = DockerAvailability.answers(dockerClient);
|
||||
if (!dockerAvailable) {
|
||||
LOG.warn("Docker daemon is not available; skipping EksAutoModeComputeDockerNightlyIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for the Auto Mode compute test");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (cluster != null) {
|
||||
try {
|
||||
eksClusterManager.stopCluster(cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop test cluster: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithComputeHasItsNodePoolsTheDefaultNodeClassAndAnAutoModeNode() {
|
||||
cluster = EksTestNode.cluster(ACCOUNT, "compute-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of("general-purpose", "system"),
|
||||
"arn:aws:iam::" + ACCOUNT + ":role/eks-auto-node"));
|
||||
cluster.setStorageConfig(new StorageConfig(new BlockStorage(true)));
|
||||
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
|
||||
network.setElasticLoadBalancing(new ElasticLoadBalancing(true));
|
||||
cluster.setKubernetesNetworkConfig(network);
|
||||
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(90));
|
||||
|
||||
await("node pools").atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(3)).ignoreExceptions()
|
||||
.until(() -> "general-purpose system".equals(node.kubectlOutput("get", "nodepools",
|
||||
"-o", "jsonpath={.items[*].metadata.name}")));
|
||||
assertEquals("eks-auto-node", node.kubectlOutput("get", "nodeclass", "default", "-o", "jsonpath={.spec.role}"));
|
||||
assertEquals("CriticalAddonsOnly", node.kubectlOutput("get", "nodepool", "system",
|
||||
"-o", "jsonpath={.spec.template.spec.taints[0].key}"));
|
||||
assertEquals("auto", node.kubectlOutput("get", "nodes",
|
||||
"-o", "jsonpath={.items[0].metadata.labels.eks\\.amazonaws\\.com/compute-type}"));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.floci.aws.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
@@ -60,6 +62,7 @@ import io.floci.aws.services.eks.model.CertificateAuthority;
|
||||
import io.floci.aws.services.eks.model.Cluster;
|
||||
import io.floci.aws.services.eks.model.ClusterIdentity;
|
||||
import io.floci.aws.services.eks.model.ClusterOidcKey;
|
||||
import io.floci.aws.services.eks.model.ComputeConfig;
|
||||
import io.floci.aws.services.eks.model.ElasticLoadBalancing;
|
||||
import io.floci.aws.services.eks.model.KubernetesNetworkConfig;
|
||||
import io.floci.aws.services.eks.model.LogSetup;
|
||||
@@ -137,6 +140,7 @@ import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
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;
|
||||
@@ -613,6 +617,7 @@ class EksClusterManagerTest {
|
||||
KubernetesNetworkConfig network = new KubernetesNetworkConfig();
|
||||
network.setElasticLoadBalancing(new ElasticLoadBalancing(loadBalancing));
|
||||
cluster.setKubernetesNetworkConfig(network);
|
||||
cluster.setComputeConfig(new ComputeConfig(loadBalancing, List.of(), null));
|
||||
|
||||
manager.startCluster(cluster);
|
||||
|
||||
@@ -620,6 +625,8 @@ class EksClusterManagerTest {
|
||||
ArgumentCaptor<List<String>> cmd = ArgumentCaptor.forClass(List.class);
|
||||
verify(builder).withCmd(cmd.capture());
|
||||
assertEquals(loadBalancing, cmd.getValue().contains("--disable=servicelb"));
|
||||
// Auto Mode's capabilities are on together, and its nodes carry the compute-type label.
|
||||
assertEquals(loadBalancing, cmd.getValue().contains("--node-label=" + EksClusterManager.AUTO_COMPUTE_LABEL));
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> labels = ArgumentCaptor.forClass(Map.class);
|
||||
verify(builder).withLabels(labels.capture());
|
||||
@@ -4463,6 +4470,102 @@ class EksClusterManagerTest {
|
||||
assertEquals(manager.blockStorageManifest(), Files.readString(blockStorageCopy()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithComputeGetsTheKindsTheDefaultNodeClassAndTheNamedPoolsAndLosesThemOnceItIsOff()
|
||||
throws Exception {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of("system"), "arn:aws:iam::000000000000:role/eks/auto-node"));
|
||||
ResourcesVpcConfig vpc = new ResourcesVpcConfig();
|
||||
vpc.setSubnetIds(List.of("subnet-a", "subnet-b"));
|
||||
vpc.setClusterSecurityGroupId("sg-cluster");
|
||||
cluster.setResourcesVpcConfig(vpc);
|
||||
Path localCopy = tempDir.resolve("auto-mode/000000000000/us-east-1/demo")
|
||||
.resolve(EksClusterManager.COMPUTE_MANIFEST_FILE);
|
||||
|
||||
manager.applyCompute("container-1", cluster);
|
||||
|
||||
String manifest = Files.readString(localCopy);
|
||||
assertTrue(manifest.contains("name: nodepools.karpenter.sh"));
|
||||
assertTrue(manifest.contains("name: nodeclasses.eks.amazonaws.com"));
|
||||
assertTrue(manifest.contains("""
|
||||
role: "auto-node"
|
||||
subnetSelectorTerms:
|
||||
- id: subnet-a
|
||||
- id: subnet-b
|
||||
securityGroupSelectorTerms:
|
||||
- id: sg-cluster
|
||||
"""));
|
||||
assertTrue(manifest.contains(" name: system\n"));
|
||||
assertFalse(manifest.contains("name: general-purpose"));
|
||||
|
||||
cluster.setComputeConfig(new ComputeConfig(false, List.of(), null));
|
||||
manager.applyCompute("container-1", cluster);
|
||||
|
||||
assertEquals(EksClusterManager.COMPUTE_MANIFEST_REMOVED, Files.readString(localCopy));
|
||||
}
|
||||
|
||||
/** A role named like a YAML boolean or number stays a string. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"true", "123", "null"})
|
||||
void theNodeClassRoleIsAStringWhateverItsName(String role) throws Exception {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of(), "arn:aws:iam::000000000000:role/" + role));
|
||||
|
||||
List<JsonNode> objects = new ObjectMapper(new YAMLFactory()).readerFor(JsonNode.class)
|
||||
.<JsonNode>readValues(manager.computeManifest(cluster)).readAll();
|
||||
|
||||
JsonNode spec = objects.stream().filter(o -> "NodeClass".equals(o.path("kind").asText())).findFirst()
|
||||
.orElseThrow().path("spec");
|
||||
assertTrue(spec.path("role").isTextual());
|
||||
assertEquals(role, spec.path("role").asText());
|
||||
}
|
||||
|
||||
/** The running node gets the Auto Mode label while compute is on and loses it once it is off. */
|
||||
@Test
|
||||
void theRunningNodeIsLabelledAsComputeIsOnOrOff() {
|
||||
EksClusterManager spyManager = Mockito.spy(manager);
|
||||
doReturn(new ContainerExec.Result(0L, "", "", false)).when(spyManager)
|
||||
.execInContainerForResult(anyString(), any(), anyInt());
|
||||
Cluster cluster = cluster();
|
||||
String node = spyManager.deriveClusterNodePrivateDnsName(cluster);
|
||||
|
||||
spyManager.applyComputeLabel(cluster, "container-1");
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of(), null));
|
||||
spyManager.applyComputeLabel(cluster, "container-1");
|
||||
cluster.setComputeConfig(new ComputeConfig(false, List.of(), null));
|
||||
spyManager.applyComputeLabel(cluster, "container-1");
|
||||
|
||||
InOrder order = Mockito.inOrder(spyManager);
|
||||
order.verify(spyManager).execInContainerForResult("container-1", new String[]{"kubectl", "label", "node",
|
||||
node, "--overwrite", "eks.amazonaws.com/compute-type=auto"}, 15);
|
||||
order.verify(spyManager).execInContainerForResult("container-1", new String[]{"kubectl", "label", "node",
|
||||
node, "--overwrite", "eks.amazonaws.com/compute-type-"}, 15);
|
||||
verify(spyManager, times(2)).execInContainerForResult(anyString(), any(), anyInt());
|
||||
}
|
||||
|
||||
/** With no subnets or security group known, the terms are empty lists on their keys' lines, which k3s parses. */
|
||||
@Test
|
||||
void aNodeClassWithoutSubnetsOrASecurityGroupHasEmptyTerms() {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of("general-purpose"), "arn:aws:iam::000000000000:role/node"));
|
||||
|
||||
String manifest = manager.computeManifest(cluster);
|
||||
|
||||
assertTrue(manifest.contains(" subnetSelectorTerms: []\n securityGroupSelectorTerms: []\n"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void computeWithoutANodeRoleGetsTheKindsAlone() {
|
||||
Cluster cluster = cluster();
|
||||
cluster.setComputeConfig(new ComputeConfig(true, List.of(), null));
|
||||
|
||||
String manifest = manager.computeManifest(cluster);
|
||||
|
||||
assertTrue(manifest.contains("name: nodeclasses.eks.amazonaws.com"));
|
||||
assertFalse(manifest.contains("kind: NodeClass\nmetadata:\n name: default"));
|
||||
assertFalse(manifest.contains("kind: NodePool\nmetadata"));
|
||||
}
|
||||
|
||||
private Path blockStorageCopy() {
|
||||
return tempDir.resolve("auto-mode/000000000000/us-east-1/demo")
|
||||
.resolve(EksClusterManager.BLOCK_STORAGE_MANIFEST_FILE);
|
||||
|
||||
@@ -458,6 +458,8 @@ class EksServiceTest {
|
||||
new ComputeConfig(false, List.of(), null), new StorageConfig(new BlockStorage(false)), off));
|
||||
|
||||
verify(clusterManager, times(2)).replaceNodeForServiceLb(running);
|
||||
// Each Auto Mode update gives the running node the pools it names, or none once compute is off.
|
||||
verify(clusterManager, times(3)).applyCompute(eq("k3s-auto-running"), eq(running));
|
||||
}
|
||||
|
||||
/** An authentication change whose node entry failed makes it on the retry the client token returns. */
|
||||
|
||||
Reference in new issue
Block a user