From 59c24c5e4e44f48b225c1d2fc99aaa0fe3f45957 Mon Sep 17 00:00:00 2001 From: Simone Paolo Petta <74307062+Simi24@users.noreply.github.com> Date: Wed, 1 Apr 2026 14:36:01 +0200 Subject: [PATCH] fix: defer startup hooks until HTTP server is ready (#157) (#159) Startup hooks that make HTTP calls back to floci (e.g. aws cli) deadlocked because they ran synchronously during StartupEvent, before the HTTP server bound to port 4566. Hooks now run on a virtual thread that polls for port readiness first. When no hooks are configured, behavior is unchanged. --- docs/configuration/initialization-hooks.md | 16 +++-- .../floci/lifecycle/EmulatorLifecycle.java | 41 ++++++++++- .../inithook/InitializationHooksRunner.java | 4 ++ .../lifecycle/EmulatorLifecycleTest.java | 72 +++++++++++++++++++ .../InitializationHooksRunnerTest.java | 34 +++++++++ 5 files changed, 160 insertions(+), 7 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java diff --git a/docs/configuration/initialization-hooks.md b/docs/configuration/initialization-hooks.md index 920fd9ed44..eebe1a820d 100644 --- a/docs/configuration/initialization-hooks.md +++ b/docs/configuration/initialization-hooks.md @@ -5,7 +5,7 @@ environment (creating buckets, populating data, configuring resources, etc.) or Hook scripts ending with `.sh` are discovered in the following directories: -- **Startup hooks** (`/etc/floci/init/start.d`) run after Floci services are initialized, but before the environment is marked as ready. +- **Startup hooks** (`/etc/floci/init/start.d`) run after the HTTP server is ready and accepting connections on port 4566. This means hooks can safely make HTTP calls back to Floci (e.g. using the AWS CLI). - **Shutdown hooks** (`/etc/floci/init/stop.d`) run when Floci is shutting down, after `destroy()` is triggered. If a hook directory does not exist or contains no `.sh` scripts, Floci skips it and continues normally. @@ -22,8 +22,15 @@ Hooks run: - With access to configured services and their endpoints - With the same environment variables as Floci -Hooks can call Floci service endpoints directly from inside the container. If a hook depends on additional CLI tools, -make sure those tools are available in the runtime image. +Hooks can call Floci service endpoints directly from inside the container (e.g. `http://localhost:4566`). +The published Docker image does not include the AWS CLI. If your hooks require it, extend the image: + +```dockerfile +FROM ghcr.io/hectorvent/floci:latest +RUN apk add --no-cache aws-cli +``` + +If a hook depends on additional CLI tools, make sure those tools are available in the runtime image. ### Execution Behavior @@ -38,7 +45,8 @@ Execution uses a fail-fast strategy: - If a script exits with a non-zero status, remaining hooks are not executed. - If a script exceeds the configured timeout, it is terminated and remaining hooks are not executed. -- A hook failure marks the corresponding startup or shutdown phase as **failed**. +- A startup hook failure triggers application shutdown. +- A shutdown hook failure is logged but does not prevent the shutdown from completing. ## Examples 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 13fb7fbdc6..9e1aa5bce8 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager; import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager; +import io.quarkus.runtime.Quarkus; import io.quarkus.runtime.ShutdownEvent; import io.quarkus.runtime.StartupEvent; import jakarta.enterprise.context.ApplicationScoped; @@ -15,11 +16,17 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; @ApplicationScoped public class EmulatorLifecycle { private static final Logger LOG = Logger.getLogger(EmulatorLifecycle.class); + private static final int HTTP_PORT = 4566; + private static final int PORT_POLL_TIMEOUT_MS = 100; + private static final int PORT_POLL_INTERVAL_MS = 50; + private static final int PORT_POLL_MAX_RETRIES = 100; private final StorageFactory storageFactory; private final ServiceRegistry serviceRegistry; @@ -40,16 +47,44 @@ public class EmulatorLifecycle { this.initializationHooksRunner = initializationHooksRunner; } - void onStart(@Observes StartupEvent ignored) throws IOException, InterruptedException { + void onStart(@Observes StartupEvent ignored) throws IOException { LOG.info("=== AWS Local Emulator Starting ==="); LOG.infov("Storage mode: {0}", config.storage().mode()); LOG.infov("Persistent path: {0}", config.storage().persistentPath()); serviceRegistry.logEnabledServices(); storageFactory.loadAll(); - initializationHooksRunner.run(InitializationHook.START); - LOG.info("=== AWS Local Emulator Ready ==="); + if (initializationHooksRunner.hasHooks(InitializationHook.START)) { + LOG.info("Startup hooks detected — deferring execution until HTTP server is ready"); + Thread.ofVirtual().name("init-hooks-runner").start(this::runStartupHooksAfterReady); + } else { + LOG.info("=== AWS Local Emulator Ready ==="); + } + } + + private void runStartupHooksAfterReady() { + try { + waitForHttpPort(); + initializationHooksRunner.run(InitializationHook.START); + LOG.info("=== AWS Local Emulator Ready ==="); + } catch (Exception e) { + LOG.error("Startup hook execution failed — shutting down", e); + Quarkus.asyncExit(); + } + } + + private static void waitForHttpPort() throws InterruptedException { + for (int attempt = 1; attempt <= PORT_POLL_MAX_RETRIES; attempt++) { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("localhost", HTTP_PORT), PORT_POLL_TIMEOUT_MS); + LOG.debugv("HTTP port {0} is ready (attempt {1})", HTTP_PORT, attempt); + return; + } catch (IOException ignored) { + Thread.sleep(PORT_POLL_INTERVAL_MS); + } + } + throw new IllegalStateException("HTTP port " + HTTP_PORT + " did not become ready in time"); } void onStop(@Observes ShutdownEvent ignored) throws IOException, InterruptedException { diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java index df8d1a2bb3..d6af7f709a 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunner.java @@ -44,6 +44,10 @@ public class InitializationHooksRunner { return scriptFileNames; } + public boolean hasHooks(final InitializationHook hook) { + return findScriptFileNames(hook.getName(), hook.getPath()).length > 0; + } + public void run(final InitializationHook hook) throws IOException, InterruptedException { final String hookName = hook.getName(); final File hookDirectory = hook.getPath(); diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java new file mode 100644 index 0000000000..61b572d372 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java @@ -0,0 +1,72 @@ +package io.github.hectorvent.floci.lifecycle; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ServiceRegistry; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; +import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; +import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager; +import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager; +import io.quarkus.runtime.StartupEvent; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.IOException; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EmulatorLifecycleTest { + + @Mock private StorageFactory storageFactory; + @Mock private ServiceRegistry serviceRegistry; + @Mock private EmulatorConfig config; + @Mock private EmulatorConfig.StorageConfig storageConfig; + @Mock private ElastiCacheProxyManager elastiCacheProxyManager; + @Mock private RdsProxyManager rdsProxyManager; + @Mock private InitializationHooksRunner initializationHooksRunner; + + private EmulatorLifecycle emulatorLifecycle; + + @BeforeEach + void setUp() { + when(config.storage()).thenReturn(storageConfig); + when(storageConfig.mode()).thenReturn("in-memory"); + when(storageConfig.persistentPath()).thenReturn("/app/data"); + emulatorLifecycle = new EmulatorLifecycle( + storageFactory, serviceRegistry, config, + elastiCacheProxyManager, rdsProxyManager, initializationHooksRunner); + } + + @Test + @DisplayName("Should log Ready immediately when no startup hooks exist") + void shouldLogReadyImmediatelyWhenNoHooksExist() throws IOException, InterruptedException { + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(storageFactory).loadAll(); + verify(initializationHooksRunner).hasHooks(InitializationHook.START); + verify(initializationHooksRunner, never()).run(InitializationHook.START); + } + + @Test + @DisplayName("Should defer hook execution when startup hooks exist") + void shouldDeferHookExecutionWhenHooksExist() throws IOException, InterruptedException { + when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(true); + + emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class)); + + verify(storageFactory).loadAll(); + verify(initializationHooksRunner).hasHooks(InitializationHook.START); + // run() is NOT called synchronously — it will be called by the virtual thread + verify(initializationHooksRunner, never()).run(InitializationHook.START); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java index 7d1f5c0283..9239ab3699 100644 --- a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHooksRunnerTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -12,6 +13,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; @ExtendWith(MockitoExtension.class) class InitializationHooksRunnerTest { @@ -152,4 +155,35 @@ class InitializationHooksRunnerTest { Assertions.assertSame(interruptedException, exception); } + @Test + @DisplayName("hasHooks should return true when scripts exist in hook directory") + void hasHooksShouldReturnTrueWhenScriptsExist(@TempDir Path tempDir) throws IOException { + Files.createFile(tempDir.resolve("01-setup.sh")); + InitializationHook hook = Mockito.mock(InitializationHook.class); + Mockito.when(hook.getName()).thenReturn("startup"); + Mockito.when(hook.getPath()).thenReturn(tempDir.toFile()); + + Assertions.assertTrue(initializationHooksRunner.hasHooks(hook)); + } + + @Test + @DisplayName("hasHooks should return false when hook directory is empty") + void hasHooksShouldReturnFalseWhenDirectoryIsEmpty(@TempDir Path tempDir) { + InitializationHook hook = Mockito.mock(InitializationHook.class); + Mockito.when(hook.getName()).thenReturn("startup"); + Mockito.when(hook.getPath()).thenReturn(tempDir.toFile()); + + Assertions.assertFalse(initializationHooksRunner.hasHooks(hook)); + } + + @Test + @DisplayName("hasHooks should return false when hook directory does not exist") + void hasHooksShouldReturnFalseWhenDirectoryDoesNotExist() { + InitializationHook hook = Mockito.mock(InitializationHook.class); + Mockito.when(hook.getName()).thenReturn("startup"); + Mockito.when(hook.getPath()).thenReturn(new File("/nonexistent/path")); + + Assertions.assertFalse(initializationHooksRunner.hasHooks(hook)); + } + }