fix(ec2,ecr,eks,elasticache,msk,opensearch): degrade gracefully with no Docker daemon (#2975)

* fix(ec2,ecr,eks,elasticache,msk,opensearch): degrade gracefully with no Docker daemon

Extends the daemonless degradation pattern #2386 established for MemoryDB,
Neptune and DocDB to the remaining container-backed services. Create paths
probe the daemon on failure, keep serving metadata, and log the outage once;
a failure with a reachable daemon still propagates.

* fix(opensearch,msk): keep the readiness pollers when the daemon is reachable

Create set the terminal state before the container started, which orphaned the readiness pollers. The terminal state is now set only in mock mode or when the daemon is unreachable, matching EKS. ElastiCache stops a partially created container before degrading to metadata.

* fix(elasticache): fail the create when a container was already started

Degrading to metadata now happens only when no container was created. A failure after creation runs the cleanup and rethrows. The service rollback then runs and no available group is persisted without a container.

* test(elasticache): stub tryStart in the parameter group reservation tests

The three tests from #3023 stubbed start, which createReplicationGroup no longer calls on this branch.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-05 21:01:38 -04:00
1 parent 43e2a48263
commit 1aa981fef2
24 files changed
+900 -47

No files matched your search

@@ -65,6 +65,10 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import com.github.dockerjava.api.command.PingCmd;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
class Ec2ContainerManagerTest {
@@ -941,6 +945,7 @@ class Ec2ContainerManagerTest {
when(ec2.imdsPort()).thenReturn(9169);
DockerClient dockerClient = mock(DockerClient.class);
stubDockerPing(dockerClient, true);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
Ec2PortForwardManager portForwardManager = mock(Ec2PortForwardManager.class);
@@ -1003,6 +1008,65 @@ class Ec2ContainerManagerTest {
assertTrue(condition.getAsBoolean(), "condition was not met before timeout");
}
@Test
void launchRunsInstanceAsMetadataOnlyWhenNoDockerDaemonIsReachable() throws Exception {
LaunchHarness harness = launchHarness();
stubDockerPing(harness.dockerClient(), false);
Instance instance = instance("i-nodocker");
harness.manager().launch(instance, "ubuntu:24.04", null, "us-west-2");
assertEquals("running", instance.getState().getName());
assertNull(instance.getDockerContainerId());
verify(harness.lifecycleManager(), never()).create(any(ContainerSpec.class));
verify(harness.metadataServer(), never()).registerContainer(anyString(), anyString(), any());
}
@Test
void launchDegradesToRunningWhenDockerDisappearsMidLaunch() throws Exception {
LaunchHarness harness = launchHarness();
PingCmd ping = mock(PingCmd.class);
when(harness.dockerClient().pingCmd()).thenReturn(ping);
doNothing().doThrow(new RuntimeException("No such file or directory")).when(ping).exec();
when(harness.lifecycleManager().create(any(ContainerSpec.class)))
.thenThrow(new RuntimeException("No such file or directory"));
Instance instance = instance("i-dockergone");
harness.manager().launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
}
@Test
void metadataOnlyInstanceStopsStartsAndTerminatesWithoutAContainer() throws Exception {
LaunchHarness harness = launchHarness();
stubDockerPing(harness.dockerClient(), false);
Instance instance = instance("i-lifecycle");
harness.manager().launch(instance, "ubuntu:24.04", null, "us-west-2");
assertEquals("running", instance.getState().getName());
harness.manager().stop(instance);
assertEquals("stopped", instance.getState().getName());
harness.manager().start(instance);
assertEquals("running", instance.getState().getName());
harness.manager().terminate(instance);
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
}
/** Stubs the daemon reachability probe every launch makes before touching Docker. */
private static void stubDockerPing(DockerClient dockerClient, boolean reachable) {
PingCmd ping = mock(PingCmd.class);
when(dockerClient.pingCmd()).thenReturn(ping);
if (!reachable) {
doThrow(new RuntimeException("No such file or directory")).when(ping).exec();
}
}
private record LaunchHarness(Ec2ContainerManager manager,
ContainerLifecycleManager lifecycleManager,
DockerClient dockerClient,
@@ -55,7 +55,9 @@ class EcrServiceTest {
when(registryManager.getProxyEndpoint()).thenReturn("http://localhost:5000");
when(registryManager.internalRepoName(anyString(), anyString(), anyString()))
.thenAnswer(inv -> inv.getArgument(0) + "/" + inv.getArgument(1) + "/" + inv.getArgument(2));
// ensureStarted() is a no-op on the mock — no Docker calls in any test below.
// The mock never talks to Docker; report the backing registry as available so the
// data-plane operations run. Registry-unavailable behaviour has its own tests below.
when(registryManager.tryEnsureStarted()).thenReturn(true);
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
@@ -80,7 +82,6 @@ class EcrServiceTest {
assertTrue(repo.getRepositoryArn().startsWith("arn:aws:ecr:us-east-1:000000000000:repository/"));
assertTrue(repo.getRepositoryUri().contains("localhost:"));
assertEquals("MUTABLE", repo.getImageTagMutability());
Mockito.verify(registryManager).ensureStarted();
}
@Test
@@ -116,6 +117,66 @@ class EcrServiceTest {
assertEquals("platform", repo.getTags().get("team"));
}
// ------------------------------------------------------------
// Registry unavailable (Floci inside Docker with no Docker daemon)
// ------------------------------------------------------------
@Test
void createRepository_succeedsAsMetadataWhenRegistryIsUnavailable() {
when(registryManager.tryEnsureStarted()).thenReturn(false);
Repository repo = service.createRepository(REPO, null, "IMMUTABLE", true, null, null,
Map.of("Project", "choudoufu"), REGION);
assertEquals(REPO, repo.getRepositoryName());
assertEquals(ACCOUNT, repo.getRegistryId());
assertEquals("arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + REPO,
repo.getRepositoryArn());
assertTrue(repo.getRepositoryUri().endsWith("/" + REPO), repo.getRepositoryUri());
assertEquals("IMMUTABLE", repo.getImageTagMutability());
assertEquals("choudoufu", repo.getTags().get("Project"));
}
@Test
void repositoryMetadataCrudWorksWhenRegistryIsUnavailable() {
when(registryManager.tryEnsureStarted()).thenReturn(false);
service.createRepository(REPO, null, null, null, null, null, Map.of("env", "dev"), REGION);
assertEquals(1, service.describeRepositories(List.of(REPO), null, REGION).size());
assertEquals("dev", service.listTagsForResource(REPO, null, REGION).get("env"));
service.tagResource(REPO, null, Map.of("team", "platform"), REGION);
assertEquals("platform", service.listTagsForResource(REPO, null, REGION).get("team"));
service.deleteRepository(REPO, null, false, REGION);
assertThrows(AwsException.class,
() -> service.describeRepositories(List.of(REPO), null, REGION));
}
@Test
void dataPlaneOperationsFailWithServerExceptionWhenRegistryIsUnavailable() {
service.createRepository(REPO, null, null, null, null, null, null, REGION);
when(registryManager.tryEnsureStarted()).thenReturn(false);
AwsException auth = assertThrows(AwsException.class, () -> service.getAuthorizationToken());
assertEquals("ServerException", auth.getErrorCode());
assertEquals(500, auth.getHttpStatus());
assertTrue(auth.getMessage().contains("Docker"), auth.getMessage());
assertEquals("ServerException",
assertThrows(AwsException.class, () -> service.listImages(REPO, null, REGION)).getErrorCode());
assertEquals("ServerException",
assertThrows(AwsException.class,
() -> service.describeImages(REPO, null, null, REGION)).getErrorCode());
assertEquals("ServerException",
assertThrows(AwsException.class,
() -> service.batchGetImage(REPO, List.of(), null, null, REGION)).getErrorCode());
assertEquals("ServerException",
assertThrows(AwsException.class,
() -> service.batchDeleteImage(REPO, List.of(), null, REGION)).getErrorCode());
}
// ------------------------------------------------------------
// DescribeRepositories
// ------------------------------------------------------------
@@ -227,7 +288,7 @@ class EcrServiceTest {
assertNotNull(data.getExpiresAt());
String decoded = new String(Base64.getDecoder().decode(data.getAuthorizationToken()));
assertTrue(decoded.startsWith("AWS:"), "decoded token should start with AWS: but was: " + decoded);
Mockito.verify(registryManager).ensureStarted();
Mockito.verify(registryManager).tryEnsureStarted();
}
@Test
@@ -143,6 +143,28 @@ class EcrRegistryManagerTest {
}
}
@Test
void tryEnsureStarted_reportsFailureInsteadOfThrowingWhenDockerIsUnreachable() {
// Floci running inside Docker without a mounted daemon socket. The control plane
// must keep working, so the failure is reported rather than propagated.
when(lifecycleManager.createAndStart(any()))
.thenThrow(new RuntimeException("Cannot connect to the Docker daemon"));
for (int attempt = 0; attempt < 6; attempt++) {
assertFalse(manager.tryEnsureStarted(), "attempt " + attempt + " should report unavailable");
}
assertFalse(manager.isStarted());
}
@Test
void tryEnsureStarted_reportsSuccessOnceTheRegistryStarts() {
when(lifecycleManager.createAndStart(any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("0123456789abcdef", Map.of()));
assertTrue(manager.tryEnsureStarted());
assertTrue(manager.isStarted());
}
@Test
void httpClient_usesRegistryContainerDnsWhenRunningInsideDocker() {
when(containerDetector.isRunningInContainer()).thenReturn(true);
@@ -412,7 +412,10 @@ class EksServiceTest {
clusterStore.putForAccount("000000000000", "persisted-cluster", persisted);
EksClusterManager clusterManager = mock(EksClusterManager.class);
doThrow(new RuntimeException("no docker")).when(clusterManager).restoreCluster(persisted);
// The daemon is reachable, so this is a genuine restore failure: the daemonless
// degradation path (which marks the cluster metadata-only ACTIVE) must not kick in.
when(clusterManager.isDockerReachable()).thenReturn(true);
doThrow(new RuntimeException("bad container state")).when(clusterManager).restoreCluster(persisted);
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
@@ -428,6 +431,33 @@ class EksServiceTest {
}
}
@Test
void initRestoresAClusterAsMetadataOnlyWhenNoDockerDaemonIsReachable() {
StorageBackend<String, Cluster> rawClusters = new InMemoryStorage<>();
var clusterStore = new AccountAwareStorageBackend<>(rawClusters, null, "000000000000");
Cluster persisted = new Cluster();
persisted.setName("persisted-cluster");
persisted.setStatus(ClusterStatus.ACTIVE);
clusterStore.putForAccount("000000000000", "persisted-cluster", persisted);
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.isDockerReachable()).thenReturn(false);
doThrow(new RuntimeException("no docker")).when(clusterManager).restoreCluster(persisted);
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(false),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(fixedStorageFactory(new InMemoryStorage<String, ClusterOidcKey>()),
new ObjectMapper()));
try {
restarted.init();
// Same degradation as create: losing the daemon is not the cluster's fault.
assertEquals(ClusterStatus.ACTIVE,
restarted.describeCluster("persisted-cluster").getStatus());
} finally {
restarted.shutdown();
}
}
@SuppressWarnings("unchecked")
private StorageFactory fixedStorageFactory(StorageBackend<String, ?> backend) {
return new StorageFactory(null, null) {
@@ -950,4 +980,91 @@ class EksServiceTest {
() -> eksService.deleteFargateProfile("my-eks-cluster", "missing-profile"));
assertEquals(404, delete.getHttpStatus());
}
private EksService newService(EksClusterManager clusterManager, boolean mock) {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory("000000000000");
}
};
return new EksService(storageFactory, testConfig(mock),
new RegionResolver("us-east-1", "000000000000"), clusterManager, null,
new EksOidcService(storageFactory, new ObjectMapper()));
}
@Test
void createClusterStaysCreatingWhileTheK3sContainerBoots() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any())).thenReturn(true);
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("real-eks");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
assertEquals(ClusterStatus.CREATING, service.createCluster(request).getStatus());
}
@Test
void createClusterReachesActiveMetadataWhenNoDockerDaemonIsReachable() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any())).thenReturn(false);
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("probe-eks");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
request.setTags(Map.of("tofu-estate", "probe1"));
Cluster cluster = service.createCluster(request);
assertEquals(ClusterStatus.ACTIVE, cluster.getStatus());
assertEquals("https://localhost:6500", cluster.getEndpoint());
assertEquals("probe1", cluster.getTags().get("tofu-estate"));
// No k3s API server exists. The empty CA is what says so.
assertEquals("", cluster.getCertificateAuthority().getData());
assertNull(cluster.getContainerId());
}
@Test
void clusterMetadataCrudWorksWhenNoDockerDaemonIsReachable() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any())).thenReturn(false);
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("probe-eks");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
request.setTags(Map.of("tofu-estate", "probe1"));
String arn = service.createCluster(request).getArn();
assertEquals(ClusterStatus.ACTIVE, service.describeCluster("probe-eks").getStatus());
assertEquals(List.of("probe-eks"), service.listClusters());
assertEquals("probe1", service.listTagsForResource(arn).get("tofu-estate"));
service.tagResource(arn, Map.of("Name", "probe-eks"));
assertEquals("probe-eks", service.listTagsForResource(arn).get("Name"));
assertEquals(NodegroupStatus.ACTIVE,
service.createNodeGroup("probe-eks", nodeGroupRequest("ng-1")).getStatus());
service.deleteCluster("probe-eks");
assertThrows(AwsException.class, () -> service.describeCluster("probe-eks"));
}
@Test
void createClusterStillFailsOnAGenuineProvisioningErrorWithAReachableDaemon() {
EksClusterManager clusterManager = mock(EksClusterManager.class);
when(clusterManager.tryStartCluster(any()))
.thenThrow(new RuntimeException("no such image: rancher/k3s"));
EksService service = newService(clusterManager, false);
CreateClusterRequest request = new CreateClusterRequest();
request.setName("broken-eks");
request.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
assertEquals(ClusterStatus.FAILED, service.createCluster(request).getStatus());
}
}
@@ -24,10 +24,11 @@ import static org.mockito.Mockito.when;
class ElastiCacheMemcachedServiceTest {
private ElastiCacheMemcachedService service;
private ElastiCacheMemcachedContainerManager containerManager;
@BeforeEach
void setUp() {
ElastiCacheMemcachedContainerManager containerManager = mock(ElastiCacheMemcachedContainerManager.class);
containerManager = mock(ElastiCacheMemcachedContainerManager.class);
StorageFactory storageFactory = mock(StorageFactory.class);
EmulatorConfig config = mock(EmulatorConfig.class);
@@ -39,7 +40,7 @@ class ElastiCacheMemcachedServiceTest {
when(config.hostname()).thenReturn(Optional.of("localhost"));
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
when(containerManager.start(anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "localhost", 11211));
service = new ElastiCacheMemcachedService(containerManager, storageFactory, config);
@@ -111,7 +112,7 @@ class ElastiCacheMemcachedServiceTest {
when(config.hostname()).thenReturn(Optional.empty());
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
when(containerManager.start(anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "cluster", "172.20.0.10", 11211));
ElastiCacheMemcachedService containerModeService =
@@ -121,4 +122,25 @@ class ElastiCacheMemcachedServiceTest {
assertEquals("172.20.0.10", cluster.getConfigurationEndpoint().address());
}
@Test
void createClusterWithoutDockerDaemonStillReachesAvailable() {
// tryStart() returns null when no Docker daemon is reachable. The cache cluster record is
// metadata, so the create still succeeds and the cluster reaches 'available' on the first
// describe (what SDK/Terraform waiters poll), on Memcached's well-known port.
when(containerManager.tryStart(anyString(), anyString())).thenReturn(null);
CacheCluster cluster = service.createCacheCluster("no-docker-cluster");
assertEquals(CacheClusterStatus.AVAILABLE, cluster.getCacheClusterStatus());
assertEquals("localhost", cluster.getConfigurationEndpoint().address());
assertEquals(11211, cluster.getConfigurationEndpoint().port());
assertEquals("no-docker-cluster",
service.getCacheCluster("no-docker-cluster").getCacheClusterId());
// Delete must not reach for a container that was never created.
service.deleteCacheCluster("no-docker-cluster");
org.mockito.Mockito.verify(containerManager, org.mockito.Mockito.never())
.stop(org.mockito.ArgumentMatchers.any());
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.elasticache;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -75,7 +76,7 @@ class ElastiCacheServiceTest {
when(config.hostname()).thenReturn(java.util.Optional.of("localhost"));
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000"));
when(containerManager.start(anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
Ec2Service ec2Service = org.mockito.Mockito.mock(Ec2Service.class);
@@ -174,7 +175,7 @@ class ElastiCacheServiceTest {
void failedProvisioningRollsBackContainerAndReleasesProxyPort() {
ElastiCacheContainerHandle handle =
new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379);
when(containerManager.start(anyString(), anyString())).thenReturn(handle);
when(containerManager.tryStart(anyString(), anyString())).thenReturn(handle);
// Proxy startup blows up after the port is reserved and the container is started.
doThrow(new RuntimeException("proxy boom"))
@@ -203,7 +204,7 @@ class ElastiCacheServiceTest {
void failedContainerStartupCleansUpContainerByIdAndReleasesPort() {
// Models a readiness timeout: start() throws without ever returning a handle.
doThrow(new RuntimeException("readiness boom"))
.when(containerManager).start(eq("grp"), anyString());
.when(containerManager).tryStart(eq("grp"), anyString());
assertThrows(RuntimeException.class,
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"));
@@ -212,7 +213,7 @@ class ElastiCacheServiceTest {
verify(containerManager).stopByGroupId("grp");
// The reserved proxy port was still released: a subsequent successful create reuses the base port.
when(containerManager.start(anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp2", "localhost", 6379));
ReplicationGroup recovered =
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null, "us-east-1");
@@ -503,7 +504,7 @@ class ElastiCacheServiceTest {
void concurrentCreateForSameGroupIdIsRejectedWhileFirstIsProvisioning() throws InterruptedException {
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.start(anyString(), anyString())).thenAnswer(inv -> {
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379);
@@ -723,7 +724,7 @@ class ElastiCacheServiceTest {
service.createCacheParameterGroup("custom-pg", "redis7", "in use", Map.of());
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.start(anyString(), anyString())).thenAnswer(inv -> {
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379);
@@ -773,7 +774,7 @@ class ElastiCacheServiceTest {
CountDownLatch startedLatch = new CountDownLatch(1);
CountDownLatch releaseLatch = new CountDownLatch(1);
when(containerManager.start(anyString(), anyString())).thenAnswer(inv -> {
when(containerManager.tryStart(anyString(), anyString())).thenAnswer(inv -> {
startedLatch.countDown();
assertTrue(releaseLatch.await(5, TimeUnit.SECONDS), "test timed out waiting for release");
return new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379);
@@ -808,7 +809,7 @@ class ElastiCacheServiceTest {
@Test
void aFailedCreateReleasesItsClaimOnTheParameterGroup() {
service.createCacheParameterGroup("custom-pg", "redis7", "in use", Map.of());
when(containerManager.start(anyString(), anyString()))
when(containerManager.tryStart(anyString(), anyString()))
.thenThrow(new RuntimeException("docker is down"));
assertThrows(RuntimeException.class,
@@ -17,8 +17,10 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -92,4 +94,35 @@ class ElastiCacheContainerManagerTest {
"io.floci.region", "us-east-1"));
}
}
@Test
void tryStartRethrowsWhenDaemonBecomesUnreachableAfterContainerWasCreated() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(6379,
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 6379))));
when(lifecycleManager.getDockerClient()).thenThrow(new IllegalStateException("no daemon"));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElastiCacheServiceConfig elasticache = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.elasticache()).thenReturn(elasticache);
when(elasticache.dockerNetwork()).thenReturn(Optional.empty());
ElastiCacheContainerManager manager = new ElastiCacheContainerManager(containerBuilder, lifecycleManager,
logStreamer, mock(ContainerDetector.class), config, mock(RegionResolver.class));
assertThrows(IllegalStateException.class, () -> manager.tryStart("my-group", "valkey/valkey:7.2"));
verify(lifecycleManager).stopAndRemove(eq("container-id"), any());
}
}
@@ -17,8 +17,10 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -79,4 +81,36 @@ class ElastiCacheMemcachedContainerManagerTest {
"io.floci.region", "us-east-1"));
}
}
@Test
void tryStartRethrowsWhenDaemonBecomesUnreachableAfterContainerWasCreated() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(11211,
new ContainerLifecycleManager.EndpointInfo("127.0.0.1", 11211))));
when(lifecycleManager.getDockerClient()).thenThrow(new IllegalStateException("no daemon"));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
when(logStreamer.attach(any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed after daemon went away"));
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(builder.build()).thenReturn(mock(ContainerSpec.class));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElastiCacheServiceConfig elasticache = mock(EmulatorConfig.ElastiCacheServiceConfig.class);
when(config.services()).thenReturn(services);
when(services.elasticache()).thenReturn(elasticache);
when(elasticache.dockerNetwork()).thenReturn(Optional.empty());
ElastiCacheMemcachedContainerManager manager = new ElastiCacheMemcachedContainerManager(
containerBuilder, lifecycleManager, logStreamer, mock(ContainerDetector.class),
config, mock(RegionResolver.class));
assertThrows(IllegalStateException.class, () -> manager.tryStart("my-cluster", "memcached:1.6"));
verify(lifecycleManager).stopAndRemove(eq("container-id"), any());
}
}
@@ -136,6 +136,34 @@ class MskServiceTest {
assertTrue(mskService.listClusters().isEmpty());
}
@Test
void createClusterStaysCreatingWhileBrokerStarts() {
when(config.services().msk().mock()).thenReturn(false);
when(redpandaManager.tryStartContainer(Mockito.any())).thenReturn(true);
MskCluster cluster = mskService.createCluster("docker-cluster");
assertEquals(ClusterState.CREATING, cluster.getState());
assertEquals(ClusterState.CREATING,
mskService.describeCluster(cluster.getClusterArn()).getState());
}
@Test
void createClusterWithoutDockerDaemonStillReachesActive() {
// tryStartContainer() returns false when no Docker daemon is reachable. The cluster
// record is metadata, so the create still succeeds, reaches ACTIVE, and reports a
// placeholder bootstrap address until a daemon appears.
when(config.services().msk().mock()).thenReturn(false);
when(redpandaManager.tryStartContainer(Mockito.any())).thenReturn(false);
MskCluster cluster = mskService.createCluster("no-docker-cluster");
assertEquals(ClusterState.ACTIVE, cluster.getState());
assertEquals("localhost:9092", cluster.getBootstrapBrokers());
assertEquals("no-docker-cluster",
mskService.describeCluster(cluster.getClusterArn()).getClusterName());
}
@Test
void createClusterPersistsRequestMetadata() {
CreateClusterRequest request = new CreateClusterRequest();
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A domain stays {@code Processing=true} until the readiness poller flips it. Mock mode and a
* Floci with no reachable Docker daemon report {@code Processing=false} from the first read.
*/
class OpenSearchServiceTest {
private OpenSearchService service;
private OpenSearchDomainManager domainManager;
private EmulatorConfig.OpenSearchServiceConfig osConfig;
@BeforeEach
void setUp() {
domainManager = mock(OpenSearchDomainManager.class);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
osConfig = mock(EmulatorConfig.OpenSearchServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.opensearch()).thenReturn(osConfig);
when(osConfig.mock()).thenReturn(false);
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
service = new OpenSearchService(AccountAwareStorageBackend.inMemory("000000000000"),
config, regionResolver, domainManager);
}
@Test
void createDomainKeepsProcessingTrueWhileContainerStarts() {
when(domainManager.tryStartDomain(any())).thenReturn(true);
Domain domain = service.createDomain("docker-domain", "OpenSearch_2.11",
null, null, null, "us-east-1");
assertTrue(domain.isProcessing(),
"the readiness poller flips Processing once the container answers");
assertTrue(service.describeDomain("docker-domain").isProcessing());
verify(domainManager).tryStartDomain(any());
}
@Test
void createDomainWithoutDockerDaemonStillSucceedsAndReportsProcessingFalse() {
// tryStartDomain() returns false when no Docker daemon is reachable. The domain record is
// metadata, so the create still succeeds and the first describe already reports the
// terminal state.
when(domainManager.tryStartDomain(any())).thenReturn(false);
Domain domain = service.createDomain("no-docker-domain", "OpenSearch_2.11",
null, null, null, "us-east-1");
assertFalse(domain.isProcessing());
assertEquals("no-docker-domain", service.describeDomain("no-docker-domain").getDomainName());
assertFalse(service.describeDomain("no-docker-domain").isProcessing());
}
@Test
void mockModeKeepsProcessingFalse() {
when(osConfig.mock()).thenReturn(true);
Domain domain = service.createDomain("mock-domain", "OpenSearch_2.11",
null, null, null, "us-east-1");
assertFalse(domain.isProcessing());
verify(domainManager, Mockito.never()).tryStartDomain(any());
}
}