Light, fluffy, and always free - The AWS Local Emulator alternative
feat(eks): deliver control plane logs to CloudWatch Logs (#4111)
Simone Primarosad5b7b7f676b1
diff --git a/docs/services/eks.md b/docs/services/eks.mdindex 9901f33023..ab5f40aeb4 100644--- a/docs/services/eks.md+++ b/docs/services/eks.md@@ -225,7 +225,9 @@ EKS clusters support configuring KMS envelope encryption for secrets and control- **Response normalization**: AWS EKS always returns the status of all five log types. Enabled types are returned first (`enabled: true`), followed by disabled types (`enabled: false`).- **Default logging**: When omitted or empty at creation time, Floci returns all five log types disabled in a single entry (`enabled: false`).- **Backfill**: Existing persisted clusters created before this feature was introduced are automatically backfilled on startup with default disabled logging.-- **Scope**: Floci stores and returns control plane logging configuration. Shipping log streams to Amazon CloudWatch Logs log groups is out of scope.+- **CloudWatch Logs delivery**: When the `api` log type is enabled on a cluster, Floci creates the CloudWatch Logs log group `/aws/eks/<cluster-name>/cluster` and streams control plane container output to a log stream named `kube-apiserver-<hash>`, where `<hash>` is the first 32 characters of the container ID. When `api` logging is disabled or omitted, no log group is created and container logs are not streamed.+- **Single-stream deviation**: AWS EKS provisions separate log streams for each component (`kube-apiserver-*`, `kube-controller-manager-*`, `kube-scheduler-*`, `authenticator-*`). Because Floci runs clusters on k3s, which embeds the Kubernetes API server, controller manager, and scheduler within a single process, control plane container logs are delivered to the single `kube-apiserver-<hash>` stream when the `api` log type is enabled. Other control plane log types (`audit`, `authenticator`, `controllerManager`, `scheduler`) do not provision separate streams.+- **Audit and authenticator logs**: Audit logging is not configured in k3s. Authenticator webhook authentication events are logged directly by Floci.## Node group inputsdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.javaindex 812d32f0a6..64d1e2f303 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java@@ -79,7 +79,7 @@ public class ContainerLogStreamer {*/public Closeable attachFromNow(String containerId, String logGroup, String logStream,String region, String logPrefix) {- return attachForAccount(null, containerId, logGroup, logStream, region, logPrefix, Instant.now());+ return attachFromNowForAccount(null, containerId, logGroup, logStream, region, logPrefix);}public Closeable attachForAccount(@@ -88,6 +88,15 @@ public class ContainerLogStreamer {return attachForAccount(accountId, containerId, logGroup, logStream, region, logPrefix, null);}+ /**+ * Like {@link #attachForAccount}, but only forwards lines the container emits from now on.+ */+ public Closeable attachFromNowForAccount(+ String accountId, String containerId, String logGroup, String logStream,+ String region, String logPrefix) {+ return attachForAccount(accountId, containerId, logGroup, logStream, region, logPrefix, Instant.now());+ }+/** {@code since} of null follows the container's complete log history. */Closeable attachForAccount(String accountId, String containerId, String logGroup, String logStream,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.javaindex 049a3ffabc..4834cacdac 100644--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java@@ -8,6 +8,7 @@ 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.ContainerLogStreamer;import io.github.hectorvent.floci.core.common.docker.ContainerSpec;import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;@@ -17,6 +18,7 @@ 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.ClusterIdentity;import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;+import io.github.hectorvent.floci.services.eks.model.LogSetup;import io.github.hectorvent.floci.services.eks.model.OidcIdentity;import com.github.dockerjava.api.DockerClient;import com.github.dockerjava.api.async.ResultCallback;@@ -37,6 +39,7 @@ import org.jboss.logging.Logger;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;+import java.io.Closeable;import java.io.File;import java.io.IOException;import java.net.HttpURLConnection;@@ -115,7 +118,9 @@ public class EksClusterManager {private final Ec2MetadataServer metadataServer;private final EksOidcService oidcService;private final FlociCertificateAuthority certificateAuthority;+ private final ContainerLogStreamer logStreamer;private final Map<String, Instance> clusterNodeInstances = new ConcurrentHashMap<>();+ private final Map<String, Closeable> clusterLogHandles = new ConcurrentHashMap<>();public EksClusterManager(ContainerBuilder containerBuilder,ContainerLifecycleManager lifecycleManager,@@ -126,7 +131,7 @@ public class EksClusterManager {EmulatorConfig config,RegionResolver regionResolver) {this(containerBuilder, lifecycleManager, containerDetector, portAllocator,- dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null, null);+ dockerHostResolver, ecrRegistryManager, config, regionResolver, null, null, null, null);}public EksClusterManager(ContainerBuilder containerBuilder,@@ -139,7 +144,7 @@ public class EksClusterManager {RegionResolver regionResolver,Ec2MetadataServer metadataServer) {this(containerBuilder, lifecycleManager, containerDetector, portAllocator,- dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null, null);+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, null, null, null);}public EksClusterManager(ContainerBuilder containerBuilder,@@ -152,11 +157,10 @@ public class EksClusterManager {RegionResolver regionResolver,Ec2MetadataServer metadataServer,EksOidcService oidcService) {- this(containerBuilder, lifecycleManager, containerDetector, portAllocator, dockerHostResolver,- ecrRegistryManager, config, regionResolver, metadataServer, oidcService, null);+ this(containerBuilder, lifecycleManager, containerDetector, portAllocator,+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService, null, null);}- @Injectpublic EksClusterManager(ContainerBuilder containerBuilder,ContainerLifecycleManager lifecycleManager,ContainerDetector containerDetector,@@ -168,6 +172,40 @@ public class EksClusterManager {Ec2MetadataServer metadataServer,EksOidcService oidcService,FlociCertificateAuthority certificateAuthority) {+ this(containerBuilder, lifecycleManager, containerDetector, portAllocator,+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService,+ certificateAuthority, null);+ }++ public EksClusterManager(ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ ContainerDetector containerDetector,+ PortAllocator portAllocator,+ DockerHostResolver dockerHostResolver,+ EcrRegistryManager ecrRegistryManager,+ EmulatorConfig config,+ RegionResolver regionResolver,+ Ec2MetadataServer metadataServer,+ EksOidcService oidcService,+ ContainerLogStreamer logStreamer) {+ this(containerBuilder, lifecycleManager, containerDetector, portAllocator,+ dockerHostResolver, ecrRegistryManager, config, regionResolver, metadataServer, oidcService,+ null, logStreamer);+ }++ @Inject+ public EksClusterManager(ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager,+ ContainerDetector containerDetector,+ PortAllocator portAllocator,+ DockerHostResolver dockerHostResolver,+ EcrRegistryManager ecrRegistryManager,+ EmulatorConfig config,+ RegionResolver regionResolver,+ Ec2MetadataServer metadataServer,+ EksOidcService oidcService,+ FlociCertificateAuthority certificateAuthority,+ ContainerLogStreamer logStreamer) {this.containerBuilder = containerBuilder;this.lifecycleManager = lifecycleManager;this.containerDetector = containerDetector;@@ -179,6 +217,7 @@ public class EksClusterManager {this.metadataServer = metadataServer;this.oidcService = oidcService;this.certificateAuthority = certificateAuthority;+ this.logStreamer = logStreamer;}/**@@ -354,6 +393,7 @@ public class EksClusterManager {applyEndpoints(cluster, containerName, hostPort, info);configureLinkLocalMetadataEndpoint(cluster, containerId);+ attachClusterLogs(cluster);LOG.infov("k3s container {0} started for cluster {1} on port {2} (internal: {3})",containerId, cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());@@ -361,7 +401,7 @@ public class EksClusterManager {/*** Re-latches a persisted cluster onto its k3s container after a Floci restart. A surviving- * container — running, or stopped by a Docker daemon reboot — is adopted (started if needed),+ * container - running, or stopped by a Docker daemon reboot - is adopted (started if needed),* keeping its published API server port and data volume, so the cluster's workloads come back* as they were. When the container is gone, the cluster is recreated via {@link #startCluster};* the named k3s data volume is reused if it survived. Callers should put the cluster back into@@ -409,6 +449,7 @@ public class EksClusterManager {cluster.setHostPort(hostPort);applyEndpoints(cluster, containerName, hostPort, info);configureLinkLocalMetadataEndpoint(cluster, info.containerId());+ attachClusterLogsFromNow(cluster);LOG.infov("Adopted surviving k3s container {0} for EKS cluster {1} on port {2} (internal: {3})",info.containerId(), cluster.getName(), String.valueOf(hostPort), cluster.getInternalEndpoint());@@ -503,18 +544,109 @@ public class EksClusterManager {*/public void stopCluster(Cluster cluster) {unregisterMetadataEndpoint(cluster);+ Closeable logStream = clusterLogHandles.remove(clusterResourceName(cluster));if (cluster.getContainerId() == null) {+ closeQuietly(logStream);return;}if (config.services().eks().keepRunningOnShutdown()) {+ closeQuietly(logStream);LOG.infov("Leaving k3s container for cluster {0} running", cluster.getName());return;}- lifecycleManager.stopAndRemove(cluster.getContainerId(), null);+ lifecycleManager.stopAndRemove(cluster.getContainerId(), logStream);ContainerStorageHelper.removeNamedVolume(config, lifecycleManager, clusterResourceName(cluster));LOG.infov("Stopped k3s container for cluster {0}", cluster.getName());}+ private static void closeQuietly(Closeable closeable) {+ if (closeable != null) {+ try {+ closeable.close();+ } catch (Exception ignored) {+ // Swallowing is safe because closing an already closed or failed log stream during shutdown is best-effort.+ }+ }+ }++ /**+ * Checks whether the cluster has API server control plane logging enabled.+ */+ public static boolean hasLoggingEnabled(Cluster cluster) {+ return hasLoggingEnabled(cluster, "api");+ }++ /**+ * Checks whether the cluster has the specified control plane log type enabled.+ */+ public static boolean hasLoggingEnabled(Cluster cluster, String logType) {+ if (cluster == null || cluster.getLogging() == null || logType == null) {+ return false;+ }+ List<LogSetup> clusterLogging = cluster.getLogging().getClusterLogging();+ if (clusterLogging == null || clusterLogging.isEmpty()) {+ return false;+ }+ for (LogSetup setup : clusterLogging) {+ if (Boolean.TRUE.equals(setup.getEnabled()) && setup.getTypes() != null+ && setup.getTypes().contains(logType)) {+ return true;+ }+ }+ return false;+ }++ /**+ * Attaches CloudWatch Logs delivery for the cluster container if logging is enabled.+ */+ public void attachClusterLogs(Cluster cluster) {+ attachClusterLogs(cluster, false);+ }++ /**+ * Attaches CloudWatch Logs delivery for an adopted cluster container, only forwarding lines+ * emitted from now on.+ */+ public void attachClusterLogsFromNow(Cluster cluster) {+ attachClusterLogs(cluster, true);+ }++ private void attachClusterLogs(Cluster cluster, boolean fromNow) {+ if (logStreamer == null || cluster == null || !hasLoggingEnabled(cluster)) {+ return;+ }+ String containerId = cluster.getContainerId();+ if (containerId == null || containerId.isBlank()) {+ return;+ }+ String resourceName = clusterResourceName(cluster);+ if (clusterLogHandles.containsKey(resourceName)) {+ return;+ }+ try {+ String logGroup = "/aws/eks/" + cluster.getName() + "/cluster";+ String hash = containerId.length() >= 32 ? containerId.substring(0, 32) : containerId;+ String logStream = "kube-apiserver-" + hash;+ String region = clusterRegion(cluster);+ String accountId = resolveClusterAccountId(cluster);+ Closeable handle = fromNow+ ? logStreamer.attachFromNowForAccount(+ accountId, containerId, logGroup, logStream, region, "eks:" + cluster.getName())+ : logStreamer.attachForAccount(+ accountId, containerId, logGroup, logStream, region, "eks:" + cluster.getName());+ if (handle != null) {+ clusterLogHandles.put(resourceName, handle);+ }+ } catch (Exception e) {+ LOG.warnv("Could not attach control plane log stream for EKS cluster {0}: {1}",+ cluster.getName(), e.getMessage());+ }+ }++ Closeable getLogHandle(Cluster cluster) {+ return clusterLogHandles.get(clusterResourceName(cluster));+ }+/*** Docker container/volume name for a cluster: the name already resolved for this record* ({@link Cluster#getDockerName()}, set by startCluster/restoreCluster), or thediff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.javaindex b4b7facb11..299a55b0f3 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java@@ -13,9 +13,12 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;import io.github.hectorvent.floci.core.common.docker.PortAllocator;import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;import io.github.hectorvent.floci.services.eks.model.CertificateAuthority;+import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;import io.github.hectorvent.floci.services.eks.model.Cluster;import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;+import io.github.hectorvent.floci.services.eks.model.LogSetup;+import io.github.hectorvent.floci.services.eks.model.Logging;import io.github.hectorvent.floci.services.eks.model.OidcIdentity;import com.fasterxml.jackson.core.JsonProcessingException;@@ -43,6 +46,7 @@ import org.junit.jupiter.api.io.TempDir;import org.mockito.ArgumentCaptor;import org.mockito.Mockito;+import java.io.Closeable;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;@@ -66,6 +70,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.atLeastOnce;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;@@ -1508,4 +1513,234 @@ class EksClusterManagerTest {assertEquals("container-1", cluster.getContainerId());}}++ @Nested+ class ControlPlaneLogs {++ private EmulatorConfig config;+ private EmulatorConfig.EksServiceConfig eks;+ private ContainerLifecycleManager lifecycleManager;+ private ContainerLogStreamer logStreamer;+ private EksClusterManager manager;+ private Closeable mockHandle;++ @BeforeEach+ void setUp() {+ config = Mockito.mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = Mockito.mock(EmulatorConfig.ServicesConfig.class);+ eks = Mockito.mock(EmulatorConfig.EksServiceConfig.class);+ when(config.services()).thenReturn(services);+ when(services.eks()).thenReturn(eks);+ when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");+ when(eks.imageTemplate()).thenReturn(Optional.empty());+ when(eks.apiServerBasePort()).thenReturn(6440);+ when(eks.apiServerMaxPort()).thenReturn(6499);+ when(eks.dockerNetwork()).thenReturn(Optional.empty());+ when(eks.disableCni()).thenReturn(false);+ when(eks.iamAuthWebhook()).thenReturn(false);+ when(eks.ecrRegistryMirror()).thenReturn(false);+ when(eks.imds()).thenReturn(false);+ when(eks.endpointMode()).thenReturn("host");+ when(eks.keepRunningOnShutdown()).thenReturn(false);+ when(config.defaultAccountId()).thenReturn("000000000000");+ when(config.defaultRegion()).thenReturn("us-east-1");++ EmulatorConfig.StorageConfig storage = Mockito.mock(EmulatorConfig.StorageConfig.class);+ when(config.storage()).thenReturn(storage);+ when(storage.mode()).thenReturn("memory");+ when(storage.pruneVolumesOnDelete()).thenReturn(false);++ lifecycleManager = Mockito.mock(ContainerLifecycleManager.class);+ when(lifecycleManager.create(any())).thenReturn("container-id-123456789012345678901234567890");+ when(lifecycleManager.startCreated(any(), any())).thenReturn(+ new ContainerInfo("container-id-123456789012345678901234567890", Map.of()));++ ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);+ ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);+ when(containerBuilder.newContainer(anyString())).thenReturn(builder);+ when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));++ PortAllocator portAllocator = Mockito.mock(PortAllocator.class);+ when(portAllocator.allocate(6440, 6499)).thenReturn(6443);++ RegionResolver regionResolver = Mockito.mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");++ logStreamer = Mockito.mock(ContainerLogStreamer.class);+ mockHandle = Mockito.mock(Closeable.class);+ when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))+ .thenReturn(mockHandle);+ when(logStreamer.attachFromNowForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))+ .thenReturn(mockHandle);++ manager = new EksClusterManager(containerBuilder, lifecycleManager,+ Mockito.mock(ContainerDetector.class), portAllocator,+ Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),+ config, regionResolver, null, null, logStreamer);+ }++ @Test+ void clusterWithEnabledTypesCreatesLogGroupAndAttachesStream() {+ Cluster cluster = new Cluster();+ cluster.setName("prod-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ manager.startCluster(cluster);++ verify(logStreamer).attachForAccount(+ eq("000000000000"),+ eq("container-id-123456789012345678901234567890"),+ eq("/aws/eks/prod-cluster/cluster"),+ eq("kube-apiserver-container-id-1234567890123456789"),+ eq("us-east-1"),+ eq("eks:prod-cluster")+ );+ assertEquals(mockHandle, manager.getLogHandle(cluster));+ }++ @Test+ void clusterWithNoEnabledTypesDoesNeither() {+ Cluster cluster = new Cluster();+ cluster.setName("no-logs-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), false))));++ manager.startCluster(cluster);++ verifyNoInteractions(logStreamer);+ assertNull(manager.getLogHandle(cluster));+ }++ @Test+ void clusterWithNonApiEnabledTypeDoesNeither() {+ Cluster cluster = new Cluster();+ cluster.setName("scheduler-only-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("scheduler"), true))));++ manager.startCluster(cluster);++ verifyNoInteractions(logStreamer);+ assertNull(manager.getLogHandle(cluster));+ }++ @Test+ void clusterWithNullLoggingDoesNeither() {+ Cluster cluster = new Cluster();+ cluster.setName("null-logs-cluster");+ cluster.setLogging(null);++ manager.startCluster(cluster);++ verifyNoInteractions(logStreamer);+ assertNull(manager.getLogHandle(cluster));+ }++ @Test+ void attachmentFailureLogsWarningAndContinuesWithoutAborting() {+ when(logStreamer.attachForAccount(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))+ .thenThrow(new RuntimeException("Docker attach connection failed"));++ Cluster cluster = new Cluster();+ cluster.setName("prod-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api", "audit"), true))));++ manager.startCluster(cluster);++ assertNull(manager.getLogHandle(cluster));+ assertEquals("container-id-123456789012345678901234567890", cluster.getContainerId());+ }++ @Test+ void logHandleIsReleasedOnClusterStop() {+ Cluster cluster = new Cluster();+ cluster.setName("prod-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ manager.startCluster(cluster);+ assertEquals(mockHandle, manager.getLogHandle(cluster));++ manager.stopCluster(cluster);++ verify(lifecycleManager).stopAndRemove("container-id-123456789012345678901234567890", mockHandle);+ assertNull(manager.getLogHandle(cluster));+ }++ @Test+ void logHandleClosedWhenKeepRunningOnShutdownIsTrue() throws Exception {+ when(eks.keepRunningOnShutdown()).thenReturn(true);++ Cluster cluster = new Cluster();+ cluster.setName("prod-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ manager.startCluster(cluster);+ assertEquals(mockHandle, manager.getLogHandle(cluster));++ manager.stopCluster(cluster);++ verify(mockHandle).close();+ verify(lifecycleManager, never()).stopAndRemove(anyString(), any());+ assertNull(manager.getLogHandle(cluster));+ }++ @Test+ void restoreClusterAttachesLogsForAdoptedContainer() {+ Container container = Mockito.mock(Container.class);+ when(container.getId()).thenReturn("adopted-container-id-12345678901234567890");+ when(lifecycleManager.findByName("floci-eks-prod-cluster")).thenReturn(Optional.of(container));+ when(lifecycleManager.adopt(anyString(), any())).thenReturn(+ new ContainerInfo("adopted-container-id-12345678901234567890",+ Map.of(6443, new ContainerLifecycleManager.EndpointInfo("localhost", 6500)),+ Map.of(6443, 6500)));++ Cluster cluster = new Cluster();+ cluster.setName("prod-cluster");+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ manager.restoreCluster(cluster);++ verify(logStreamer).attachFromNowForAccount(+ eq("000000000000"),+ eq("adopted-container-id-12345678901234567890"),+ eq("/aws/eks/prod-cluster/cluster"),+ eq("kube-apiserver-adopted-container-id-12345678901"),+ eq("us-east-1"),+ eq("eks:prod-cluster")+ );+ assertEquals(mockHandle, manager.getLogHandle(cluster));+ }++ @Test+ void hasLoggingEnabledVerification() {+ assertFalse(EksClusterManager.hasLoggingEnabled(null));++ Cluster cluster = new Cluster();+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));++ cluster.setLogging(new Logging(List.of()));+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));++ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), false))));+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));++ cluster.setLogging(new Logging(List.of(new LogSetup(List.of(), true))));+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));++ cluster.setLogging(new Logging(List.of(new LogSetup(null, true))));+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));++ cluster.setLogging(new Logging(List.of(+ new LogSetup(List.of("api"), false),+ new LogSetup(List.of("scheduler"), true)+ )));+ assertFalse(EksClusterManager.hasLoggingEnabled(cluster));+ assertTrue(EksClusterManager.hasLoggingEnabled(cluster, "scheduler"));++ cluster.setLogging(new Logging(List.of(+ new LogSetup(List.of("api"), true),+ new LogSetup(List.of("scheduler"), false)+ )));+ assertTrue(EksClusterManager.hasLoggingEnabled(cluster));+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksControlPlaneLogsDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksControlPlaneLogsDockerIntegrationTest.javanew file mode 100644index 0000000000..9623b92680--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksControlPlaneLogsDockerIntegrationTest.java@@ -0,0 +1,250 @@+package io.github.hectorvent.floci.services.eks;++import com.github.dockerjava.api.DockerClient;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;+import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;+import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService.LogEventsResult;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;+import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;+import io.github.hectorvent.floci.services.eks.model.Cluster;+import io.github.hectorvent.floci.services.eks.model.LogSetup;+import io.github.hectorvent.floci.services.eks.model.Logging;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++@QuarkusTest+class EksControlPlaneLogsDockerIntegrationTest {++ private static final Logger LOG = Logger.getLogger(EksControlPlaneLogsDockerIntegrationTest.class);+ private static final String TEST_IMAGE = "alpine:3.21";+ private static final String REGION = "us-east-1";+ private static final String ACCOUNT = "000000000000";++ @Inject+ DockerClient dockerClient;++ @Inject+ ContainerBuilder containerBuilder;++ @Inject+ ContainerLifecycleManager lifecycleManager;++ @Inject+ EksClusterManager eksClusterManager;++ @Inject+ CloudWatchLogsService cloudWatchLogsService;++ private String containerId;+ private Cluster cluster;++ @BeforeEach+ void requireDocker() {+ boolean dockerAvailable = isDockerAvailable();+ if (!dockerAvailable) {+ LOG.warn("Docker daemon is not available; skipping EksControlPlaneLogsDockerIntegrationTest");+ }+ Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS control plane logs integration test");+ }++ @AfterEach+ void tearDown() {+ if (cluster != null) {+ try {+ eksClusterManager.stopCluster(cluster);+ } catch (Exception ignored) {+ }+ }+ if (containerId != null) {+ try {+ lifecycleManager.stopAndRemove(containerId, null);+ } catch (Exception ignored) {+ }+ }+ }++ @Test+ void clusterWithLoggingDeliversEventsToCloudWatchLogs() throws Exception {+ String clusterName = "cplogs-it-" + UUID.randomUUID().toString().substring(0, 8);+ cluster = new Cluster();+ cluster.setName(clusterName);+ cluster.setAccountId(ACCOUNT);+ cluster.setArn("arn:aws:eks:" + REGION + ":" + ACCOUNT + ":cluster/" + clusterName);+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ String expectedMessage = "eks-cp-log-message-" + UUID.randomUUID();+ ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)+ .withName("floci-eks-cp-test-" + clusterName)+ .withCmd(List.of("sh", "-c", "echo '" + expectedMessage + "'; sleep 30"))+ .build();++ containerId = lifecycleManager.createAndStart(spec).containerId();+ assertNotNull(containerId, "Container ID must not be null");+ cluster.setContainerId(containerId);++ eksClusterManager.attachClusterLogs(cluster);+ assertNotNull(eksClusterManager.getLogHandle(cluster), "Log handle should be active after attach");++ String logGroup = "/aws/eks/" + clusterName + "/cluster";+ String streamPrefix = "kube-apiserver-";++ List<LogStream> streams = List.of();+ long deadline = System.currentTimeMillis() + 10_000;+ while (System.currentTimeMillis() < deadline) {+ try {+ streams = cloudWatchLogsService.describeLogStreams(logGroup, streamPrefix, REGION);+ if (!streams.isEmpty()) {+ break;+ }+ } catch (Exception ignored) {+ }+ Thread.sleep(100);+ }+ assertFalse(streams.isEmpty(), "Expected log stream starting with " + streamPrefix + " in group " + logGroup);++ String streamName = streams.get(0).getLogStreamName();+ assertTrue(streamName.startsWith(streamPrefix), "Stream name should start with prefix: " + streamName);++ List<LogEvent> events = List.of();+ while (System.currentTimeMillis() < deadline) {+ try {+ LogEventsResult result = cloudWatchLogsService.getLogEvents(+ logGroup, streamName, null, null, 10, true, null, REGION);+ if (!result.events().isEmpty()) {+ events = result.events();+ break;+ }+ } catch (Exception ignored) {+ }+ Thread.sleep(100);+ }+ assertFalse(events.isEmpty(), "Expected log events in stream " + streamName);+ assertTrue(events.stream().anyMatch(e -> e.getMessage().contains(expectedMessage)),+ "Expected event containing: " + expectedMessage);++ eksClusterManager.stopCluster(cluster);+ assertNull(eksClusterManager.getLogHandle(cluster), "Log handle should be removed after stop");+ }++ @Test+ void restoredClusterDoesNotReplayOldLogs() throws Exception {+ String clusterName = "cplogs-restore-" + UUID.randomUUID().toString().substring(0, 8);+ cluster = new Cluster();+ cluster.setName(clusterName);+ cluster.setAccountId(ACCOUNT);+ cluster.setArn("arn:aws:eks:" + REGION + ":" + ACCOUNT + ":cluster/" + clusterName);+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), true))));++ String oldMessage = "eks-old-msg-" + UUID.randomUUID();+ String newMessage = "eks-new-msg-" + UUID.randomUUID();+ ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)+ .withName("floci-eks-cp-test-" + clusterName)+ .withCmd(List.of("sh", "-c", "echo '" + oldMessage + "'; sleep 2; echo '" + newMessage + "'; sleep 30"))+ .build();++ containerId = lifecycleManager.createAndStart(spec).containerId();+ assertNotNull(containerId, "Container ID must not be null");+ cluster.setContainerId(containerId);++ // Allow old message to be emitted before attaching+ Thread.sleep(1500);++ eksClusterManager.attachClusterLogsFromNow(cluster);+ assertNotNull(eksClusterManager.getLogHandle(cluster), "Log handle should be active after attachFromNow");++ String logGroup = "/aws/eks/" + clusterName + "/cluster";+ String streamPrefix = "kube-apiserver-";++ List<LogStream> streams = List.of();+ long deadline = System.currentTimeMillis() + 10_000;+ while (System.currentTimeMillis() < deadline) {+ try {+ streams = cloudWatchLogsService.describeLogStreams(logGroup, streamPrefix, REGION);+ if (!streams.isEmpty()) {+ break;+ }+ } catch (Exception ignored) {+ // Log group or stream not yet created+ }+ Thread.sleep(100);+ }+ assertFalse(streams.isEmpty(), "Expected log stream starting with " + streamPrefix + " in group " + logGroup);++ String streamName = streams.get(0).getLogStreamName();++ List<LogEvent> events = List.of();+ while (System.currentTimeMillis() < deadline) {+ try {+ LogEventsResult result = cloudWatchLogsService.getLogEvents(+ logGroup, streamName, null, null, 10, true, null, REGION);+ if (!result.events().isEmpty()) {+ events = result.events();+ if (events.stream().anyMatch(e -> e.getMessage().contains(newMessage))) {+ break;+ }+ }+ } catch (Exception ignored) {+ // Stream not yet populated+ }+ Thread.sleep(100);+ }+ assertFalse(events.isEmpty(), "Expected log events in stream " + streamName);+ assertTrue(events.stream().anyMatch(e -> e.getMessage().contains(newMessage)),+ "Expected event containing new message: " + newMessage);+ assertFalse(events.stream().anyMatch(e -> e.getMessage().contains(oldMessage)),+ "Did not expect old message to be replayed: " + oldMessage);++ eksClusterManager.stopCluster(cluster);+ assertNull(eksClusterManager.getLogHandle(cluster), "Log handle should be removed after stop");+ }++ @Test+ void clusterWithoutLoggingDoesNotCreateLogGroup() {+ String clusterName = "cplogs-off-" + UUID.randomUUID().toString().substring(0, 8);+ cluster = new Cluster();+ cluster.setName(clusterName);+ cluster.setAccountId(ACCOUNT);+ cluster.setArn("arn:aws:eks:" + REGION + ":" + ACCOUNT + ":cluster/" + clusterName);+ cluster.setLogging(new Logging(List.of(new LogSetup(List.of("api"), false))));++ ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)+ .withName("floci-eks-cp-test-" + clusterName)+ .withCmd(List.of("sh", "-c", "echo 'should-not-stream'; sleep 10"))+ .build();++ containerId = lifecycleManager.createAndStart(spec).containerId();+ cluster.setContainerId(containerId);++ eksClusterManager.attachClusterLogs(cluster);+ assertNull(eksClusterManager.getLogHandle(cluster), "No log handle expected when logging disabled");++ String logGroup = "/aws/eks/" + clusterName + "/cluster";+ List<LogGroup> groupsResult = cloudWatchLogsService.describeLogGroups(logGroup, REGION);+ assertTrue(groupsResult.isEmpty(), "Log group should not exist when logging is disabled");+ }++ private boolean isDockerAvailable() {+ try {+ dockerClient.pingCmd().exec();+ return true;+ } catch (Exception e) {+ return false;+ }+ }+}