Light, fluffy, and always free - The AWS Local Emulator alternative
feat(eks): implement EKS service with real k3s data plane support (#493)
Hector Ventura63ed81c59d50
diff --git a/README.md b/README.mdindex 7878cdd6d8..beb35e8e12 100644--- a/README.md+++ b/README.md@@ -55,6 +55,7 @@| Kinesis (streams, shards, fan-out) | ✅ | ⚠️ Partial || KMS (sign, verify, re-encrypt) | ✅ | ⚠️ Partial || ECS (clusters, services, tasks) | ✅ | ❌ |+| EKS (clusters, mock + real k3s) | ✅ | ❌ || EC2 (VPCs, instances, security groups) | ✅ | ⚠️ Partial || Native binary | ✅ ~40 MB | ❌ |@@ -78,7 +79,7 @@ flowchart LRendsubgraph Containers ["Container Services 🐳"]- C["Lambda\nElastiCache\nRDS\nECS\nMSK"]+ C["Lambda\nElastiCache\nRDS\nECS\nMSK\nEKS"]endRouter --> Stateless@@ -133,12 +134,13 @@ flowchart LR| **AppConfig** | In-process | Applications, environments, profiles, hosted configuration versions, deployments || **AppConfigData** | In-process | Configuration sessions, dynamic configuration retrieval || **Bedrock Runtime** | In-process (stub) | Dummy Converse and InvokeModel responses for local development; streaming returns 501 |+| **EKS** | **Real Docker containers** (mock mode available) | Clusters, tagging; real mode starts k3s per cluster with a live Kubernetes API server |-> **Lambda, ElastiCache, RDS, MSK, and ECS** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane.+> **Lambda, ElastiCache, RDS, MSK, ECS, and EKS** spin up real Docker containers and support IAM authentication and SigV4 request signing — the same auth flow as production AWS. **ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane.>> For per-service operation counts and endpoint protocols, see the [Services Overview](https://floci.io/floci/services/) in the documentation site.-**34 AWS services supported.**+**35 AWS services supported.**## Persistence & Storage Modesdiff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex d0365a673c..cc1b2f8df3 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -189,6 +189,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>ecr</artifactId></dependency>+ <!-- EKS client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>eks</artifactId>+ </dependency><!-- EventBridge Scheduler client --><dependency><groupId>software.amazon.awssdk</groupId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 0ce0f439d2..550c593948 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -37,6 +37,7 @@ import software.amazon.awssdk.services.acm.AcmClient;import software.amazon.awssdk.services.ec2.Ec2Client;import software.amazon.awssdk.services.ecr.EcrClient;import software.amazon.awssdk.services.ecs.EcsClient;+import software.amazon.awssdk.services.eks.EksClient;import software.amazon.awssdk.services.scheduler.SchedulerClient;import software.amazon.awssdk.services.appconfig.AppConfigClient;import software.amazon.awssdk.services.appconfigdata.AppConfigDataClient;@@ -462,6 +463,14 @@ public final class TestFixtures {.build();}+ public static EksClient eksClient() {+ return EksClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static SchedulerClient schedulerClient() {return SchedulerClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksTest.javanew file mode 100644index 0000000000..961ee05206--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EksTest.java@@ -0,0 +1,162 @@+package com.floci.test;++import org.junit.jupiter.api.*;+import software.amazon.awssdk.services.eks.EksClient;+import software.amazon.awssdk.services.eks.model.*;++import java.util.List;+import java.util.Map;++import static org.assertj.core.api.Assertions.*;++@DisplayName("EKS Elastic Kubernetes Service")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class EksTest {++ private static EksClient eks;+ private static String clusterName;+ private static String clusterArn;++ @BeforeAll+ static void setup() {+ eks = TestFixtures.eksClient();+ clusterName = "sdk-test-cluster-" + (System.currentTimeMillis() % 100000);+ }++ @AfterAll+ static void cleanup() {+ if (eks != null) {+ try {+ eks.deleteCluster(DeleteClusterRequest.builder()+ .name(clusterName)+ .build());+ } catch (Exception ignored) {}+ eks.close();+ }+ }++ @Test+ @Order(1)+ void createCluster() {+ CreateClusterResponse response = eks.createCluster(CreateClusterRequest.builder()+ .name(clusterName)+ .roleArn("arn:aws:iam::000000000000:role/eks-role")+ .resourcesVpcConfig(VpcConfigRequest.builder()+ .subnetIds(List.of())+ .securityGroupIds(List.of())+ .build())+ .version("1.29")+ .tags(Map.of("env", "test"))+ .build());++ assertThat(response.cluster()).isNotNull();+ assertThat(response.cluster().name()).isEqualTo(clusterName);+ assertThat(response.cluster().arn()).isNotBlank();+ assertThat(response.cluster().version()).isEqualTo("1.29");+ assertThat(response.cluster().status()).isIn(ClusterStatus.CREATING, ClusterStatus.ACTIVE);++ clusterArn = response.cluster().arn();+ }++ @Test+ @Order(2)+ void listClusters() {+ ListClustersResponse response = eks.listClusters(ListClustersRequest.builder().build());++ assertThat(response.clusters()).isNotNull();+ assertThat(response.clusters()).contains(clusterName);+ }++ @Test+ @Order(3)+ void describeCluster() {+ DescribeClusterResponse response = eks.describeCluster(DescribeClusterRequest.builder()+ .name(clusterName)+ .build());++ assertThat(response.cluster()).isNotNull();+ assertThat(response.cluster().name()).isEqualTo(clusterName);+ assertThat(response.cluster().arn()).isEqualTo(clusterArn);+ assertThat(response.cluster().status()).isIn(ClusterStatus.CREATING, ClusterStatus.ACTIVE);+ assertThat(response.cluster().resourcesVpcConfig()).isNotNull();+ assertThat(response.cluster().kubernetesNetworkConfig()).isNotNull();+ assertThat(response.cluster().certificateAuthority()).isNotNull();+ }++ @Test+ @Order(4)+ void describeClusterNotFound() {+ assertThatThrownBy(() -> eks.describeCluster(DescribeClusterRequest.builder()+ .name("nonexistent-cluster-xyz")+ .build()))+ .isInstanceOf(ResourceNotFoundException.class);+ }++ @Test+ @Order(5)+ void tagResource() {+ eks.tagResource(TagResourceRequest.builder()+ .resourceArn(clusterArn)+ .tags(Map.of("team", "platform", "cost-center", "eng"))+ .build());++ // Verify tags are stored+ ListTagsForResourceResponse listResponse = eks.listTagsForResource(+ ListTagsForResourceRequest.builder()+ .resourceArn(clusterArn)+ .build());++ assertThat(listResponse.tags()).containsEntry("team", "platform");+ assertThat(listResponse.tags()).containsEntry("cost-center", "eng");+ assertThat(listResponse.tags()).containsEntry("env", "test");+ }++ @Test+ @Order(6)+ void untagResource() {+ eks.untagResource(UntagResourceRequest.builder()+ .resourceArn(clusterArn)+ .tagKeys("env")+ .build());++ ListTagsForResourceResponse listResponse = eks.listTagsForResource(+ ListTagsForResourceRequest.builder()+ .resourceArn(clusterArn)+ .build());++ assertThat(listResponse.tags()).doesNotContainKey("env");+ assertThat(listResponse.tags()).containsKey("team");+ }++ @Test+ @Order(7)+ void createDuplicateClusterFails() {+ assertThatThrownBy(() -> eks.createCluster(CreateClusterRequest.builder()+ .name(clusterName)+ .roleArn("arn:aws:iam::000000000000:role/eks-role")+ .resourcesVpcConfig(VpcConfigRequest.builder().build())+ .build()))+ .isInstanceOf(ResourceInUseException.class);+ }++ @Test+ @Order(100)+ void deleteCluster() {+ DeleteClusterResponse response = eks.deleteCluster(DeleteClusterRequest.builder()+ .name(clusterName)+ .build());++ assertThat(response.cluster()).isNotNull();+ assertThat(response.cluster().name()).isEqualTo(clusterName);+ assertThat(response.cluster().status()).isEqualTo(ClusterStatus.DELETING);+ }++ @Test+ @Order(101)+ void describeDeletedClusterFails() {+ assertThatThrownBy(() -> eks.describeCluster(DescribeClusterRequest.builder()+ .name(clusterName)+ .build()))+ .isInstanceOf(ResourceNotFoundException.class);+ }+}diff --git a/docs/configuration/ports.md b/docs/configuration/ports.mdindex ca6806704e..6ee51f4a27 100644--- a/docs/configuration/ports.md+++ b/docs/configuration/ports.md@@ -7,6 +7,7 @@| `4566` | HTTP | All AWS API calls (every service) || `5100–5199` | HTTP | ECR Registry sidecar (`floci-ecr-registry`) — bound directly by that container, not the floci container || `6379–6399` | TCP | ElastiCache Redis proxy, one port per replication group |+| `6500–6599` | HTTPS | EKS k3s API server, one port per cluster (real mode only) || `7001–7099` | TCP | RDS proxy, one port per DB instance || `9200–9299` | HTTP | Lambda Runtime API (internal: consumed by spawned Lambda containers, not host-mapped) || `9400–9499` | HTTP | OpenSearch proxy, reserved for `opensearch.mode: real` (not yet available) |@@ -43,6 +44,27 @@ The port assigned to a replication group is returned in the `PrimaryEndpoint.Por!!! noteThe proxy range starts at `6379` by default (matching the standard Redis port for the first cluster). Configure the range with `FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT` and `FLOCI_SERVICES_ELASTICACHE_PROXY_MAX_PORT`.+## Ports 6500–6599 — EKS (real mode)++When you create an EKS cluster in real mode, Floci starts a k3s Docker container and binds its API server to the next available port in the `6500–6599` range. The Kubernetes endpoint returned by `DescribeCluster` points to `https://localhost:<hostPort>`.++These ports are only needed in real mode (`FLOCI_SERVICES_EKS_MOCK=false`). In mock mode no k3s containers are started and no ports are used.++```bash+# Create a cluster (real mode)+aws eks create-cluster \+ --name my-cluster \+ --role-arn arn:aws:iam::000000000000:role/eks-role \+ --resources-vpc-config subnetIds=[],securityGroupIds=[] \+ --endpoint-url http://localhost:4566++# The endpoint field in DescribeCluster tells you the API server port:+# "endpoint": "https://localhost:6500"+```++!!! note+ Configure the range with `FLOCI_SERVICES_EKS_API_SERVER_BASE_PORT` and `FLOCI_SERVICES_EKS_API_SERVER_MAX_PORT`.+## Ports 7001–7099 — RDSWhen you create an RDS DB instance, Floci starts a PostgreSQL or MySQL Docker container and creates a TCP proxy on the next available port in the `7001–7099` range.@@ -101,9 +123,12 @@ services:ports:- "4566:4566" # All AWS API calls- "6379-6399:6379-6399" # ElastiCache / Redis proxy ports+ - "6500-6599:6500-6599" # EKS k3s API server ports (real mode only)- "7001-7099:7001-7099" # RDS / PostgreSQL + MySQL proxy portsvolumes:- /var/run/docker.sock:/var/run/docker.sock```+Omit `6500-6599` if you run EKS in mock mode (`FLOCI_SERVICES_EKS_MOCK=true`).+If your application runs inside the same Docker Compose network, it can reach Floci directly on container port `4566` — the host port mapping is only needed for tools running on the host (CLI, IDE plugins, etc.).\ No newline at end of filediff --git a/docs/services/eks.md b/docs/services/eks.mdnew file mode 100644index 0000000000..a0c08cb016--- /dev/null+++ b/docs/services/eks.md@@ -0,0 +1,173 @@+# EKS (Elastic Kubernetes Service)++**Protocol:** REST-JSON+**Endpoint:** `http://localhost:4566/` (path-routed via JAX-RS)++EKS uses a standard REST API with JSON bodies — not the JSON 1.1 (`X-Amz-Target`) or Query protocol.++## Supported Operations++| Operation | Description |+|---|---|+| `CreateCluster` | Create a new EKS cluster |+| `DescribeCluster` | Describe a cluster by name |+| `ListClusters` | List all cluster names |+| `DeleteCluster` | Delete a cluster |+| `TagResource` | Add tags to a cluster |+| `UntagResource` | Remove tags from a cluster |+| `ListTagsForResource` | List tags on a cluster |++## Modes++### Mock mode (`mock: true`)++Cluster metadata is stored in-process. No Docker containers are started. The cluster transitions directly to `ACTIVE` on creation. Use this in CI or whenever you only need the EKS API shape, not a real Kubernetes API server.++### Real mode (`mock: false`, default)++Floci starts a **k3s** (`rancher/k3s`) container for each cluster. The k3s API server is exposed on a host port from the configured range (`6500–6599`). Once `/readyz` responds, the cluster transitions to `ACTIVE` and the CA certificate is extracted from the kubeconfig.++!!! note "Docker socket required"+ Real mode starts privileged Docker containers. Mount the Docker socket and set the Docker network so containers can reach each other.++```yaml+services:+ floci:+ image: hectorvent/floci:latest+ volumes:+ - /var/run/docker.sock:/var/run/docker.sock+ ports:+ - "4566:4566"+ - "6500-6599:6500-6599" # k3s API server ports (real mode only)+ environment:+ FLOCI_SERVICES_EKS_DOCKER_NETWORK: my_project_default+```++## Configuration++```yaml+floci:+ services:+ eks:+ enabled: true+ mock: false # true = metadata only, no Docker+ provider: k3s # only k3s is supported+ default-image: "rancher/k3s:latest"+ api-server-base-port: 6500 # first port in the k3s API server range+ api-server-max-port: 6599+ data-path: ./data/eks # host bind-mount root for cluster data+ docker-network: "" # inherits floci.services.docker-network if unset+ keep-running-on-shutdown: false # leave k3s containers running after Floci stops+```++### Environment Variables++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_EKS_ENABLED` | `true` | Enable the EKS service |+| `FLOCI_SERVICES_EKS_MOCK` | `false` | Metadata-only mode (no Docker) |+| `FLOCI_SERVICES_EKS_DEFAULT_IMAGE` | `rancher/k3s:latest` | k3s Docker image |+| `FLOCI_SERVICES_EKS_API_SERVER_BASE_PORT` | `6500` | First port in the k3s API server range |+| `FLOCI_SERVICES_EKS_API_SERVER_MAX_PORT` | `6599` | Last port in the k3s API server range |+| `FLOCI_SERVICES_EKS_DATA_PATH` | `./data/eks` | Host bind-mount root for cluster data |+| `FLOCI_SERVICES_EKS_DOCKER_NETWORK` | *(unset)* | Docker network for k3s containers |+| `FLOCI_SERVICES_EKS_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave k3s containers running after Floci stops |++### Mock mode (CI / tests)++Use `FLOCI_SERVICES_EKS_MOCK=true` when you only need the API shape:++```yaml+# docker-compose.yml — CI / test environment+services:+ floci:+ image: hectorvent/floci:latest+ environment:+ FLOCI_SERVICES_EKS_MOCK: "true"+```++## ARN Format++```+arn:aws:eks:<region>:<accountId>:cluster/<clusterName>+```++## Examples++```bash+export AWS_ENDPOINT_URL=http://localhost:4566+export AWS_DEFAULT_REGION=us-east-1+export AWS_ACCESS_KEY_ID=test+export AWS_SECRET_ACCESS_KEY=test++# Create a cluster+aws eks create-cluster \+ --name my-cluster \+ --role-arn arn:aws:iam::000000000000:role/eks-role \+ --resources-vpc-config subnetIds=[],securityGroupIds=[] \+ --kubernetes-version 1.29++# Describe the cluster+aws eks describe-cluster --name my-cluster++# List clusters+aws eks list-clusters++# Tag a cluster+aws eks tag-resource \+ --resource-arn arn:aws:eks:us-east-1:000000000000:cluster/my-cluster \+ --tags env=dev,team=platform++# Delete a cluster+aws eks delete-cluster --name my-cluster+```++## Java SDK Example++```java+EksClient eks = EksClient.builder()+ .endpointOverride(URI.create("http://localhost:4566"))+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create("test", "test")))+ .build();++// Create cluster+CreateClusterResponse created = eks.createCluster(r -> r+ .name("my-cluster")+ .roleArn("arn:aws:iam::000000000000:role/eks-role")+ .resourcesVpcConfig(v -> v+ .subnetIds(List.of())+ .securityGroupIds(List.of()))+ .version("1.29")+ .tags(Map.of("env", "dev")));++// Describe cluster+DescribeClusterResponse described = eks.describeCluster(r -> r+ .name("my-cluster"));++System.out.println(described.cluster().status()); // ACTIVE++// List clusters+List<String> names = eks.listClusters(r -> {}).clusters();++// Tag resource+eks.tagResource(r -> r+ .resourceArn(created.cluster().arn())+ .tags(Map.of("team", "platform")));++// Delete cluster+eks.deleteCluster(r -> r.name("my-cluster"));+```++## Not Implemented (Phase 1)++The following EKS features are not yet supported:++- Node groups (`CreateNodegroup`, `DescribeNodegroup`, `ListNodegroups`, `DeleteNodegroup`)+- Fargate profiles+- `UpdateClusterConfig` / `UpdateClusterVersion`+- Add-ons (`CreateAddon`, `DescribeAddon`, `ListAddons`)+- Identity provider configs+- Access entries and policies+- Encryption configdiff --git a/docs/services/index.md b/docs/services/index.mdindex b0f360cf58..ca4dcb2c30 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -1,6 +1,6 @@# Services Overview-Floci emulates 33 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.+Floci emulates 34 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.This page is the canonical reference for supported service counts and operation counts. Other docs (and the README) should link here rather than duplicating the table.@@ -43,10 +43,11 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [AppConfig](appconfig.md) | `/applications/...`, `/deploymentstrategies/...` | REST JSON | 16 || [AppConfigData](appconfig.md#data-plane) | `/configurationsessions`, `/configuration` | REST JSON | 2 || [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/invoke` | REST JSON | 2 (stub; streaming returns 501) |+| [EKS](eks.md) | `/clusters`, `/clusters/{name}`, `/tags/{resourceArn}` | REST JSON | 7 |-**Lambda, ElastiCache, RDS, and ECS** spin up real Docker containers and support IAM authentication and SigV4 request signing, the same auth flow as production AWS.+**Lambda, ElastiCache, RDS, ECS, and EKS** spin up real Docker containers and support IAM authentication and SigV4 request signing, the same auth flow as production AWS.-**ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane.+**ECR** runs a shared `registry:2` container so the stock `docker` client can push and pull image bytes against repositories returned by the AWS-shaped control plane. **EKS** (real mode) starts a k3s container per cluster and exposes the Kubernetes API server on a host port.## Common Setupdiff --git a/mkdocs.yml b/mkdocs.ymlindex 7f6fe19185..13794459a0 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -95,6 +95,7 @@ nav:- ACM: services/acm.md- ECS: services/ecs.md- ECR: services/ecr.md+ - EKS: services/eks.md- OpenSearch: services/opensearch.md- EC2: services/ec2.md- AppConfig: services/appconfig.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 711f1f0c25..3afe75a0bc 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -235,6 +235,7 @@ public interface EmulatorConfig {EcrServiceConfig ecr();ResourceGroupsTaggingServiceConfig tagging();BedrockRuntimeServiceConfig bedrockRuntime();+ EksServiceConfig eks();}interface SsmServiceConfig {@@ -574,6 +575,36 @@ public interface EmulatorConfig {boolean enabled();}+ interface EksServiceConfig {+ @WithDefault("true")+ boolean enabled();++ /** When true, clusters go straight to ACTIVE without starting real Docker containers. */+ @WithDefault("false")+ boolean mock();++ @WithDefault("k3s")+ String provider();++ @WithDefault("rancher/k3s:latest")+ String defaultImage();++ @WithDefault("6500")+ int apiServerBasePort();++ @WithDefault("6599")+ int apiServerMaxPort();++ @WithDefault("./data/eks")+ String dataPath();++ /** Docker network to attach k3s containers to. Empty = default bridge. */+ Optional<String> dockerNetwork();++ @WithDefault("false")+ boolean keepRunningOnShutdown();+ }+interface InitHooksConfig {@WithDefault("/bin/sh")String shellExecutable();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 3396651097..7b41c3e444 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.appconfig.AppConfigDataController;import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeController;import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;+import io.github.hectorvent.floci.services.eks.EksController;import io.github.hectorvent.floci.services.lambda.LambdaController;import io.github.hectorvent.floci.services.opensearch.OpenSearchController;import io.github.hectorvent.floci.services.ses.SesController;@@ -193,7 +194,11 @@ public class ResolvedServiceCatalog {// id too as a safety net (catalog lookup is exact-match).Set.of("bedrock", "bedrock-runtime"),Set.of(),- Set.of(BedrockRuntimeController.class))+ Set.of(BedrockRuntimeController.class)),+ descriptor("eks", "eks", config.services().eks().enabled(), true,+ "eks", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,+ protocols(ServiceProtocol.REST_JSON),+ Set.of(), Set.of("eks"), Set.of(), Set.of(EksController.class))));}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.javaindex d5683c52ce..3f41e02b40 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java@@ -8,6 +8,7 @@ import jakarta.inject.Inject;import jakarta.ws.rs.Consumes;import jakarta.ws.rs.DELETE;import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;import jakarta.ws.rs.PUT;import jakarta.ws.rs.Path;import jakarta.ws.rs.PathParam;@@ -72,6 +73,15 @@ public class SharedTagsController {return Response.ok(root).build();}+ @POST+ @Path("/{arn: .*}")+ @Consumes(MediaType.APPLICATION_JSON)+ public Response tagResourcePost(@Context HttpHeaders headers,+ @PathParam("arn") String arn,+ String body) {+ return tagResource(headers, arn, body);+ }+@PUT@Path("/{arn: .*}")@Consumes(MediaType.APPLICATION_JSON)diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.javaindex 0e34d17944..f036c9afb4 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java@@ -72,6 +72,7 @@ public class ContainerBuilder {private final List<Bind> binds = new ArrayList<>();private final List<String> extraHosts = new ArrayList<>();private LogConfig logConfig;+ private boolean privileged;Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver) {this.image = image;@@ -268,6 +269,15 @@ public class ContainerBuilder {return this;}+ /**+ * Runs the container in privileged mode (required for k3s and similar containers+ * that need full system access).+ */+ public Builder withPrivileged(boolean privileged) {+ this.privileged = privileged;+ return this;+ }+/*** Builds the immutable ContainerSpec.*/@@ -285,7 +295,8 @@ public class ContainerBuilder {List.copyOf(mounts),List.copyOf(binds),List.copyOf(extraHosts),- logConfig+ logConfig,+ privileged);}}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.javaindex 6d5f6f2236..ebeb1eb1ef 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java@@ -254,6 +254,11 @@ public class ContainerLifecycleManager {private HostConfig buildHostConfig(ContainerSpec spec) {HostConfig hostConfig = HostConfig.newHostConfig();+ // Privileged mode (required for e.g. k3s containers)+ if (spec.privileged()) {+ hostConfig.withPrivileged(true);+ }+// Memory limitif (spec.hasMemoryLimit()) {hostConfig.withMemory(spec.memoryBytes());diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.javaindex 1c351e2824..b879e3f2ba 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java@@ -24,6 +24,7 @@ import java.util.Map;* @param binds Legacy bind mounts (prefer mounts for new code)* @param extraHosts Extra /etc/hosts entries as "hostname:ip" strings* @param logConfig Docker log driver configuration (null = daemon default)+ * @param privileged Whether to run the container in privileged mode (required for k3s)*/public record ContainerSpec(String image,@@ -38,14 +39,15 @@ public record ContainerSpec(List<Mount> mounts,List<Bind> binds,List<String> extraHosts,- LogConfig logConfig+ LogConfig logConfig,+ boolean privileged) {/*** Creates a minimal spec with just the image name.* All other fields will be null or empty lists.*/public ContainerSpec(String image) {- this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null);+ this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false);}/**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.javanew file mode 100644index 0000000000..592a648eb4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java@@ -0,0 +1,252 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.core.common.docker.PortAllocator;+import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;+import io.github.hectorvent.floci.services.eks.model.Cluster;+import com.github.dockerjava.api.async.ResultCallback;+import com.github.dockerjava.api.command.ExecCreateCmdResponse;+import com.github.dockerjava.api.model.Frame;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.io.IOException;+import java.net.HttpURLConnection;+import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.List;+import java.util.concurrent.TimeUnit;++/**+ * Manages the Docker lifecycle of k3s containers for real-mode EKS clusters.+ * Not used when {@code floci.services.eks.mock=true}.+ */+@ApplicationScoped+public class EksClusterManager {++ private static final Logger LOG = Logger.getLogger(EksClusterManager.class);+ private static final int K3S_API_SERVER_PORT = 6443;++ private final ContainerBuilder containerBuilder;+ private final ContainerLifecycleManager lifecycleManager;+ private final ContainerDetector containerDetector;+ private final PortAllocator portAllocator;+ private final EmulatorConfig config;++ @Inject+ public EksClusterManager(ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ ContainerDetector containerDetector,+ PortAllocator portAllocator,+ EmulatorConfig config) {+ this.containerBuilder = containerBuilder;+ this.lifecycleManager = lifecycleManager;+ this.containerDetector = containerDetector;+ this.portAllocator = portAllocator;+ this.config = config;+ }++ /**+ * Starts a k3s container for the given cluster. Updates the cluster with+ * the container ID and host port. The cluster status remains CREATING until+ * {@link #isReady(Cluster)} returns true and {@link #finalizeCluster(Cluster)} is called.+ */+ public void startCluster(Cluster cluster) {+ String image = config.services().eks().defaultImage();+ String containerName = "floci-eks-" + cluster.getName();++ LOG.infov("Starting k3s container for EKS cluster: {0} using image {1}",+ cluster.getName(), image);++ // Allocate host port for the k3s API server+ int hostPort = portAllocator.allocate(+ config.services().eks().apiServerBasePort(),+ config.services().eks().apiServerMaxPort());++ // Ensure data directory exists+ Path dataPath = Path.of(config.services().eks().dataPath(), cluster.getName());+ try {+ Files.createDirectories(dataPath);+ } catch (IOException e) {+ LOG.warnv("Could not create EKS data directory {0}: {1}", dataPath, e.getMessage());+ }++ // Remove any stale container+ lifecycleManager.removeIfExists(containerName);++ // Build container spec+ String hostDataPath;+ String hostPersistentPath = config.storage().hostPersistentPath();+ boolean isAbsoluteHostPath = hostPersistentPath.startsWith("/");++ if (isAbsoluteHostPath) {+ String dataPathStr = dataPath.toAbsolutePath().normalize().toString();+ String persistentPathStr = Path.of(config.storage().persistentPath()).toAbsolutePath().normalize().toString();+ hostDataPath = dataPathStr.replace(persistentPathStr, hostPersistentPath);+ } else {+ // Relative or named-volume path: when running inside Docker (DinD), a relative path+ // refers to a path inside this container that the host daemon cannot bind-mount.+ // Use a named Docker volume per cluster instead — the host daemon manages it directly.+ hostDataPath = "floci-eks-" + cluster.getName();+ }++ ContainerSpec spec = containerBuilder.newContainer(image)+ .withName(containerName)+ .withCmd(List.of("server",+ "--disable=traefik",+ "--tls-san=localhost",+ "--kube-apiserver-arg=storage-backend=sqlite3",+ "--kube-apiserver-arg=etcd-servers=unix:///tmp/kine.sock"))+ .withEnv("K3S_KUBECONFIG_MODE", "644")+ .withPortBinding(K3S_API_SERVER_PORT, hostPort)+ .withBind(hostDataPath, "/var/lib/rancher/k3s")+ .withDockerNetwork(config.services().eks().dockerNetwork())+ .withPrivileged(true)+ .withLogRotation()+ .build();++ ContainerInfo info = lifecycleManager.createAndStart(spec);+ cluster.setContainerId(info.containerId());++ // Set a preliminary endpoint (will be confirmed after readiness check)+ if (containerDetector.isRunningInContainer()) {+ cluster.setEndpoint("https://" + containerName + ":" + K3S_API_SERVER_PORT);+ } else {+ cluster.setEndpoint("https://localhost:" + hostPort);+ }++ LOG.infov("k3s container {0} started for cluster {1} on port {2}",+ info.containerId(), cluster.getName(), hostPort);+ }++ /**+ * Checks whether the k3s API server is ready by polling its /readyz endpoint.+ */+ public boolean isReady(Cluster cluster) {+ String endpoint = cluster.getEndpoint();+ if (endpoint == null || cluster.getContainerId() == null) {+ return false;+ }++ // /livez endpoint on the k3s API server (usually unauthenticated)+ String livezUrl = endpoint + "/livez";+ try {+ HttpURLConnection conn = (HttpURLConnection) URI.create(livezUrl).toURL().openConnection();+ conn.setRequestMethod("GET");+ conn.setConnectTimeout(2000);+ conn.setReadTimeout(2000);+ // k3s uses self-signed TLS — disable verification+ if (conn instanceof javax.net.ssl.HttpsURLConnection https) {+ disableSslVerification(https);+ }+ int code = conn.getResponseCode();+ return code == 200 || code == 401 || code == 403;+ } catch (Exception e) {+ return false;+ }+ }++ /**+ * Extracts the kubeconfig from the running k3s container, rewrites the server URL,+ * and sets the certificate authority data on the cluster.+ */+ public void finalizeCluster(Cluster cluster) {+ String containerId = cluster.getContainerId();+ if (containerId == null) {+ return;+ }++ try {+ String kubeconfigYaml = execInContainer(containerId,+ new String[]{"cat", "/etc/rancher/k3s/k3s.yaml"});++ // Extract CA data+ String caData = extractYamlField(kubeconfigYaml, "certificate-authority-data");+ if (caData != null) {+ cluster.setCertificateAuthority(new CertificateAuthority(caData.trim()));+ }++ 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}",+ cluster.getName(), e.getMessage());+ }+ }++ /**+ * Stops and removes the k3s container for the given cluster.+ */+ public void stopCluster(Cluster cluster) {+ if (cluster.getContainerId() == null) {+ return;+ }+ if (config.services().eks().keepRunningOnShutdown()) {+ LOG.infov("Leaving k3s container for cluster {0} running", cluster.getName());+ return;+ }+ lifecycleManager.stopAndRemove(cluster.getContainerId(), null);+ LOG.infov("Stopped k3s container for cluster {0}", cluster.getName());+ }++ private String execInContainer(String containerId, String[] cmd) throws Exception {+ var dockerClient = lifecycleManager.getDockerClient();+ ExecCreateCmdResponse exec = dockerClient+ .execCreateCmd(containerId)+ .withCmd(cmd)+ .withAttachStdout(true)+ .withAttachStderr(true)+ .exec();++ StringBuilder output = new StringBuilder();+ boolean completed = dockerClient.execStartCmd(exec.getId())+ .exec(new ResultCallback.Adapter<Frame>() {+ @Override+ public void onNext(Frame frame) {+ output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));+ }+ })+ .awaitCompletion(10, TimeUnit.SECONDS);++ if (!completed) {+ throw new RuntimeException("exec timed out in container " + containerId);+ }+ return output.toString();+ }++ private String extractYamlField(String yaml, String fieldName) {+ for (String line : yaml.split("\n")) {+ String trimmed = line.trim();+ if (trimmed.startsWith(fieldName + ":")) {+ return trimmed.substring(fieldName.length() + 1).trim();+ }+ }+ return null;+ }++ @SuppressWarnings("java:S4830")+ private void disableSslVerification(javax.net.ssl.HttpsURLConnection conn) {+ try {+ javax.net.ssl.TrustManager[] trustAll = new javax.net.ssl.TrustManager[]{+ new javax.net.ssl.X509TrustManager() {+ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }+ public void checkClientTrusted(java.security.cert.X509Certificate[] c, String a) {}+ public void checkServerTrusted(java.security.cert.X509Certificate[] c, String a) {}+ }+ };+ javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLS");+ sc.init(null, trustAll, new java.security.SecureRandom());+ conn.setSSLSocketFactory(sc.getSocketFactory());+ conn.setHostnameVerifier((h, s) -> true);+ } catch (Exception e) {+ LOG.debugv("Could not disable SSL verification: {0}", e.getMessage());+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksController.javanew file mode 100644index 0000000000..cb20b12971--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksController.java@@ -0,0 +1,66 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;+import jakarta.inject.Inject;+import jakarta.ws.rs.Consumes;+import jakarta.ws.rs.DELETE;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.POST;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.PathParam;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;+import java.util.Map;++/**+ * EKS REST-JSON controller.+ *+ * <p>EKS uses standard HTTP verbs with JSON bodies — not JSON 1.1 (X-Amz-Target) or Query protocol.+ */+@Path("/")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class EksController {++ private final EksService eksService;++ @Inject+ public EksController(EksService eksService) {+ this.eksService = eksService;+ }++ @POST+ @Path("/clusters")+ public Response createCluster(CreateClusterRequest request) {+ Cluster cluster = eksService.createCluster(request);+ return Response.ok(Map.of("cluster", cluster)).build();+ }++ @GET+ @Path("/clusters")+ public Response listClusters(@QueryParam("nextToken") String nextToken,+ @QueryParam("maxResults") Integer maxResults) {+ List<String> clusterNames = eksService.listClusters();+ return Response.ok(Map.of("clusters", clusterNames)).build();+ }++ @GET+ @Path("/clusters/{name}")+ public Response describeCluster(@PathParam("name") String name) {+ Cluster cluster = eksService.describeCluster(name);+ return Response.ok(Map.of("cluster", cluster)).build();+ }++ @DELETE+ @Path("/clusters/{name}")+ public Response deleteCluster(@PathParam("name") String name) {+ Cluster cluster = eksService.deleteCluster(name);+ return Response.ok(Map.of("cluster", cluster)).build();+ }++}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.javanew file mode 100644index 0000000000..7ce31eb1f9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java@@ -0,0 +1,242 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.TagHandler;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;+import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.github.hectorvent.floci.services.eks.model.ClusterStatus;+import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;+import io.github.hectorvent.floci.services.eks.model.KubernetesNetworkConfig;+import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig;+import com.fasterxml.jackson.core.type.TypeReference;+import jakarta.annotation.PostConstruct;+import jakarta.annotation.PreDestroy;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;+import java.util.stream.Collectors;++@ApplicationScoped+public class EksService implements TagHandler {++ private static final Logger LOG = Logger.getLogger(EksService.class);++ private final StorageBackend<String, Cluster> storage;+ private final EmulatorConfig config;+ private final EksClusterManager clusterManager;+ private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();++ @Inject+ public EksService(StorageFactory storageFactory, EmulatorConfig config, EksClusterManager clusterManager) {+ this.storage = storageFactory.create("eks", "eks-clusters.json",+ new TypeReference<Map<String, Cluster>>() {});+ this.config = config;+ this.clusterManager = clusterManager;+ }++ @PostConstruct+ public void init() {+ if (!config.services().eks().mock()) {+ startReadinessPoller();+ }+ }++ @PreDestroy+ public void shutdown() {+ poller.shutdownNow();+ if (!config.services().eks().mock()) {+ for (Cluster cluster : storage.scan(k -> true)) {+ clusterManager.stopCluster(cluster);+ }+ }+ }++ public Cluster createCluster(CreateClusterRequest request) {+ String name = request.getName();+ if (name == null || name.isBlank()) {+ throw new AwsException("InvalidParameterException", "Cluster name is required", 400);+ }+ if (storage.get(name).isPresent()) {+ throw new AwsException("ResourceInUseException",+ "Cluster already exists: " + name, 409);+ }++ String region = config.defaultRegion();+ String accountId = config.defaultAccountId();+ String arn = "arn:aws:eks:" + region + ":" + accountId + ":cluster/" + name;++ Cluster cluster = new Cluster();+ cluster.setName(name);+ cluster.setArn(arn);+ cluster.setCreatedAt(Instant.now());+ cluster.setVersion(request.getVersion() != null ? request.getVersion() : "1.29");+ cluster.setRoleArn(request.getRoleArn());+ cluster.setResourcesVpcConfig(buildVpcConfigResponse(request.getResourcesVpcConfig()));+ cluster.setKubernetesNetworkConfig(buildNetworkConfig(request.getKubernetesNetworkConfig()));+ cluster.setStatus(ClusterStatus.CREATING);+ cluster.setTags(request.getTags() != null ? new HashMap<>(request.getTags()) : new HashMap<>());+ cluster.setPlatformVersion("eks.1");+ cluster.setCertificateAuthority(new CertificateAuthority(""));++ if (config.services().eks().mock()) {+ cluster.setStatus(ClusterStatus.ACTIVE);+ cluster.setEndpoint("https://localhost:" + config.services().eks().apiServerBasePort());+ } else {+ clusterManager.startCluster(cluster);+ }++ storage.put(name, cluster);+ return cluster;+ }++ public Cluster describeCluster(String name) {+ return storage.get(name)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "No cluster found for name: " + name, 404));+ }++ public List<String> listClusters() {+ return storage.scan(k -> true).stream()+ .map(Cluster::getName)+ .collect(Collectors.toList());+ }++ public Cluster deleteCluster(String name) {+ Cluster cluster = storage.get(name)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "No cluster found for name: " + name, 404));++ cluster.setStatus(ClusterStatus.DELETING);+ if (!config.services().eks().mock()) {+ clusterManager.stopCluster(cluster);+ }+ storage.delete(name);+ return cluster;+ }++ @Override+ public String serviceKey() {+ return "eks";+ }++ @Override+ public void tagResource(String region, String resourceArn, Map<String, String> tags) {+ String clusterName = extractClusterName(resourceArn);+ Cluster cluster = storage.get(clusterName)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Resource not found: " + resourceArn, 404));++ if (cluster.getTags() == null) {+ cluster.setTags(new HashMap<>());+ }+ cluster.getTags().putAll(tags);+ storage.put(clusterName, cluster);+ }++ @Override+ public void untagResource(String region, String resourceArn, List<String> tagKeys) {+ String clusterName = extractClusterName(resourceArn);+ Cluster cluster = storage.get(clusterName)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Resource not found: " + resourceArn, 404));++ if (cluster.getTags() != null && tagKeys != null) {+ tagKeys.forEach(cluster.getTags()::remove);+ }+ storage.put(clusterName, cluster);+ }++ @Override+ public Map<String, String> listTags(String region, String resourceArn) {+ String clusterName = extractClusterName(resourceArn);+ Cluster cluster = storage.get(clusterName)+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Resource not found: " + resourceArn, 404));++ return cluster.getTags() != null ? cluster.getTags() : Map.of();+ }++ public void tagResource(String resourceArn, Map<String, String> tags) {+ tagResource(null, resourceArn, tags);+ }++ public void untagResource(String resourceArn, List<String> tagKeys) {+ untagResource(null, resourceArn, tagKeys);+ }++ public Map<String, String> listTagsForResource(String resourceArn) {+ return listTags(null, resourceArn);+ }++ private String extractClusterName(String resourceArn) {+ // arn:aws:eks:us-east-1:000000000000:cluster/my-cluster+ int idx = resourceArn.lastIndexOf('/');+ if (idx < 0 || idx == resourceArn.length() - 1) {+ throw new AwsException("InvalidParameterException",+ "Invalid resource ARN: " + resourceArn, 400);+ }+ return resourceArn.substring(idx + 1);+ }++ private ResourcesVpcConfig buildVpcConfigResponse(ResourcesVpcConfig request) {+ ResourcesVpcConfig response = new ResourcesVpcConfig();+ if (request != null) {+ response.setSubnetIds(request.getSubnetIds() != null ? request.getSubnetIds() : List.of());+ response.setSecurityGroupIds(request.getSecurityGroupIds() != null ? request.getSecurityGroupIds() : List.of());+ response.setVpcId(request.getVpcId() != null ? request.getVpcId() : "");+ response.setEndpointPublicAccess(request.getEndpointPublicAccess() != null ? request.getEndpointPublicAccess() : Boolean.TRUE);+ response.setEndpointPrivateAccess(request.getEndpointPrivateAccess() != null ? request.getEndpointPrivateAccess() : Boolean.FALSE);+ response.setPublicAccessCidrs(request.getPublicAccessCidrs() != null ? request.getPublicAccessCidrs() : List.of("0.0.0.0/0"));+ } else {+ response.setSubnetIds(List.of());+ response.setSecurityGroupIds(List.of());+ response.setVpcId("");+ response.setEndpointPublicAccess(Boolean.TRUE);+ response.setEndpointPrivateAccess(Boolean.FALSE);+ response.setPublicAccessCidrs(List.of("0.0.0.0/0"));+ }+ return response;+ }++ private KubernetesNetworkConfig buildNetworkConfig(KubernetesNetworkConfig request) {+ KubernetesNetworkConfig config = new KubernetesNetworkConfig();+ if (request != null) {+ config.setServiceIpv4Cidr(request.getServiceIpv4Cidr() != null ? request.getServiceIpv4Cidr() : "10.100.0.0/16");+ config.setIpFamily(request.getIpFamily() != null ? request.getIpFamily() : "ipv4");+ } else {+ config.setServiceIpv4Cidr("10.100.0.0/16");+ config.setIpFamily("ipv4");+ }+ return config;+ }++ private void startReadinessPoller() {+ poller.scheduleAtFixedRate(() -> {+ try {+ for (Cluster cluster : storage.scan(k -> true)) {+ if (cluster.getStatus() == ClusterStatus.CREATING) {+ if (clusterManager.isReady(cluster)) {+ LOG.infov("EKS cluster {0} is now ACTIVE", cluster.getName());+ clusterManager.finalizeCluster(cluster);+ cluster.setStatus(ClusterStatus.ACTIVE);+ storage.put(cluster.getName(), cluster);+ }+ }+ }+ } catch (Exception e) {+ LOG.error("Error in EKS readiness poller", e);+ }+ }, 2, 3, TimeUnit.SECONDS);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/CertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/CertificateAuthority.javanew file mode 100644index 0000000000..f5018d6601--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/CertificateAuthority.java@@ -0,0 +1,20 @@+package io.github.hectorvent.floci.services.eks.model;++import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+public class CertificateAuthority {++ @JsonProperty("data")+ private String data;++ public CertificateAuthority() {}++ public CertificateAuthority(String data) {+ this.data = data;+ }++ public String getData() { return data; }+ public void setData(String data) { this.data = data; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.javanew file mode 100644index 0000000000..6d1a7598a8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/Cluster.java@@ -0,0 +1,96 @@+package io.github.hectorvent.floci.services.eks.model;++import com.fasterxml.jackson.annotation.JsonFormat;+import com.fasterxml.jackson.annotation.JsonIgnore;+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.Map;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class Cluster {++ @JsonProperty("name")+ private String name;++ @JsonProperty("arn")+ private String arn;++ @JsonProperty("createdAt")+ @JsonFormat(shape = JsonFormat.Shape.NUMBER)+ private Instant createdAt;++ @JsonProperty("version")+ private String version;++ @JsonProperty("endpoint")+ private String endpoint;++ @JsonProperty("roleArn")+ private String roleArn;++ @JsonProperty("resourcesVpcConfig")+ private ResourcesVpcConfig resourcesVpcConfig;++ @JsonProperty("kubernetesNetworkConfig")+ private KubernetesNetworkConfig kubernetesNetworkConfig;++ @JsonProperty("status")+ private ClusterStatus status;++ @JsonProperty("certificateAuthority")+ private CertificateAuthority certificateAuthority;++ @JsonProperty("platformVersion")+ private String platformVersion;++ @JsonProperty("tags")+ private Map<String, String> tags;++ @JsonIgnore+ private String containerId;++ public Cluster() {}++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public Instant getCreatedAt() { return createdAt; }+ public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }++ public String getVersion() { return version; }+ public void setVersion(String version) { this.version = version; }++ public String getEndpoint() { return endpoint; }+ public void setEndpoint(String endpoint) { this.endpoint = endpoint; }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }++ public ResourcesVpcConfig getResourcesVpcConfig() { return resourcesVpcConfig; }+ public void setResourcesVpcConfig(ResourcesVpcConfig resourcesVpcConfig) { this.resourcesVpcConfig = resourcesVpcConfig; }++ public KubernetesNetworkConfig getKubernetesNetworkConfig() { return kubernetesNetworkConfig; }+ public void setKubernetesNetworkConfig(KubernetesNetworkConfig kubernetesNetworkConfig) { this.kubernetesNetworkConfig = kubernetesNetworkConfig; }++ public ClusterStatus getStatus() { return status; }+ public void setStatus(ClusterStatus status) { this.status = status; }++ public CertificateAuthority getCertificateAuthority() { return certificateAuthority; }+ public void setCertificateAuthority(CertificateAuthority certificateAuthority) { this.certificateAuthority = certificateAuthority; }++ public String getPlatformVersion() { return platformVersion; }+ public void setPlatformVersion(String platformVersion) { this.platformVersion = platformVersion; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }++ public String getContainerId() { return containerId; }+ public void setContainerId(String containerId) { this.containerId = containerId; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterStatus.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterStatus.javanew file mode 100644index 0000000000..027f9c7a9c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/ClusterStatus.java@@ -0,0 +1,5 @@+package io.github.hectorvent.floci.services.eks.model;++public enum ClusterStatus {+ CREATING, ACTIVE, DELETING, FAILED, UPDATING, DEGRADED+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.javanew file mode 100644index 0000000000..b83ec11f55--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/CreateClusterRequest.java@@ -0,0 +1,56 @@+package io.github.hectorvent.floci.services.eks.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.Map;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class CreateClusterRequest {++ @JsonProperty("name")+ private String name;++ @JsonProperty("version")+ private String version;++ @JsonProperty("roleArn")+ private String roleArn;++ @JsonProperty("resourcesVpcConfig")+ private ResourcesVpcConfig resourcesVpcConfig;++ @JsonProperty("kubernetesNetworkConfig")+ private KubernetesNetworkConfig kubernetesNetworkConfig;++ @JsonProperty("tags")+ private Map<String, String> tags;++ @JsonProperty("clientRequestToken")+ private String clientRequestToken;++ public CreateClusterRequest() {}++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getVersion() { return version; }+ public void setVersion(String version) { this.version = version; }++ public String getRoleArn() { return roleArn; }+ public void setRoleArn(String roleArn) { this.roleArn = roleArn; }++ public ResourcesVpcConfig getResourcesVpcConfig() { return resourcesVpcConfig; }+ public void setResourcesVpcConfig(ResourcesVpcConfig resourcesVpcConfig) { this.resourcesVpcConfig = resourcesVpcConfig; }++ public KubernetesNetworkConfig getKubernetesNetworkConfig() { return kubernetesNetworkConfig; }+ public void setKubernetesNetworkConfig(KubernetesNetworkConfig kubernetesNetworkConfig) { this.kubernetesNetworkConfig = kubernetesNetworkConfig; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }++ public String getClientRequestToken() { return clientRequestToken; }+ public void setClientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/KubernetesNetworkConfig.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/KubernetesNetworkConfig.javanew file mode 100644index 0000000000..54eee3e114--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/KubernetesNetworkConfig.java@@ -0,0 +1,24 @@+package io.github.hectorvent.floci.services.eks.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class KubernetesNetworkConfig {++ @JsonProperty("serviceIpv4Cidr")+ private String serviceIpv4Cidr;++ @JsonProperty("ipFamily")+ private String ipFamily;++ public KubernetesNetworkConfig() {}++ public String getServiceIpv4Cidr() { return serviceIpv4Cidr; }+ public void setServiceIpv4Cidr(String serviceIpv4Cidr) { this.serviceIpv4Cidr = serviceIpv4Cidr; }++ public String getIpFamily() { return ipFamily; }+ public void setIpFamily(String ipFamily) { this.ipFamily = ipFamily; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/model/ResourcesVpcConfig.java b/src/main/java/io/github/hectorvent/floci/services/eks/model/ResourcesVpcConfig.javanew file mode 100644index 0000000000..267d796914--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/eks/model/ResourcesVpcConfig.java@@ -0,0 +1,56 @@+package io.github.hectorvent.floci.services.eks.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class ResourcesVpcConfig {++ @JsonProperty("subnetIds")+ private List<String> subnetIds;++ @JsonProperty("securityGroupIds")+ private List<String> securityGroupIds;++ @JsonProperty("clusterSecurityGroupId")+ private String clusterSecurityGroupId;++ @JsonProperty("vpcId")+ private String vpcId;++ @JsonProperty("endpointPublicAccess")+ private Boolean endpointPublicAccess;++ @JsonProperty("endpointPrivateAccess")+ private Boolean endpointPrivateAccess;++ @JsonProperty("publicAccessCidrs")+ private List<String> publicAccessCidrs;++ public ResourcesVpcConfig() {}++ public List<String> getSubnetIds() { return subnetIds; }+ public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }++ public List<String> getSecurityGroupIds() { return securityGroupIds; }+ public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds; }++ public String getClusterSecurityGroupId() { return clusterSecurityGroupId; }+ public void setClusterSecurityGroupId(String clusterSecurityGroupId) { this.clusterSecurityGroupId = clusterSecurityGroupId; }++ public String getVpcId() { return vpcId; }+ public void setVpcId(String vpcId) { this.vpcId = vpcId; }++ public Boolean getEndpointPublicAccess() { return endpointPublicAccess; }+ public void setEndpointPublicAccess(Boolean endpointPublicAccess) { this.endpointPublicAccess = endpointPublicAccess; }++ public Boolean getEndpointPrivateAccess() { return endpointPrivateAccess; }+ public void setEndpointPrivateAccess(Boolean endpointPrivateAccess) { this.endpointPrivateAccess = endpointPrivateAccess; }++ public List<String> getPublicAccessCidrs() { return publicAccessCidrs; }+ public void setPublicAccessCidrs(List<String> publicAccessCidrs) { this.publicAccessCidrs = publicAccessCidrs; }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 095addf0a7..3bb8cfae0d 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -170,3 +170,12 @@ floci:uri-style: hostnamebedrock-runtime:enabled: true+ eks:+ enabled: true+ mock: false+ provider: k3s+ default-image: "rancher/k3s:latest"+ api-server-base-port: 6500+ api-server-max-port: 6599+ data-path: ./data/eks+ keep-running-on-shutdown: falsediff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.javaindex cfcbebe54c..7abce846ef 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java@@ -49,7 +49,8 @@ class HealthControllerIntegrationTest {"appconfigdata": "running","ecr": "running","tagging": "running",- "bedrock-runtime": "running"+ "bedrock-runtime": "running",+ "eks": "running"},"edition": "floci-always-free","version": "dev"diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.javanew file mode 100644index 0000000000..c1a8b64db8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java@@ -0,0 +1,145 @@+package io.github.hectorvent.floci.services.eks;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.eks.model.ClusterStatus;+import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;+import io.github.hectorvent.floci.services.eks.model.Cluster;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++import java.util.List;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.Mockito.when;++class EksServiceTest {++ private EksService eksService;+ private EmulatorConfig config;+ private EksClusterManager clusterManager;++ @BeforeEach+ void setUp() {+ StorageFactory storageFactory = Mockito.mock(StorageFactory.class);+ when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))+ .thenReturn(new InMemoryStorage<>());++ config = Mockito.mock(EmulatorConfig.class);+ var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);+ var eksConfig = Mockito.mock(EmulatorConfig.EksServiceConfig.class);++ when(config.services()).thenReturn(servicesConfig);+ when(servicesConfig.eks()).thenReturn(eksConfig);+ when(eksConfig.mock()).thenReturn(true);+ when(eksConfig.apiServerBasePort()).thenReturn(6500);+ when(config.defaultRegion()).thenReturn("us-east-1");+ when(config.defaultAccountId()).thenReturn("000000000000");++ clusterManager = Mockito.mock(EksClusterManager.class);+ eksService = new EksService(storageFactory, config, clusterManager);+ }++ @Test+ void createCluster() {+ CreateClusterRequest req = new CreateClusterRequest();+ req.setName("test-cluster");+ req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");+ req.setVersion("1.29");++ Cluster cluster = eksService.createCluster(req);++ assertNotNull(cluster);+ assertEquals("test-cluster", cluster.getName());+ assertEquals(ClusterStatus.ACTIVE, cluster.getStatus());+ assertTrue(cluster.getArn().contains("test-cluster"));+ assertEquals("1.29", cluster.getVersion());+ assertNotNull(cluster.getCreatedAt());+ }++ @Test+ void createClusterDuplicateFails() {+ CreateClusterRequest req = new CreateClusterRequest();+ req.setName("dup-cluster");+ req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");++ eksService.createCluster(req);++ assertThrows(AwsException.class, () -> eksService.createCluster(req));+ }++ @Test+ void describeCluster() {+ CreateClusterRequest req = new CreateClusterRequest();+ req.setName("my-cluster");+ req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");+ eksService.createCluster(req);++ Cluster described = eksService.describeCluster("my-cluster");+ assertEquals("my-cluster", described.getName());+ }++ @Test+ void describeClusterNotFound() {+ AwsException ex = assertThrows(AwsException.class,+ () -> eksService.describeCluster("nonexistent"));+ assertEquals(404, ex.getHttpStatus());+ }++ @Test+ void listClusters() {+ CreateClusterRequest req1 = new CreateClusterRequest();+ req1.setName("cluster-a");+ req1.setRoleArn("arn:aws:iam::000000000000:role/eks-role");++ CreateClusterRequest req2 = new CreateClusterRequest();+ req2.setName("cluster-b");+ req2.setRoleArn("arn:aws:iam::000000000000:role/eks-role");++ eksService.createCluster(req1);+ eksService.createCluster(req2);++ List<String> names = eksService.listClusters();+ assertEquals(2, names.size());+ assertTrue(names.contains("cluster-a"));+ assertTrue(names.contains("cluster-b"));+ }++ @Test+ void deleteCluster() {+ CreateClusterRequest req = new CreateClusterRequest();+ req.setName("to-delete");+ req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");+ eksService.createCluster(req);++ Cluster deleted = eksService.deleteCluster("to-delete");+ assertEquals(ClusterStatus.DELETING, deleted.getStatus());+ assertTrue(eksService.listClusters().isEmpty());+ }++ @Test+ void taggingOperations() {+ CreateClusterRequest req = new CreateClusterRequest();+ req.setName("tagged-cluster");+ req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");+ Cluster cluster = eksService.createCluster(req);++ String arn = cluster.getArn();++ // tagResource+ eksService.tagResource(arn, Map.of("env", "test", "team", "platform"));+ Map<String, String> tags = eksService.listTagsForResource(arn);+ assertEquals("test", tags.get("env"));+ assertEquals("platform", tags.get("team"));++ // untagResource+ eksService.untagResource(arn, List.of("env"));+ tags = eksService.listTagsForResource(arn);+ assertFalse(tags.containsKey("env"));+ assertEquals("platform", tags.get("team"));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 739cf4cd93..499c4e9468 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -139,3 +139,6 @@ floci:enabled: truebedrock-runtime:enabled: true+ eks:+ enabled: true+ mock: true