diff --git a/docs/services/eks.md b/docs/services/eks.md index a99da8b855..40c0d82695 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -474,7 +474,13 @@ With a persistent [storage mode](../configuration/storage.md) (the default), clu - A surviving container (for example after a Docker Desktop / daemon reboot) is adopted and started in place, keeping its published API server port and data volume: deployments come back as they were. -- A missing container is recreated. Its named k3s data volume (`floci-aws-eks-`; for a +- A missing container, or a survivor that cannot be adopted, is recreated on the API server port + the cluster's endpoint names, so existing kubeconfigs stay valid. Only when that port is in use + (by another process, another container or another cluster), or it is outside the configured + range, does the cluster move to the first free port, which changes its endpoint; Floci logs a + warning when a port in use moves it. A `network` mode endpoint names the container itself, so it + stays the same whatever host port the container gets. + Its named k3s data volume (`floci-aws-eks-`; for a [non-default account](../configuration/multi-account.md), `floci-aws-eks-.`) is reused if it survived; volumes follow the global prune policy (`FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE`, default `false`), so they are retained when the diff --git a/src/main/java/io/floci/aws/core/common/docker/PortAllocator.java b/src/main/java/io/floci/aws/core/common/docker/PortAllocator.java index 03a84c7b74..c42bd30fcf 100644 --- a/src/main/java/io/floci/aws/core/common/docker/PortAllocator.java +++ b/src/main/java/io/floci/aws/core/common/docker/PortAllocator.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; +import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.IntFunction; @@ -65,7 +66,7 @@ public class PortAllocator { // allocator blocks on. Set published = publishedHostPorts(); for (int port = basePort; port <= maxPort; port++) { - if (!reserved.contains(port) && !published.contains(port) && isPortFree(port)) { + if (available(port, published)) { reserved.add(port); LOG.debugv("Allocated port {0} from range {1}-{2}", String.valueOf(port), String.valueOf(basePort), String.valueOf(maxPort)); return port; @@ -74,6 +75,24 @@ public class PortAllocator { throw new RuntimeException("No free port available in range " + basePort + "-" + maxPort); } + /** + * Allocates {@code port} itself when {@link #allocate} would hand it out, or answers empty when it is reserved, + * published by a container or bound. A failure reading Docker's published ports propagates rather than reading + * as a taken port. + */ + public synchronized OptionalInt allocateIfFree(int port) { + if (!available(port, publishedHostPorts())) { + return OptionalInt.empty(); + } + reserved.add(port); + LOG.debugv("Allocated port {0}", String.valueOf(port)); + return OptionalInt.of(port); + } + + private boolean available(int port, Set published) { + return !reserved.contains(port) && !published.contains(port) && isPortFree(port); + } + /** * Marks a port as reserved without probing whether it is free. Used on restart to * re-reserve host ports already held by surviving containers (e.g. persisted EC2 diff --git a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java index 113dd32672..3998f18b99 100644 --- a/src/main/java/io/floci/aws/services/eks/EksClusterManager.java +++ b/src/main/java/io/floci/aws/services/eks/EksClusterManager.java @@ -93,6 +93,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -673,9 +674,7 @@ public class EksClusterManager cluster.getName(), image); // Allocate host port for the k3s API server - int hostPort = retainedPort != null ? retainedPort : portAllocator.allocate( - config.services().eks().apiServerBasePort(), - config.services().eks().apiServerMaxPort()); + int hostPort = retainedPort != null ? retainedPort : allocateApiServerPort(cluster); cluster.setHostPort(hostPort); try { @@ -690,6 +689,41 @@ public class EksClusterManager } } + /** + * Allocates the k3s API server's host port. A cluster recreated on restore asks first for the + * port its persisted endpoint names, since an EKS endpoint never changes and every kubeconfig + * written for the cluster names that port. Only when that port is taken does the cluster get the + * first free one, which changes its endpoint, and a warning says so. A port outside the + * configured range is not asked for, and neither is the port of a network-mode endpoint: that + * endpoint names the container's own API server port, whatever host port the container gets. + */ + private int allocateApiServerPort(Cluster cluster) { + int basePort = config.services().eks().apiServerBasePort(); + int maxPort = config.services().eks().apiServerMaxPort(); + int previousPort = networkEndpointMode() ? -1 : endpointPort(cluster.getEndpoint()); + if (previousPort >= basePort && previousPort <= maxPort) { + OptionalInt kept = portAllocator.allocateIfFree(previousPort); + if (kept.isPresent()) { + return kept.getAsInt(); + } + LOG.warnv("API server port {0} of EKS cluster {1} is taken; moving the cluster to another port " + + "changes its endpoint", String.valueOf(previousPort), cluster.getName()); + } + return portAllocator.allocate(basePort, maxPort); + } + + /** The port an endpoint URL names, or -1 when it names none. */ + private static int endpointPort(String endpoint) { + if (endpoint == null) { + return -1; + } + try { + return URI.create(endpoint).getPort(); + } catch (IllegalArgumentException e) { + return -1; + } + } + private void launchCluster(Cluster cluster, String image, String containerName, int hostPort) { // Remove any stale container ContainerStorageHelper.removeStaleContainer(config, lifecycleManager, containerName); @@ -986,7 +1020,8 @@ public class EksClusterManager * keeping its published API server port and data volume, so the cluster's workloads come back * as they were. A survivor whose node capacity changed, or that is not on the Docker network * Floci now uses, is replaced on the same volume. When the container is gone, the cluster is - * recreated via {@link #startCluster}; the named k3s data volume is reused if it survived. + * recreated via {@link #startCluster}, on the API server port its endpoint names if that port is + * still free; the named k3s data volume is reused if it survived. * Callers should put the cluster back into CREATING so the readiness poller re-verifies the API * server and re-extracts the certificate authority before marking it ACTIVE again. */ @@ -1024,6 +1059,9 @@ public class EksClusterManager LOG.infov("Adopting pre-upgrade EKS cluster {0} with local-storage enabled", cluster.getName()); } if (!adoptSurvivingCluster(cluster, existing.get().getId(), certificateHost(existingLabels))) { + // The survivor is replaced, and it may still publish the port the endpoint names: it goes before a + // port is chosen, so the new container can take that port and the endpoint stays. + lifecycleManager.removeIfExistsStrict(containerName); startCluster(cluster); return; } @@ -1856,13 +1894,18 @@ public class EksClusterManager * {@link EksStartupValidator} has already refused an invalid value at boot. */ private String endpointHost() { - if (containerDetector.isRunningInContainer() - && ENDPOINT_MODE_NETWORK.equalsIgnoreCase(config.services().eks().endpointMode())) { + if (networkEndpointMode()) { return "localhost"; } return endpointHostFrom(config.services().eks().endpointHost()); } + /** Whether endpoints name the k3s container rather than a host port: network mode, with Floci in a container. */ + private boolean networkEndpointMode() { + return containerDetector.isRunningInContainer() + && ENDPOINT_MODE_NETWORK.equalsIgnoreCase(config.services().eks().endpointMode()); + } + /** * The configured endpoint host as a bare hostname or IP address, the form a {@code --tls-san} takes. * A bracketed IPv6 literal is unbracketed; a scheme, port or path is refused, since the endpoint diff --git a/src/test/java/io/floci/aws/core/common/docker/PortAllocatorTest.java b/src/test/java/io/floci/aws/core/common/docker/PortAllocatorTest.java index b6a1e5a961..245f1c669c 100644 --- a/src/test/java/io/floci/aws/core/common/docker/PortAllocatorTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/PortAllocatorTest.java @@ -4,8 +4,10 @@ import io.floci.aws.testing.StartGate; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; +import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.ConcurrentHashMap; @@ -75,6 +77,23 @@ class PortAllocatorTest { } } + @Test + void allocateIfFreeHandsOutThatPortOnlyWhileNothingHoldsIt() throws Exception { + PortAllocator allocator = new PortAllocator(); + int port = allocator.allocate(19900, 19999); + allocator.release(port); + + assertEquals(OptionalInt.of(port), allocator.allocateIfFree(port)); + // Reserved now, as allocate leaves a port it hands out. + assertEquals(OptionalInt.empty(), allocator.allocateIfFree(port)); + allocator.release(port); + try (ServerSocket bound = new ServerSocket(port)) { + assertEquals(OptionalInt.empty(), allocator.allocateIfFree(port)); + } + assertEquals(OptionalInt.of(port), allocator.allocateIfFree(port)); + allocator.release(port); + } + @Test void throwsWhenRangeExhausted() { PortAllocator allocator = new PortAllocator(); diff --git a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java index 750230803b..1e6cd94d8a 100644 --- a/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/floci/aws/services/eks/EksClusterManagerTest.java @@ -83,6 +83,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; +import java.text.MessageFormat; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -92,6 +93,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -115,6 +117,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -597,6 +600,7 @@ class EksClusterManagerTest { private PortAllocator portAllocator; private DockerClient dockerClient; private ContainerBuilder containerBuilder; + private ContainerBuilder.Builder builder; private ContainerDetector containerDetector; private EksClusterManager manager; @@ -620,7 +624,7 @@ class EksClusterManagerTest { lifecycleManager = Mockito.mock(ContainerLifecycleManager.class); containerBuilder = Mockito.mock(ContainerBuilder.class); - ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); + builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF); when(containerBuilder.newContainer(anyString())).thenReturn(builder); when(builder.build()).thenReturn(new ContainerSpec("test-image")); portAllocator = Mockito.mock(PortAllocator.class); @@ -1269,6 +1273,126 @@ class EksClusterManagerTest { verify(lifecycleManager).removeIfExists("floci-eks-demo"); } + @Test + void recreatingAMissingContainerKeepsTheApiServerPortTheEndpointNames() { + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.empty()); + stubFreshStart("cid-new", 6440); + when(portAllocator.allocateIfFree(6453)).thenReturn(OptionalInt.of(6453)); + Cluster cluster = cluster(); + cluster.setEndpoint("https://localhost:6453"); + + manager.restoreCluster(cluster); + + assertEquals("cid-new", cluster.getContainerId()); + assertEquals(6453, cluster.getHostPort()); + assertEquals("https://localhost:6453", cluster.getEndpoint()); + verify(builder).withPortBinding(6443, 6453); + verify(portAllocator, never()).allocate(6440, 6499); + } + + @Test + void recreatingASurvivorThatPublishesNoPortKeepsTheApiServerPortTheEndpointNames() { + when(lifecycleManager.findByName("floci-eks-demo")) + .thenReturn(Optional.of(survivingContainer("cid-1"))); + when(lifecycleManager.adopt("cid-1", List.of(6443), Optional.empty())) + .thenReturn(new ContainerInfo("cid-1", Map.of())); + stubFreshStart("cid-new", 6440); + when(portAllocator.allocateIfFree(6457)).thenReturn(OptionalInt.of(6457)); + Cluster cluster = cluster(); + cluster.setEndpoint("https://localhost:6457"); + + manager.restoreCluster(cluster); + + assertEquals("cid-new", cluster.getContainerId()); + assertEquals("https://localhost:6457", cluster.getEndpoint()); + verify(builder).withPortBinding(6443, 6457); + verify(portAllocator, never()).allocate(6440, 6499); + } + + /** + * A survivor that can't be adopted may still publish the port the endpoint names. It is removed before the + * port is asked for, so the new container takes that port and the endpoint stays. + */ + @Test + void recreatingASurvivorThatCannotBeAdoptedRemovesItBeforeTakingTheEndpointsPort() { + when(lifecycleManager.findByName("floci-eks-demo")) + .thenReturn(Optional.of(survivingContainer("cid-1"))); + when(lifecycleManager.adopt("cid-1", List.of(6443), Optional.empty())) + .thenThrow(new RuntimeException("the survivor did not start")); + stubFreshStart("cid-new", 6440); + when(portAllocator.allocateIfFree(6457)).thenReturn(OptionalInt.of(6457)); + Cluster cluster = cluster(); + cluster.setEndpoint("https://localhost:6457"); + + manager.restoreCluster(cluster); + + InOrder order = inOrder(lifecycleManager, portAllocator); + order.verify(lifecycleManager).removeIfExistsStrict("floci-eks-demo"); + order.verify(portAllocator).allocateIfFree(6457); + assertEquals("cid-new", cluster.getContainerId()); + assertEquals("https://localhost:6457", cluster.getEndpoint()); + verify(portAllocator, never()).allocate(6440, 6499); + } + + @Test + void recreatingAMissingContainerMovesToAFreePortWhenTheEndpointPortIsTaken() { + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.empty()); + stubFreshStart("cid-new", 6440); + when(portAllocator.allocateIfFree(6457)).thenReturn(OptionalInt.empty()); + Cluster cluster = cluster(); + cluster.setEndpoint("https://localhost:6457"); + + List logs = LogCapture.capture(EksClusterManager.class, () -> manager.restoreCluster(cluster)); + + assertEquals(6440, cluster.getHostPort()); + assertEquals("https://localhost:6440", cluster.getEndpoint()); + verify(builder).withPortBinding(6443, 6440); + verify(portAllocator).allocate(6440, 6499); + String warning = "API server port 6457 of EKS cluster demo is taken; moving the cluster to another port " + + "changes its endpoint"; + // Compared by severity, not identity: JBoss LogManager has its own Level constants. + List warnings = logs.stream() + .filter(record -> record.getLevel().intValue() >= Level.WARNING.intValue()) + .map(record -> MessageFormat.format(record.getMessage(), record.getParameters())) + .toList(); + assertTrue(warnings.contains(warning), String.valueOf(warnings)); + } + + /** + * A network-mode endpoint names the container's own API server port, 6443, which says nothing + * about the host port the container had, so it is not asked for even inside the range. + */ + @Test + void recreatingAMissingContainerInNetworkModeDoesNotAskForTheEndpointsContainerPort() { + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(config.services().eks().endpointMode()).thenReturn("network"); + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.empty()); + stubFreshStart("cid-new", 6440); + Cluster cluster = cluster(); + cluster.setEndpoint("https://floci-eks-demo:6443"); + + manager.restoreCluster(cluster); + + assertEquals(6440, cluster.getHostPort()); + assertEquals("https://" + cluster.getDockerName() + ":6443", cluster.getEndpoint()); + verify(builder).withPortBinding(6443, 6440); + verify(portAllocator, never()).allocateIfFree(6443); + } + + @Test + void recreatingAMissingContainerIgnoresAnEndpointPortOutsideTheConfiguredRange() { + when(lifecycleManager.findByName("floci-eks-demo")).thenReturn(Optional.empty()); + stubFreshStart("cid-new", 6440); + Cluster cluster = cluster(); + cluster.setEndpoint("https://localhost:6512"); + + manager.restoreCluster(cluster); + + assertEquals(6440, cluster.getHostPort()); + assertEquals("https://localhost:6440", cluster.getEndpoint()); + verify(portAllocator, never()).allocateIfFree(6512); + } + @Test void stopClusterRetainsTheDataVolumeInPersistentStorageMode() { when(storage.mode()).thenReturn("hybrid");