diff --git a/docs/services/ec2.md b/docs/services/ec2.md index cf7507da33..c4f9003900 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1486,6 +1486,37 @@ include every image that process should expose. Missing or invalid files fail on catalog use; leaving the setting unset preserves the bundled catalog. Containerized Floci needs the file mounted at the configured container path. +For an image whose guest kubelet registers its own EKS Node, set +`kubeletRegistersNode: true` on that image entry. This is explicit image capability +metadata, independent of `guestRuntime`: systemd guests do not necessarily run +kubelet. For example, a locally built worker can use: + +```yaml +defaultDockerImage: example/base:1 +images: + - imageId: ami-kubelet-worker + aliases: [ami-kubelet-alias] + dockerImage: example/kubelet-worker:1 + name: kubelet-worker + description: Linux guest with kubelet and cluster bootstrap support + architecture: arm64 + creationDate: '2026-01-01T00:00:00.000Z' + guestRuntime: systemd + kubeletRegistersNode: true +``` + +With this capability, Floci tracks the instance's cluster join and notifies join +listeners, but does not create a synthetic Kubernetes Node or patch its capacity, +allocatable resources or Ready condition. The same rule applies when joined nodes +are replayed after cluster recreation or process restart. Both the image ID and its +aliases use the capability. Keep the configured catalog available across restarts. +Omitting the field, setting it to `false`, or using an unknown image ID preserves +simulated Node registration. No bundled image opts in automatically. + +This setting does not install, start or authenticate kubelet, or set up worker +networking. The image and its bootstrap configuration must do that. If kubelet +fails to join, Floci will not synthesize a Ready Node to hide the failure. + ### Public IPv4 addresses Whether an instance has an automatic public IPv4 address is decided by the same rule with and diff --git a/docs/services/eks.md b/docs/services/eks.md index 85e4149f21..1e5780047d 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -554,7 +554,7 @@ For local testing workflows that rely on automatic volume binding without a CSI ## Joining EC2 instances as cluster nodes -Floci allows EC2 instances to join an EKS cluster as Kubernetes worker nodes. Launching an instance via `RunInstances` with user data targeting a cluster automatically registers a matching Kubernetes node. +Floci allows EC2 instances to join an EKS cluster as Kubernetes worker nodes. Launching an instance via `RunInstances` with user data targeting a cluster records its join and, by default, registers a matching Kubernetes node. ### Join mechanisms @@ -566,15 +566,27 @@ On AWS, EC2 does not fail instance launches if a target cluster is missing. Floc ### Node metadata and AWS outcome alignment -When an instance joins a cluster, Floci registers a Kubernetes `Node` matching AWS conventions: +For simulated workers, Floci registers a Kubernetes `Node` matching AWS conventions: - **Node name**: Uses the instance's private DNS name (`privateDnsName`), matching AWS EKS conventions. - **Provider ID**: Set to `spec.providerID: aws:////`. - **Labels & Status**: Includes topology and instance-type labels, ready status, internal IP, and catalog capacity. - **EC2 persistence**: The instance remains an authentic EC2 instance reported by `DescribeInstances`. +### Guest kubelet registration + +For custom images that run kubelet, set `kubeletRegistersNode: true` in the +[EC2 image catalog](ec2.md#external-image-catalog). Floci then leaves Node creation, +capacity, allocatable resources and readiness to the guest kubelet, on both initial +join and replay. Join tracking, persisted instance IDs and registration listeners +still run. The image and bootstrap configuration remain responsible for starting +and authenticating kubelet and providing worker networking. + +The capability is opt-in per image, including its aliases. A systemd runtime alone +does not enable it; omitted or false values keep the simulated behavior. + ### Differences and limitations -- Floci registers the `Node` directly in the control plane with matching provider ID, labels, and ready status. +- For simulated workers, Floci registers the `Node` directly in the control plane with matching provider ID, labels, and ready status. - Node cleanup on termination is handled in part two; an instance can belong to at most one cluster at a time. ## Configuration diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java index 1a61c621d1..a6867719ba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ImageCatalog.java @@ -215,6 +215,8 @@ public class Ec2ImageCatalog { public Boolean advertised; public String guestRuntime; public Boolean cloudInit; + /** The guest kubelet owns EKS Node creation and status instead of Floci simulating them. */ + public Boolean kubeletRegistersNode; public String provenance; public boolean advertised() { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index a60d4bc651..411327c9ba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -35,6 +35,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ec2.ClusterNodeInstanceProvider; +import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog; import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog; import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType; import io.github.hectorvent.floci.services.ec2.Ec2MetadataProxy; @@ -175,6 +176,7 @@ public class EksClusterManager private final EksOidcService oidcService; private final FlociCertificateAuthority certificateAuthority; private final ContainerLogStreamer logStreamer; + private final Ec2ImageCatalog imageCatalog; private final Ec2InstanceTypeCatalog instanceTypeCatalog = new Ec2InstanceTypeCatalog(); private final Map clusterNodeInstances = new ConcurrentHashMap<>(); private final Map> joinedClusterInstances = new ConcurrentHashMap<>(); @@ -451,6 +453,27 @@ public class EksClusterManager ContainerLogStreamer logStreamer, StorageBackend nodeGroupStorage, long archiveRetryBackoffMillis) { + this(containerBuilder, lifecycleManager, containerDetector, portAllocator, + dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, + oidcService, certificateAuthority, logStreamer, nodeGroupStorage, + archiveRetryBackoffMillis, new Ec2ImageCatalog()); + } + + EksClusterManager(ContainerBuilder containerBuilder, + ContainerLifecycleManager lifecycleManager, + ContainerDetector containerDetector, + PortAllocator portAllocator, + DockerHostResolver dockerHostResolver, + EcrRegistryManager ecrRegistryManager, + EmulatorConfig config, + RegionResolver regionResolver, + Ec2MetadataServer metadataServer, + EksOidcService oidcService, + FlociCertificateAuthority certificateAuthority, + ContainerLogStreamer logStreamer, + StorageBackend nodeGroupStorage, + long archiveRetryBackoffMillis, + Ec2ImageCatalog imageCatalog) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.containerDetector = containerDetector; @@ -465,6 +488,7 @@ public class EksClusterManager this.logStreamer = logStreamer; this.nodeGroupStorage = nodeGroupStorage; this.archiveRetryBackoffMillis = archiveRetryBackoffMillis; + this.imageCatalog = imageCatalog; } @Inject @@ -480,14 +504,15 @@ public class EksClusterManager EksOidcService oidcService, FlociCertificateAuthority certificateAuthority, ContainerLogStreamer logStreamer, - StorageFactory storageFactory) { + StorageFactory storageFactory, + Ec2ImageCatalog imageCatalog) { this(containerBuilder, lifecycleManager, containerDetector, portAllocator, dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, certificateAuthority, logStreamer, storageFactory != null ? storageFactory.create("eks", "eks-nodegroups.json", new TypeReference>() {}) - : null); + : null, RetryingTarCopier.DEFAULT_BACKOFF_MS, imageCatalog); } /** @@ -3117,6 +3142,11 @@ public class EksClusterManager } private void registerNodeInCluster(Cluster cluster, String containerId, Instance instance) { + if (imageCatalog.findByIdOrAlias(instance.getImageId()) + .map(image -> Boolean.TRUE.equals(image.kubeletRegistersNode)).orElse(false)) { + // Do not race the guest kubelet with a status-less Node or synthetic Ready status. + return; + } String region = instance.getRegion() != null ? instance.getRegion() : clusterRegion(cluster); String nodeName = deriveInstanceNodeName(instance, region); try { diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExternalImageCatalogTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExternalImageCatalogTest.java index 88611b169b..1099b00a12 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExternalImageCatalogTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ExternalImageCatalogTest.java @@ -52,6 +52,16 @@ class Ec2ExternalImageCatalogTest { assertEquals("linux/386", resolver.resolveImage("ami-local-i386").dockerPlatform()); } + @Test + void kubeletRegistrationIsAnExplicitImageCapability() { + Ec2ImageCatalog catalog = new Ec2ImageCatalog(Path.of("src/test/resources/ec2/kubelet-image-catalog.yaml")); + assertEquals(Boolean.TRUE, catalog.findByIdOrAlias("ami-kubelet-worker").orElseThrow().kubeletRegistersNode); + assertEquals(Boolean.TRUE, catalog.findByIdOrAlias("ami-kubelet-alias").orElseThrow().kubeletRegistersNode); + assertNull(catalog.findByIdOrAlias("ami-systemd-guest").orElseThrow().kubeletRegistersNode); + assertEquals(Boolean.FALSE, catalog.findByIdOrAlias("ami-simulated-worker").orElseThrow().kubeletRegistersNode); + assertTrue(new Ec2ImageCatalog().images().stream().noneMatch(image -> Boolean.TRUE.equals(image.kubeletRegistersNode))); + } + @Test void missingOrInvalidFileFailsInsteadOfSilentlyUsingBundledImages() throws Exception { assertThrows(IllegalStateException.class, diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index 90da0c86ab..bdc62da191 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -36,6 +36,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.common.docker.PortAllocator; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog; import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog; import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer; import io.github.hectorvent.floci.services.ec2.model.Instance; @@ -4165,13 +4166,16 @@ class EksClusterManagerTest { EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class); when(config.services()).thenReturn(services); when(services.eks()).thenReturn(Mockito.mock(EmulatorConfig.EksServiceConfig.class)); + EmulatorConfig.Ec2ServiceConfig ec2 = Mockito.mock(EmulatorConfig.Ec2ServiceConfig.class); + when(services.ec2()).thenReturn(ec2); + when(ec2.imageCatalogPath()).thenReturn(Optional.of("src/test/resources/ec2/kubelet-image-catalog.yaml")); manager = Mockito.spy(new EksClusterManager(Mockito.mock(ContainerBuilder.class), Mockito.mock(ContainerLifecycleManager.class), Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class), Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class), config, new RegionResolver("us-east-1", "000000000000"), Mockito.mock(Ec2MetadataServer.class), Mockito.mock(EksOidcService.class), inlineMock(FlociCertificateAuthority.class), Mockito.mock(ContainerLogStreamer.class), - new InMemoryStorage<>())); + new InMemoryStorage<>(), 0, new Ec2ImageCatalog(config))); } private Cluster clusterNamed(String name, String containerId) { @@ -4209,6 +4213,62 @@ class EksClusterManagerTest { assertFalse(manager.isInstanceJoined(cluster, "i-0123456789abcdef0")); } + @ParameterizedTest + @ValueSource(strings = {"ami-kubelet-worker", "ami-kubelet-alias"}) + void kubeletOwnsNodeRegistrationIncludingClusterReplay(String imageId) { + Cluster cluster = clusterNamed("kubelet-cluster", "kubelet-container"); + Instance inst = createInstance("i-kubelet", "us-east-1a", "t4g.medium", "arm64", "10.0.1.51"); + inst.setImageId(imageId); + doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager) + .execInContainerForResult(anyString(), any(), anyInt()); + List notifications = new ArrayList<>(); + manager.addNodeRegistrationListener(notifications::add); + + manager.joinInstance(cluster, inst); + manager.joinInstance(cluster, inst); + assertTrue(manager.isInstanceJoined(cluster, inst.getInstanceId())); + assertTrue(manager.isJoinedNode(cluster, manager.deriveInstanceNodeName(inst, inst.getRegion()))); + assertEquals(List.of(inst), manager.getJoinedInstances(cluster)); + assertEquals(Map.of(inst.getInstanceId(), "us-east-1"), cluster.getJoinedInstanceIds()); + assertEquals(List.of(inst), notifications); + assertThrows(AwsException.class, () -> manager.joinInstance(clusterNamed("other", "other-container"), inst)); + + manager.registerAllJoinedNodes(cluster, "recreated-container"); + manager.unregisterMetadataEndpoint(cluster); + // Process restore rebuilds the manager's join map from the persisted instance IDs. + manager.joinInstance(cluster, inst); + assertEquals(Map.of(inst.getInstanceId(), "us-east-1"), cluster.getJoinedInstanceIds()); + assertEquals(List.of(inst, inst), notifications); + verify(manager, never()).execInContainerForResult(anyString(), any(), anyInt()); + } + + @ParameterizedTest + @ValueSource(strings = {"ami-systemd-guest", "ami-simulated-worker", "ami-unknown"}) + void imagesWithoutKubeletOwnershipKeepSyntheticRegistrationOnJoinAndReplay(String imageId) { + Cluster cluster = clusterNamed("simulated-cluster", "simulated-container"); + Instance inst = createInstance("i-simulated", "us-east-1a", "t3.medium", "x86_64", "10.0.1.52"); + inst.setImageId(imageId); + ArgumentCaptor commands = ArgumentCaptor.forClass(String[].class); + doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager) + .execInContainerForResult(anyString(), commands.capture(), anyInt()); + + Instance kubelet = createInstance("i-kubelet", "us-east-1a", "t4g.medium", "arm64", "10.0.1.53"); + kubelet.setImageId("ami-kubelet-worker"); + manager.joinInstance(cluster, kubelet); + manager.joinInstance(cluster, inst); + manager.registerAllJoinedNodes(cluster, "recreated-container"); + + assertEquals(2, manager.getJoinedInstances(cluster).size()); + assertEquals(4, commands.getAllValues().size()); + for (int offset : List.of(0, 2)) { + assertTrue(commands.getAllValues().get(offset)[2].contains("kubectl apply -f -")); + String[] patch = commands.getAllValues().get(offset + 1); + assertEquals("--subresource=status", patch[4]); + assertTrue(patch[7].contains("KubeletReady")); + assertTrue(patch[7].contains("\"memory\":\"4096Mi\"")); + } + } + @Test void joinInstanceRegistersNodeInRunningContainerWithExpectedManifest() { Cluster cluster = clusterNamed("live-cluster", "live-container-123"); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksKubeletRegistrationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksKubeletRegistrationIntegrationTest.java new file mode 100644 index 0000000000..2829890f38 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksKubeletRegistrationIntegrationTest.java @@ -0,0 +1,104 @@ +package io.github.hectorvent.floci.services.eks; + +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.docker.ContainerExec; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.eks.model.Cluster; +import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.mockito.InjectSpy; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertAll; +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +@QuarkusTest +@TestProfile(EksKubeletRegistrationIntegrationTest.ImageCatalogProfile.class) +class EksKubeletRegistrationIntegrationTest { + + public static final class ImageCatalogProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ec2.image-catalog-path", "src/test/resources/ec2/kubelet-image-catalog.yaml"); + } + } + + @Inject + EksService eksService; + + @Inject + Ec2Service ec2Service; + + @InjectSpy + EksClusterManager manager; + + @Test + void bootstrapJoinUsesConfiguredCatalogAndKeepsReplayFreeOfSyntheticWrites() { + String account = "123456789012"; + String region = "us-east-1"; + String clusterName = "kubelet-" + UUID.randomUUID().toString().substring(0, 8); + CreateClusterRequest request = new CreateClusterRequest(); + request.setName(clusterName); + request.setRoleArn("arn:aws:iam::" + account + ":role/EksClusterRole"); + Cluster cluster = RequestScopes.callAs(account, region, () -> eksService.createCluster(request)); + cluster.setContainerId("mock-kubelet-control-plane"); + doReturn(new ContainerExec.Result(0L, "", "", false)).when(manager) + .execInContainerForResult(anyString(), any(), anyInt()); + String script = "#!/bin/bash\n/etc/eks/bootstrap.sh " + clusterName; + String instanceId = null; + try { + instanceId = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account + "/20260101/" + region + + "/ec2/aws4_request, SignedHeaders=host, Signature=abc") + .formParam("Action", "RunInstances") + .formParam("ImageId", "ami-kubelet-alias") + .formParam("InstanceType", "t4g.medium") + .formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("UserData", Base64.getEncoder().encodeToString(script.getBytes(StandardCharsets.UTF_8))) + .post("/").then().statusCode(200) + .extract().path("RunInstancesResponse.instancesSet.item.instanceId"); + String joinedId = instanceId; + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> { + assertTrue(RequestScopes.callAs(account, region, () -> eksService.isInstanceJoined(clusterName, joinedId))); + Cluster stored = RequestScopes.callAs(account, region, () -> eksService.describeCluster(clusterName)); + assertEquals(region, stored.getJoinedInstanceIds().get(joinedId)); + }); + Instance instance = RequestScopes.callAs(account, region, + () -> ec2Service.getInstance(region, joinedId).orElseThrow()); + assertEquals("ami-kubelet-alias", instance.getImageId()); + manager.registerAllJoinedNodes(cluster, "recreated-control-plane"); + verify(manager, never()).execInContainerForResult(anyString(), any(), anyInt()); + } finally { + String launchedId = instanceId; + RequestScopes.runAs(account, region, () -> assertAll("Clean up worker and cluster independently", + () -> manager.unregisterMetadataEndpoint(cluster), + () -> { + if (launchedId != null) { + ec2Service.terminateInstances(region, List.of(launchedId)); + assertEquals("terminated", ec2Service.getInstance(region, launchedId).orElseThrow().getState().getName()); + } + }, + () -> eksService.deleteCluster(clusterName))); + } + } +} diff --git a/src/test/resources/ec2/kubelet-image-catalog.yaml b/src/test/resources/ec2/kubelet-image-catalog.yaml new file mode 100644 index 0000000000..4edf3079a7 --- /dev/null +++ b/src/test/resources/ec2/kubelet-image-catalog.yaml @@ -0,0 +1,25 @@ +defaultDockerImage: example/base:1 +images: + - imageId: ami-kubelet-worker + aliases: [ami-kubelet-alias] + dockerImage: example/kubelet-worker:1 + name: kubelet-worker + description: Guest owns Kubernetes Node registration + architecture: arm64 + creationDate: '2026-01-01T00:00:00.000Z' + guestRuntime: systemd + kubeletRegistersNode: true + - imageId: ami-systemd-guest + dockerImage: example/systemd-guest:1 + name: systemd-guest + description: Systemd alone does not imply a kubelet + architecture: x86_64 + creationDate: '2026-01-01T00:00:00.000Z' + guestRuntime: systemd + - imageId: ami-simulated-worker + dockerImage: example/base:1 + name: simulated-worker + description: Explicitly simulated Kubernetes Node registration + architecture: x86_64 + creationDate: '2026-01-01T00:00:00.000Z' + kubeletRegistersNode: false