fix(docker): retry core and EKS archive uploads (#5916)

* fix(docker): retry core and EKS archive uploads

* fix(docker): fail fast on local host archive errors

* test(docker): skip backoff in archive retry regressions

Allow package-private caller entry points to select the archive backoff while production retains the shared defaults. Remove the unused user-data tar builder requested in review.

* test(resourceexplorer2): isolate empty-query count assertions

The shared integration fixture can contain exactly 1000 resources, where a capped total does not imply incomplete results. Search a tracked single-resource view and cover 999, 1000 and 1001 matches with deterministic service tests.
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-10-18 11:53:50 -04:00
1 parent f5811c3a07
commit d951fd532c
12 files changed
+803 -106

No files matched your search

@@ -16,19 +16,28 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -83,10 +92,19 @@ class ContainerLifecycleManagerCaBundleTest {
@Test
void tlsOnCopiesTheBundleAndAppendsTheTrustEnvAfterTheSpecEnv() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
Path bundle = writeBundle();
writeBundle();
CreateContainerCmd createCmd = stubCreateContainer();
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
List<InputStream> streams = new ArrayList<>();
when(copyCmd.withTarInputStream(any(InputStream.class))).thenAnswer(invocation -> {
streams.add(invocation.getArgument(0));
return copyCmd;
});
when(copyCmd.exec()).thenAnswer(invocation -> {
assertBundleArchive(streams.getLast());
return null;
});
assertEquals("container-id", manager().create(specWithEnv(List.of("FOO=bar"))));
@@ -99,16 +117,49 @@ class ContainerLifecycleManagerCaBundleTest {
"AWS_CA_BUNDLE=/etc/floci-ca-bundle.pem"), env);
verify(copyCmd).withRemotePath("/etc");
ArgumentCaptor<InputStream> tar = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(tar.capture());
assertEquals(1, streams.size());
verify(copyCmd).exec();
try (TarArchiveInputStream in = new TarArchiveInputStream(tar.getValue())) {
TarArchiveEntry entry = in.getNextEntry();
assertEquals("floci-ca-bundle.pem", entry.getName());
assertEquals(0644, entry.getMode() & 0777, "world-readable, so a non-root USER can read it");
assertEquals(Files.readString(bundle), new String(in.readAllBytes(), StandardCharsets.UTF_8));
assertNull(in.getNextEntry(), "the archive holds only the bundle");
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void transientCopyFailurePreservesTheContainerAndTrustWithAFreshTar(boolean consumeCompletely) throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
writeBundle();
CreateContainerCmd createCmd = stubCreateContainer();
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
List<InputStream> streams = new ArrayList<>();
when(copyCmd.withTarInputStream(any(InputStream.class))).thenAnswer(invocation -> {
streams.add(invocation.getArgument(0));
return copyCmd;
});
AtomicInteger attempts = new AtomicInteger();
when(copyCmd.exec()).thenAnswer(invocation -> {
int attempt = attempts.incrementAndGet();
InputStream stream = streams.getLast();
if (attempt == 1 && !consumeCompletely) {
assertEquals(513, stream.readNBytes(513).length, "consume the tar header and part of the CA bundle");
} else {
assertBundleArchive(stream);
}
if (attempt == 1) {
throw new RuntimeException(new IOException("Connection reset"));
}
return null;
});
lenient().when(dockerClient.removeContainerCmd("container-id"))
.thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
assertEquals("container-id", manager().create(specWithEnv(List.of("FOO=bar"))));
assertEquals(2, attempts.get());
assertEquals(2, streams.size());
assertNotSame(streams.getFirst(), streams.get(1), "a consumed tar stream cannot be replayed");
assertTrue(capturedEnv(createCmd).contains("AWS_CA_BUNDLE=/etc/floci-ca-bundle.pem"));
verify(copyCmd, times(2)).withRemotePath("/etc");
verify(createCmd).exec();
verify(dockerClient, never()).removeContainerCmd(anyString());
}
@Test
@@ -211,8 +262,20 @@ class ContainerLifecycleManagerCaBundleTest {
return Files.writeString(tlsDir.resolve("floci-ca-bundle.pem"), BUNDLE_PEM);
}
private static void assertBundleArchive(InputStream stream) throws IOException {
byte[] archive = stream.readAllBytes();
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry = in.getNextEntry();
assertNotNull(entry, "every attempt must begin with a complete tar header");
assertEquals("floci-ca-bundle.pem", entry.getName());
assertEquals(0644, entry.getMode() & 0777, "world-readable, so a non-root USER can read it");
assertArrayEquals(BUNDLE_PEM.getBytes(StandardCharsets.UTF_8), in.readAllBytes());
assertNull(in.getNextEntry(), "the archive holds only the bundle");
}
}
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config, 0L);
}
private static ContainerSpec specWithEnv(List<String> env) {
@@ -2,34 +2,55 @@ package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.core.util.CompressArchiveUtil;
import com.github.dockerjava.transport.DockerHttpClient;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockMakers;
import org.mockito.MockedStatic;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
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.anyBoolean;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
/**
* The transport-level retry ({@code RetryingDockerHttpClient}) must refuse to replay a one-shot
@@ -47,6 +68,13 @@ class RetryingTarCopierTest {
return new RuntimeException(new IOException("Broken pipe"));
}
private static DockerClient dockerClient(DockerHttpClient transport) {
return DockerClientImpl.getInstance(DefaultDockerClientConfig.createDefaultConfigBuilder()
.withDockerHost("tcp://localhost:2375")
.withApiVersion("1.44")
.build(), transport);
}
private static CopyArchiveToContainerCmd failingOnce(DockerClient docker, AtomicInteger calls) {
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(cmd.exec()).thenAnswer(inv -> {
@@ -180,14 +208,128 @@ class RetryingTarCopierTest {
void copyHostResourceRetriesTransientBrokenPipe(@TempDir Path dir) throws IOException {
Path file = dir.resolve("kubeconfig.yaml");
Files.writeString(file, "apiVersion: v1");
DockerClient docker = mock(DockerClient.class);
AtomicInteger calls = new AtomicInteger();
failingOnce(docker, calls);
DockerHttpClient transport = mock(DockerHttpClient.class);
DockerHttpClient.Response ok = mock(DockerHttpClient.Response.class);
when(ok.getStatusCode()).thenReturn(200);
when(transport.execute(any())).thenThrow(brokenPipe()).thenReturn(ok);
RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher", file.toString(),
MAX_ATTEMPTS, 0L);
try (DockerClient docker = dockerClient(transport)) {
RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher", file.toString(),
MAX_ATTEMPTS, 0L);
}
assertEquals(2, calls.get());
verify(transport, times(2)).execute(any());
}
@ParameterizedTest
@NullSource
@ValueSource(strings = {"Docker transport failure"})
void copyHostResourceStillRetriesTransportClientExceptions(String message, @TempDir Path dir) throws IOException {
Path file = dir.resolve("kubeconfig.yaml");
Files.writeString(file, "apiVersion: v1");
DockerHttpClient transport = mock(DockerHttpClient.class);
DockerHttpClient.Response ok = mock(DockerHttpClient.Response.class);
when(ok.getStatusCode()).thenReturn(200);
when(transport.execute(any()))
.thenThrow(new DockerClientException(message, new IOException("Broken pipe"))).thenReturn(ok);
try (DockerClient docker = dockerClient(transport)) {
RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher", file.toString(),
MAX_ATTEMPTS, 0L);
}
verify(transport, times(2)).execute(any());
}
@Test
void copyHostResourceDoesNotRetryLocalArchiveFailure(@TempDir Path dir) throws IOException {
Path file = dir.resolve("kubeconfig.yaml");
Files.writeString(file, "apiVersion: v1");
DockerHttpClient transport = mock(DockerHttpClient.class);
IOException archiveFailure = new IOException("No space left on device");
AtomicInteger archiveAttempts = new AtomicInteger();
try (DockerClient docker = dockerClient(transport);
MockedStatic<CompressArchiveUtil> archives = mockStatic(CompressArchiveUtil.class,
withSettings().mockMaker(MockMakers.INLINE).defaultAnswer(CALLS_REAL_METHODS))) {
archives.when(() -> CompressArchiveUtil.tar(any(Path.class), any(Path.class),
anyBoolean(), anyBoolean())).thenAnswer(invocation -> {
archiveAttempts.incrementAndGet();
throw archiveFailure;
});
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher",
file.toString(), MAX_ATTEMPTS, 0L));
Throwable cause = thrown;
while (cause.getCause() != null) {
cause = cause.getCause();
}
assertSame(archiveFailure, cause, "the original local archive failure must survive");
verify(transport, never()).execute(any());
assertEquals(1, archiveAttempts.get(), "local archive failures cannot recover by retrying Docker");
}
}
@Test
void copyHostResourceDoesNotRetryLocalArchiveReadFailure(@TempDir Path dir) throws IOException {
Path file = dir.resolve("kubeconfig.yaml");
Files.writeString(file, "apiVersion: v1");
DockerHttpClient transport = mock(DockerHttpClient.class);
AtomicInteger archiveAttempts = new AtomicInteger();
AtomicReference<Path> archivePath = new AtomicReference<>();
try (DockerClient docker = dockerClient(transport);
MockedStatic<CompressArchiveUtil> archives = mockStatic(CompressArchiveUtil.class,
withSettings().mockMaker(MockMakers.INLINE).defaultAnswer(CALLS_REAL_METHODS))) {
archives.when(() -> CompressArchiveUtil.tar(any(Path.class), any(Path.class),
anyBoolean(), anyBoolean())).thenAnswer(invocation -> {
archiveAttempts.incrementAndGet();
Path archive = invocation.getArgument(1);
archivePath.set(archive);
Files.delete(archive);
// A symlink loop fails when docker-java opens the archive, before HTTP.
Files.createSymbolicLink(archive, archive.getFileName());
return null;
});
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher",
file.toString(), MAX_ATTEMPTS, 0L));
Throwable cause = thrown;
while (cause.getCause() != null) {
cause = cause.getCause();
}
FileSystemException readFailure = assertInstanceOf(FileSystemException.class, cause);
assertEquals(archivePath.get().toString(), readFailure.getFile());
verify(transport, never()).execute(any());
assertEquals(1, archiveAttempts.get(), "opening a local archive must not spend the Docker retry budget");
}
}
@Test
void copyHostResourceDoesNotRetryDaemonRejection(@TempDir Path dir) throws IOException {
Path file = dir.resolve("kubeconfig.yaml");
Files.writeString(file, "apiVersion: v1");
DockerHttpClient transport = mock(DockerHttpClient.class);
DockerHttpClient.Response missingContainer = mock(DockerHttpClient.Response.class);
when(missingContainer.getStatusCode()).thenReturn(404);
when(missingContainer.getHeaders()).thenReturn(Map.of());
when(missingContainer.getBody()).thenAnswer(invocation -> new ByteArrayInputStream(
"{\"message\":\"No such container: c-1\"}".getBytes(StandardCharsets.UTF_8)));
when(transport.execute(any())).thenReturn(missingContainer);
try (DockerClient docker = dockerClient(transport)) {
RuntimeException thrown = assertThrows(RuntimeException.class,
() -> RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher",
file.toString(), MAX_ATTEMPTS, 0L));
assertInstanceOf(NotFoundException.class, thrown.getCause());
}
verify(transport, times(1)).execute(any());
}
@Test
@@ -1,21 +1,111 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class UserDataPipelineTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void retriesConsumedScriptUploadBeforeExecutingExactlyOnce(boolean consumeCompletely) {
String script = "#!/bin/sh\nprintf 'bootstrap complete\\n'\n";
DockerClient docker = mock(DockerClient.class);
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(docker.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
List<InputStream> streams = new ArrayList<>();
when(copyCmd.withTarInputStream(any(InputStream.class))).thenAnswer(invocation -> {
streams.add(invocation.getArgument(0));
return copyCmd;
});
AtomicInteger attempts = new AtomicInteger();
when(copyCmd.exec()).thenAnswer(invocation -> {
int attempt = attempts.incrementAndGet();
InputStream stream = streams.getLast();
if (attempt == 1 && !consumeCompletely) {
assertEquals(513, stream.readNBytes(513).length, "consume the tar header and part of the script");
} else {
byte[] archive = stream.readAllBytes();
try (TarArchiveInputStream tar = new TarArchiveInputStream(new ByteArrayInputStream(archive))) {
TarArchiveEntry entry = tar.getNextEntry();
assertNotNull(entry, "every attempt must begin with a complete tar header");
assertEquals("user-data.sh", entry.getName());
assertEquals(0755, entry.getMode() & 0777);
assertArrayEquals(script.getBytes(StandardCharsets.UTF_8), tar.readAllBytes());
assertNull(tar.getNextEntry(), "the archive holds only the user-data script");
}
}
if (attempt == 1) {
throw new RuntimeException(new IOException("Connection reset"));
}
return null;
});
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, "container-id", 0L,
"bootstrap complete\n", "");
List<String> output = new ArrayList<>();
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, "container-id",
"test instance", script, Duration.ofSeconds(1), output::add, null, 0L);
assertTrue(result.isSuccess(), result.getFailureMessage());
assertEquals(2, attempts.get());
assertEquals(2, streams.size());
assertNotSame(streams.getFirst(), streams.get(1), "a consumed tar stream cannot be replayed");
assertEquals(List.of(List.of(UserDataPipeline.USER_DATA_SCRIPT_PATH)), commands);
assertEquals(List.of("bootstrap complete"), output);
verify(copyCmd, times(2)).withRemotePath("/var/lib");
verify(docker).execStartCmd("exec-container-id");
}
@Test
void daemonRejectionDoesNotRetryScriptUploadOrExecuteTheScript() {
DockerClient docker = mock(DockerClient.class);
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(docker.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
when(copyCmd.exec()).thenThrow(new NotFoundException("Could not find the file /var/lib in container"));
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, "container-id",
"test instance", "#!/bin/sh\nexit 0\n", Duration.ofSeconds(1), null, null);
assertFalse(result.isSuccess());
assertTrue(result.getFailureMessage().contains("Could not find the file /var/lib in container"));
verify(copyCmd).exec();
verify(docker, never()).execCreateCmd(anyString());
}
@Test
void extractsPlainShellScript() {
String script = "#!/bin/bash\necho 'hello world'\n";
@@ -0,0 +1,346 @@
package io.github.hectorvent.floci.services.eks;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.core.command.CopyArchiveToContainerCmdImpl;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.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.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 org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.zip.GZIPInputStream;
import static io.github.hectorvent.floci.testing.InlineMocks.inlineMock;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class EksClusterManagerArchiveRetryTest {
private static final String CONTAINER_ID = "container-1";
private static final String CA_PEM = "-----BEGIN CERTIFICATE-----\ntest-only-ca\n-----END CERTIFICATE-----\n";
private static final byte[] PRIVATE_KEY = "test-only generated private key\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] PUBLIC_KEY = "test-only generated public key\n".getBytes(StandardCharsets.UTF_8);
@TempDir
Path tempDir;
private final List<ArchiveUpload> uploads = new ArrayList<>();
private Function<ArchiveUpload, RuntimeException> failure = upload -> null;
private EmulatorConfig.EksServiceConfig eks;
private ContainerLifecycleManager lifecycleManager;
private EksOidcService oidcService;
private EksClusterManager manager;
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
eks = mock(EmulatorConfig.EksServiceConfig.class);
EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
when(config.services()).thenReturn(services);
when(services.eks()).thenReturn(eks);
when(config.tls()).thenReturn(tls);
when(config.port()).thenReturn(4566);
when(config.defaultAccountId()).thenReturn("000000000000");
when(tls.enabled()).thenReturn(true);
when(eks.podIdentityWebhook()).thenReturn(true);
when(eks.dataPath()).thenReturn(tempDir.toString());
when(eks.defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
when(eks.imageTemplate()).thenReturn(Optional.empty());
when(eks.dockerNetwork()).thenReturn(Optional.empty());
when(eks.endpointMode()).thenReturn("host");
DockerClient docker = mock(DockerClient.class);
CopyArchiveToContainerCmd.Exec copyExec = mock(CopyArchiveToContainerCmd.Exec.class);
when(copyExec.exec(any())).thenAnswer(invocation -> {
CopyArchiveToContainerCmd command = invocation.getArgument(0);
ArchiveUpload upload = consumeArchive(command);
uploads.add(upload);
RuntimeException copyFailure = failure.apply(upload);
if (copyFailure != null) {
throw copyFailure;
}
return null;
});
when(docker.copyArchiveToContainerCmd(anyString())).thenAnswer(invocation ->
new CopyArchiveToContainerCmdImpl(copyExec, invocation.getArgument(0)));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.getDockerClient()).thenReturn(docker);
when(lifecycleManager.create(any())).thenReturn(CONTAINER_ID);
when(lifecycleManager.startCreated(any(), any())).thenReturn(new ContainerInfo(CONTAINER_ID, Map.of()));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
FlociCertificateAuthority certificateAuthority = inlineMock(FlociCertificateAuthority.class);
when(certificateAuthority.caPem()).thenReturn(CA_PEM);
oidcService = mock(EksOidcService.class);
manager = new EksClusterManager(containerBuilder, lifecycleManager,
mock(ContainerDetector.class), mock(PortAllocator.class), dockerHostResolver,
mock(EcrRegistryManager.class), config, regionResolver, null, oidcService, certificateAuthority,
null, null, 0L);
}
@Test
void auditPolicyRetriesAfterTheFirstArchiveIsConsumed() throws IOException {
Path policy = tempDir.resolve("audit-policy.yaml");
byte[] content = EksClusterManager.buildAuditPolicy().getBytes(StandardCharsets.UTF_8);
Files.write(policy, content);
failFirstUploadOf("audit-policy.yaml");
manager.copyAuditPolicyIntoContainer(CONTAINER_ID, policy.toString(), "demo");
assertEquals(2, uploads.size(), "a consumed audit policy archive must be rebuilt after a broken pipe");
for (ArchiveUpload upload : uploads) {
assertHostFileUpload(upload, policy, content);
}
}
@Test
void signingPrivateKeyRetriesBeforeUploadingThePublicKey() throws IOException {
EksClusterManager.SigningKeyFiles keys = signingKeyFiles();
failFirstUploadOf("sa-signing-key.pem");
manager.copySigningKeysIntoContainer(CONTAINER_ID, keys, "demo");
assertEquals(3, uploads.size(), "the private key must recover before the public key is uploaded");
assertHostFileUpload(uploads.get(0), keys.signingKeyPath(), PRIVATE_KEY);
assertHostFileUpload(uploads.get(1), keys.signingKeyPath(), PRIVATE_KEY);
assertHostFileUpload(uploads.get(2), keys.publicKeyPath(), PUBLIC_KEY);
assertSigningKeySourcesRemainPrivate(keys);
}
@Test
void signingPublicKeyRetriesWithoutUploadingTheSuccessfulPrivateKeyAgain() throws IOException {
EksClusterManager.SigningKeyFiles keys = signingKeyFiles();
failFirstUploadOf("sa-public-key.pem");
manager.copySigningKeysIntoContainer(CONTAINER_ID, keys, "demo");
assertEquals(3, uploads.size(), "only the failed public key upload must be retried");
assertHostFileUpload(uploads.get(0), keys.signingKeyPath(), PRIVATE_KEY);
assertHostFileUpload(uploads.get(1), keys.publicKeyPath(), PUBLIC_KEY);
assertHostFileUpload(uploads.get(2), keys.publicKeyPath(), PUBLIC_KEY);
assertSigningKeySourcesRemainPrivate(keys);
}
@Test
void dockerJavaDirectHostResourceCopyUses0644ForPrivateSourceFiles() throws IOException {
EksClusterManager.SigningKeyFiles keys = signingKeyFiles();
lifecycleManager.getDockerClient().copyArchiveToContainerCmd(CONTAINER_ID)
.withHostResource(keys.signingKeyPath().toString())
.withRemotePath("/etc")
.exec();
assertEquals(1, uploads.size());
assertHostFileUpload(uploads.getFirst(), keys.signingKeyPath(), PRIVATE_KEY);
assertSigningKeySourcesRemainPrivate(keys);
}
@Test
void containerdLinkRetriesWithEveryDirectoryAndTheSymlinkIntact() {
failFirstUploadOf("etc/containerd/certs.d");
manager.linkContainerdCertsDir(CONTAINER_ID, "demo");
assertEquals(2, uploads.size(), "the entire multi-entry archive must survive the retry");
for (ArchiveUpload upload : uploads) {
assertEquals(CONTAINER_ID, upload.containerId());
assertEquals("/", upload.remotePath());
assertEquals(3, upload.entries().size());
assertDirectory(upload.entries().get(0), "var/lib/rancher/k3s/agent/etc/containerd/certs.d/");
assertDirectory(upload.entries().get(1), "etc/containerd/");
ArchiveEntry link = upload.entries().get(2);
assertEquals("etc/containerd/certs.d", link.name());
assertTrue(link.symbolicLink());
assertFalse(link.directory());
assertEquals(0777, link.mode());
assertEquals("/var/lib/rancher/k3s/agent/etc/containerd/certs.d", link.linkName());
assertArrayEquals(new byte[0], link.content());
}
}
@Test
void podIdentityManifestRetriesWithItsFullContentAndMode() {
failFirstUploadOf("server/manifests/floci-eks-pod-identity.yaml");
byte[] expected = EksClusterManager.buildPodIdentityWebhookConfiguration(
"https://host.docker.internal:4566/_floci/eks/clusters/demo/pod-identity-webhook/scope/000000000000",
CA_PEM).getBytes(StandardCharsets.UTF_8);
manager.registerPodIdentityWebhook(CONTAINER_ID, cluster());
assertEquals(2, uploads.size(), "the pod identity manifest must be rebuilt after the consumed upload fails");
for (ArchiveUpload upload : uploads) {
assertFileUpload(upload, "/var/lib/rancher/k3s", "server/manifests/floci-eks-pod-identity.yaml", expected);
}
}
@Test
void publicKeyDaemonRejectionDoesNotRetryEitherKeyOrPropagate() throws IOException {
EksClusterManager.SigningKeyFiles keys = signingKeyFiles();
failure = upload -> containsEntry(upload, "sa-public-key.pem")
? new NotFoundException("No such container: " + CONTAINER_ID) : null;
assertDoesNotThrow(() -> manager.copySigningKeysIntoContainer(CONTAINER_ID, keys, "demo"));
assertEquals(2, uploads.size());
assertHostFileUpload(uploads.get(0), keys.signingKeyPath(), PRIVATE_KEY);
assertHostFileUpload(uploads.get(1), keys.publicKeyPath(), PUBLIC_KEY);
assertSigningKeySourcesRemainPrivate(keys);
}
@Test
void archiveDaemonRejectionsAreNotRetriedAndLeaveTheClusterRunning() {
failure = upload -> new NotFoundException("No such container: " + CONTAINER_ID);
when(eks.irsaSigningKey()).thenReturn(true);
Cluster cluster = cluster();
cluster.setLogging(new Logging(List.of(new LogSetup(List.of("audit"), true))));
ClusterOidcKey key = new ClusterOidcKey("https://test.invalid/issuer", "fixture", "public", "private");
when(oidcService.ensureKeyForAccount("000000000000", "demo", key.getIssuer())).thenReturn(key);
when(oidcService.exportSigningKeyPem(key)).thenReturn(new String(PRIVATE_KEY, StandardCharsets.UTF_8));
when(oidcService.exportPublicKeyPem(key)).thenReturn(new String(PUBLIC_KEY, StandardCharsets.UTF_8));
assertDoesNotThrow(() -> manager.startCluster(cluster));
assertEquals(List.of("audit-policy.yaml", "etc/containerd/certs.d",
"server/manifests/floci-eks-pod-identity.yaml", "sa-signing-key.pem"),
uploads.stream().map(upload -> upload.entries().getLast().name()).toList(),
"each rejected feature is attempted once and startup continues with reduced functionality");
verify(lifecycleManager).startCreated(any(), any());
assertEquals(CONTAINER_ID, cluster.getContainerId());
}
private EksClusterManager.SigningKeyFiles signingKeyFiles() throws IOException {
Path signingKey = tempDir.resolve("sa-signing-key.pem");
Path publicKey = tempDir.resolve("sa-public-key.pem");
Files.write(signingKey, PRIVATE_KEY);
Files.write(publicKey, PUBLIC_KEY);
if (Files.getFileStore(tempDir).supportsFileAttributeView("posix")) {
Files.setPosixFilePermissions(signingKey, PosixFilePermissions.fromString("rw-------"));
Files.setPosixFilePermissions(publicKey, PosixFilePermissions.fromString("rw-------"));
}
return new EksClusterManager.SigningKeyFiles(signingKey, publicKey);
}
private static void assertSigningKeySourcesRemainPrivate(EksClusterManager.SigningKeyFiles keys) throws IOException {
if (Files.getFileStore(keys.signingKeyPath()).supportsFileAttributeView("posix")) {
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(keys.signingKeyPath()));
assertEquals(PosixFilePermissions.fromString("rw-------"), Files.getPosixFilePermissions(keys.publicKeyPath()));
}
}
private static Cluster cluster() {
Cluster cluster = new Cluster();
cluster.setName("demo");
cluster.setAccountId("000000000000");
cluster.setIdentity(new ClusterIdentity(new OidcIdentity("https://test.invalid/issuer")));
return cluster;
}
private void failFirstUploadOf(String name) {
AtomicInteger attempts = new AtomicInteger();
failure = upload -> containsEntry(upload, name) && attempts.incrementAndGet() == 1
? new RuntimeException(new IOException("Broken pipe")) : null;
}
private static boolean containsEntry(ArchiveUpload upload, String name) {
return upload.entries().stream().anyMatch(entry -> entry.name().equals(name));
}
private static ArchiveUpload consumeArchive(CopyArchiveToContainerCmd command) throws IOException {
InputStream body = command.getTarInputStream();
if (command.getHostResource() != null) {
body = new GZIPInputStream(body);
}
List<ArchiveEntry> entries = new ArrayList<>();
try (TarArchiveInputStream tar = new TarArchiveInputStream(body)) {
TarArchiveEntry entry;
while ((entry = tar.getNextEntry()) != null) {
entries.add(new ArchiveEntry(entry.getName(), entry.getMode() & 07777,
entry.isDirectory(), entry.isSymbolicLink(), entry.getLinkName(), tar.readAllBytes()));
}
body.transferTo(OutputStream.nullOutputStream());
}
return new ArchiveUpload(command.getContainerId(), command.getRemotePath(), command.getHostResource(), entries);
}
private static void assertHostFileUpload(ArchiveUpload upload, Path source, byte[] content) {
assertEquals(source.toString(), upload.hostResource());
// docker-java's File-based tar entries default to 0644 even when the source file is protected with 0600.
assertFileUpload(upload, "/etc", source.getFileName().toString(), content);
}
private static void assertFileUpload(ArchiveUpload upload, String remotePath, String name, byte[] content) {
assertEquals(CONTAINER_ID, upload.containerId());
assertEquals(remotePath, upload.remotePath());
assertEquals(1, upload.entries().size());
ArchiveEntry entry = upload.entries().getFirst();
assertEquals(name, entry.name());
assertEquals(0644, entry.mode());
assertFalse(entry.directory());
assertFalse(entry.symbolicLink());
assertArrayEquals(content, entry.content());
}
private static void assertDirectory(ArchiveEntry entry, String name) {
assertEquals(name, entry.name());
assertTrue(entry.directory());
assertFalse(entry.symbolicLink());
assertEquals(0755, entry.mode());
assertArrayEquals(new byte[0], entry.content());
}
private record ArchiveUpload(String containerId, String remotePath, String hostResource, List<ArchiveEntry> entries) {}
private record ArchiveEntry(String name, int mode, boolean directory, boolean symbolicLink,
String linkName, byte[] content) {}
}
@@ -62,6 +62,8 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@@ -1330,15 +1332,23 @@ class EksClusterManagerTest {
@Test
void copiesArchiveWithTargetDirectoryAndSymlinkAtContainerRoot() throws Exception {
ArgumentCaptor<InputStream> archive = ArgumentCaptor.forClass(InputStream.class);
when(copyCmd.withTarInputStream(archive.capture())).thenReturn(copyCmd);
ByteArrayOutputStream archiveBytes = new ByteArrayOutputStream();
when(copyCmd.exec()).thenAnswer(invocation -> {
archive.getValue().transferTo(archiveBytes);
return null;
});
manager.linkContainerdCertsDir("container-1", "demo");
verify(dockerClient).copyArchiveToContainerCmd("container-1");
verify(copyCmd).withRemotePath("/");
verify(copyCmd).exec();
ArgumentCaptor<InputStream> archive = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(archive.capture());
try (TarArchiveInputStream tar = new TarArchiveInputStream(archive.getValue())) {
verify(copyCmd).withTarInputStream(any());
try (TarArchiveInputStream tar = new TarArchiveInputStream(
new ByteArrayInputStream(archiveBytes.toByteArray()))) {
TarArchiveEntry targetDir = tar.getNextEntry();
assertNotNull(targetDir);
assertEquals("var/lib/rancher/k3s/agent/etc/containerd/certs.d/", targetDir.getName());
@@ -481,27 +481,33 @@ class ResourceExplorer2IntegrationTest {
}
@Test
void searchWithEmptyQueryReturnsAllResources() {
Response response = given()
void searchWithEmptyQueryReturnsEveryResourceInItsView() {
String bucketArn = Arn.global(AwsRegions.partitionFor("us-east-1"), "s3", "", "re2-test-bucket")
.toString();
String viewArn = trackView(given()
.header("Authorization", AUTH)
.contentType("application/json")
.body("""
{"QueryString": ""}
""")
.body(Map.of("ViewName", "empty-query-fixture-view",
"Filters", Map.of("FilterString", "id:" + bucketArn)))
.when()
.post("/CreateView")
.then()
.statusCode(200)
.extract().path("View.ViewArn"));
given()
.header("Authorization", AUTH)
.contentType("application/json")
.body(Map.of("QueryString", "", "ViewArn", viewArn))
.when()
.post("/Search")
.then()
.statusCode(200)
.body("Count.TotalResources", greaterThanOrEqualTo(0))
.body("Resources", notNullValue())
.extract().response();
// Unscoped, so how many resources the shared emulator holds is not knowable here.
// Complete says whether the 1000-result cap bit, which is exactly what TotalResources
// reaching the cap means — assert that relationship rather than a fixed value.
int total = response.path("Count.TotalResources");
boolean complete = response.path("Count.Complete");
assertEquals(total < 1000, complete);
.body("Count.TotalResources", equalTo(1))
.body("Count.Complete", equalTo(true))
.body("Resources.size()", equalTo(1))
.body("Resources[0].Arn", equalTo(bucketArn))
.body("ViewArn", equalTo(viewArn));
}
}
@@ -14,6 +14,8 @@ import io.github.hectorvent.floci.services.resourceexplorer2.model.View;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Instant;
import java.util.ArrayList;
@@ -134,6 +136,17 @@ class ResourceExplorer2ListVsSearchCapTest {
assertEquals(1000, lastTotal);
}
@ParameterizedTest
@CsvSource({"999,999,true", "1000,1000,true", "1001,1000,false"})
void searchCountDistinguishesExactCapFromTruncation(int resourceCount, int expectedTotal, boolean complete) {
ObjectNode result = newServiceWith(resourceCount).search("", 1000, null, null, REGION);
assertEquals(expectedTotal, result.path("Resources").size());
assertEquals(expectedTotal, result.path("Count").path("TotalResources").asInt());
assertEquals(complete, result.path("Count").path("Complete").asBoolean());
assertFalse(result.has("NextToken"));
}
@Test
void oneThrowingProviderIsSkippedAndHealthyProvidersStillSurface() {
// Discovery aggregates every provider. A single provider blowing up (bad stored data, a bug)