diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index d93d532349..fe36bf14dd 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -233,6 +233,12 @@ public class EmulatorLifecycle { } void onStop(@Observes ShutdownEvent ignored) { + // Flush persisted state to disk FIRST, before the slow proxy/container teardown below. + // Stopping Docker sidecars (RDS/ElastiCache/etc.) can block long enough to exhaust the + // SIGTERM grace window and trigger SIGKILL; if the flush ran last it would be skipped and + // in-memory (hybrid) data would be lost on an otherwise-graceful shutdown. shutdownAll() + // still runs at the end to stop the flush schedulers and capture any shutdown-time writes. + storageFactory.flushAll(); if (config.services().ec2().enabled() && !config.services().ec2().mock()) { ec2MetadataServer.stop(); } diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java index 07e6a2287f..b085f9c110 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -265,6 +265,22 @@ class EmulatorLifecycleTest { verify(initializationHooksRunner, never()).run(InitializationHook.STOP); } + @Test + @DisplayName("onStop flushes storage BEFORE the slow container teardown, and shuts it down last") + void shouldFlushStorageBeforeContainerTeardown() { + emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class)); + + // The disk flush must run before the blocking Docker container teardown so a graceful + // shutdown can't be cut off by the SIGTERM grace window before data is persisted + // (regression guard for issue #1521). shutdownAll() still runs last to stop the flush + // schedulers and capture any shutdown-time writes. + var inOrder = Mockito.inOrder(storageFactory, rdsContainerManager, elastiCacheContainerManager); + inOrder.verify(storageFactory).flushAll(); + inOrder.verify(elastiCacheContainerManager).stopAll(); + inOrder.verify(rdsContainerManager).stopAll(); + inOrder.verify(storageFactory).shutdownAll(); + } + @Test @DisplayName("Should still run full resource cleanup when a pre-shutdown hook fails") void shouldRunFullCleanupAfterFailingPreShutdownHook() throws IOException, InterruptedException {