mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lifecycle): tear down process-bound containers on shutdown (#1869)
Containers whose lifetime is bound to the emulator process (Lambda warm pool, ECS tasks, EC2 instances, in-flight Batch and CodeBuild jobs) were cleaned up ad hoc via @PreDestroy, which runs after the ShutdownEvent observers when the storage flush schedulers are already stopped — so containers could leak and state changes made during stop were lost. Introduce a ContainerTeardown contract implemented by each runner and invoke every implementation from EmulatorLifecycle.onStop before StorageFactory.shutdownAll(), making teardown deterministic and keeping its state changes in the final flush. Implementations stay idempotent, with @PreDestroy retained as a fallback.
This commit is contained in:
1 parent
aa77d4ce46
commit
eae039fbd0
11 files changed
+312
-40
No files matched your search
@@ -78,6 +78,7 @@ class EmulatorLifecycleTest {
|
||||
@Mock private InitLifecycleState initLifecycleState;
|
||||
@Mock private EmulatorConfig.TlsConfig tlsConfig;
|
||||
@Mock private io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker schemaCreationWorker;
|
||||
@Mock private jakarta.enterprise.inject.Instance<io.github.hectorvent.floci.core.common.ContainerTeardown> containerTeardowns;
|
||||
|
||||
private EmulatorLifecycle emulatorLifecycle;
|
||||
|
||||
@@ -98,7 +99,9 @@ class EmulatorLifecycleTest {
|
||||
rabbitMqManager, rdsService,
|
||||
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
|
||||
pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState,
|
||||
schemaCreationWorker);
|
||||
schemaCreationWorker, containerTeardowns);
|
||||
Mockito.lenient().when(containerTeardowns.iterator())
|
||||
.thenReturn(java.util.Collections.emptyIterator());
|
||||
}
|
||||
|
||||
private void stubStorageConfig() {
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package io.github.hectorvent.floci.services.ecs;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
|
||||
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Verifies emulator-shutdown teardown stops the Docker containers of running tasks
|
||||
* exactly once. Without it, task containers outlive the process as orphans (task
|
||||
* state is transient, so nothing reclaims them on the next start).
|
||||
*/
|
||||
class EcsServiceTeardownTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void stopManagedContainersStopsEachRunningTaskOnce() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().ecs().mock()).thenReturn(false); // docker mode
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
|
||||
EcsContainerManager containerManager = mock(EcsContainerManager.class);
|
||||
EcsTaskHandle handle = mock(EcsTaskHandle.class);
|
||||
when(containerManager.startTask(any(), any(), any(), anyString())).thenReturn(handle);
|
||||
|
||||
EcsService service = new EcsService(
|
||||
new RegionResolver(REGION, "000000000000"),
|
||||
containerManager,
|
||||
config,
|
||||
mock(EcsLoadBalancerRegistrar.class),
|
||||
new SingleUseStorageFactory());
|
||||
service.initializeStorage();
|
||||
|
||||
ContainerDefinition cd = new ContainerDefinition();
|
||||
cd.setName("app");
|
||||
cd.setImage("nginx:alpine");
|
||||
service.registerTaskDefinition("teardown-fam", List.of(cd), null, null, null,
|
||||
null, null, List.of(), REGION);
|
||||
service.runTask(null, "teardown-fam", 1, LaunchType.FARGATE, null, null,
|
||||
List.of(), null, REGION);
|
||||
|
||||
service.stopManagedContainers();
|
||||
verify(containerManager, times(1)).stopTask(handle);
|
||||
|
||||
// The reconciler must be stopped before handles are drained, or a tick could
|
||||
// restart the drained tasks between teardown and the final storage flush.
|
||||
assertTrue(service.isReconcilerShutdown());
|
||||
|
||||
// Handles are claimed on the first pass; a second invocation must be a no-op.
|
||||
service.stopManagedContainers();
|
||||
verify(containerManager, times(1)).stopTask(handle);
|
||||
}
|
||||
|
||||
private static final class SingleUseStorageFactory extends StorageFactory {
|
||||
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
|
||||
|
||||
private SingleUseStorageFactory() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> StorageBackend<String, V> create(String serviceName,
|
||||
String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (StorageBackend<String, V>) stores.computeIfAbsent(fileName, ignored -> new InMemoryStorage<>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -40,29 +37,33 @@ class WarmPoolTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownHookRegisteredAfterInit() throws Exception {
|
||||
void stopManagedContainersDrainsPool() {
|
||||
// Lifecycle-driven teardown replaces the old raw JVM shutdown hook: the pool
|
||||
// drains when EmulatorLifecycle.onStop invokes the ContainerTeardown contract.
|
||||
WarmPool pool = buildPool();
|
||||
pool.init();
|
||||
|
||||
Field hookField = WarmPool.class.getDeclaredField("shutdownHook");
|
||||
hookField.setAccessible(true);
|
||||
Thread hook = (Thread) hookField.get(pool);
|
||||
LambdaFunction fn = mock(LambdaFunction.class);
|
||||
when(fn.getFunctionName()).thenReturn("drain-fn");
|
||||
ContainerHandle handle = new ContainerHandle("cid-drain", "drain-fn", null, ContainerState.WARM);
|
||||
when(containerLauncher.launch(any())).thenReturn(handle);
|
||||
|
||||
assertNotNull(hook);
|
||||
pool.release(pool.acquire(fn));
|
||||
pool.stopManagedContainers();
|
||||
verify(containerLauncher).stop(handle);
|
||||
|
||||
// Idempotent: a second drain (e.g. the @PreDestroy fallback) is a no-op.
|
||||
pool.stopManagedContainers();
|
||||
verify(containerLauncher, times(1)).stop(handle);
|
||||
pool.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownHookDrainsEmptyPool() throws Exception {
|
||||
void stopManagedContainersOnEmptyPoolIsNoOp() {
|
||||
WarmPool pool = buildPool();
|
||||
pool.init();
|
||||
|
||||
Field hookField = WarmPool.class.getDeclaredField("shutdownHook");
|
||||
hookField.setAccessible(true);
|
||||
Thread hook = (Thread) hookField.get(pool);
|
||||
|
||||
// Running the hook on an empty pool must not throw
|
||||
hook.run();
|
||||
pool.stopManagedContainers();
|
||||
|
||||
pool.shutdown();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user