mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(eks): implement EKS service with real k3s data plane support (#493)
* feat(eks): implement EKS service with real k3s data plane support * fix: adjusting eks volume issues
This commit is contained in:
1 parent
b013588037
commit
63ed81c59d
27 files changed
+1428
-11
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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))
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -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 limit
|
||||
if (spec.hasMemoryLimit()) {
|
||||
hostConfig.withMemory(spec.memoryBytes());
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.eks.model;
|
||||
|
||||
public enum ClusterStatus {
|
||||
CREATING, ACTIVE, DELETING, FAILED, UPDATING, DEGRADED
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
+24
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
Reference in new issue
Block a user