Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(core): make the init hook directory configurable (#5801)

Hector Ventura050f93e60043
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 08569e3e3e..eaa86478aa 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -173,6 +173,7 @@ With TLS, set `FLOCI_DNS_SPOOF_AWS_ENDPOINTS` as an environment variable (or `-D
| Variable | Default | Description |
|---|---|---|
+| `FLOCI_INIT_HOOKS_DIR` | `/etc/floci/init` | Root of the Floci hook directories (`boot.d`, `start.d`, `ready.d`, `stop.d`, `shutdown.d`) |
| `FLOCI_INIT_HOOKS_SHELL_EXECUTABLE` | `/bin/sh` | Shell used to execute hook scripts |
| `FLOCI_INIT_HOOKS_TIMEOUT_SECONDS` | `30` | Maximum time a single hook script may run |
| `FLOCI_INIT_HOOKS_SHUTDOWN_GRACE_PERIOD_SECONDS` | `2` | Time allowed for stop hooks to complete during shutdown |
diff --git a/docs/configuration/initialization-hooks.md b/docs/configuration/initialization-hooks.md
index 80c975d951..9acefbc56b 100644
--- a/docs/configuration/initialization-hooks.md
+++ b/docs/configuration/initialization-hooks.md
@@ -34,6 +34,10 @@ Floci merges scripts from two directory trees. The Floci-native tree has priorit
The LocalStack-compat paths let existing LocalStack bootstrap scripts work without modification.
Mount them under `/etc/localstack/init/` and they run as-is.
+The Floci root is `/etc/floci/init` by default, which is where the image expects the directories to be
+mounted. When Floci runs as a binary on the host, set `FLOCI_INIT_HOOKS_DIR` to a directory of your
+own: the phase directories are read from under it (for example `~/floci-init/ready.d`).
+
## Script Types
Floci discovers scripts with the following extensions:
@@ -41,6 +45,15 @@ Floci discovers scripts with the following extensions:
- `.sh` — executed with the configured shell (default `/bin/sh`)
- `.py` — executed with `python3`
+On Windows, where there is no `/bin/sh`, Floci also runs:
+
+- `.ps1` with PowerShell (`powershell -NoProfile -ExecutionPolicy Bypass -File`)
+- `.cmd` and `.bat` with `cmd /c`
+- `.py` with `python` rather than `python3`
+
+`.sh` scripts are skipped on Windows, with a warning naming the file, unless `FLOCI_INIT_HOOKS_SHELL_EXECUTABLE`
+points at a shell such as Git Bash. On Linux and macOS, `.ps1`, `.cmd` and `.bat` files are ignored.
+
Files with any other extension are ignored.
## Execution Order and Behavior
@@ -166,6 +179,7 @@ aws ssm delete-parameter --name /app/bootstrapped
| Variable | Default | Description |
|---|---|---|
+| `FLOCI_INIT_HOOKS_DIR` | `/etc/floci/init` | Root of the Floci hook directories (`boot.d`, `start.d`, `ready.d`, `stop.d`, `shutdown.d`) |
| `FLOCI_INIT_HOOKS_SHELL_EXECUTABLE` | `/bin/sh` | Shell used to run `.sh` scripts |
| `FLOCI_INIT_HOOKS_TIMEOUT_SECONDS` | `30` | Maximum runtime per script before it is killed and treated as a failure |
| `FLOCI_INIT_HOOKS_SHUTDOWN_GRACE_PERIOD_SECONDS` | `2` | Extra wait after terminating a timed-out script |
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index c684958afa..008782a764 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -3509,6 +3509,15 @@ public interface EmulatorConfig {
}
interface InitHooksConfig {
+ /**
+ * Root of the Floci-native hook directories ({@code boot.d}, {@code start.d}, {@code ready.d},
+ * {@code stop.d}, {@code shutdown.d}). The image mounts them under the default; a binary on
+ * the host points this at a directory of its own. The LocalStack-compat tree under
+ * {@code /etc/localstack/init} is always read as well.
+ */
+ @WithDefault("/etc/floci/init")
+ String dir();
+
@WithDefault("/bin/sh")
String shellExecutable();
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
index b30bf46004..9b4740aabe 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptExecutor.java
@@ -18,10 +18,16 @@ public class HookScriptExecutor {
private static final Logger LOG = Logger.getLogger(HookScriptExecutor.class);
private final EmulatorConfig.InitHooksConfig initHooksConfig;
+ private final boolean windows;
@Inject
public HookScriptExecutor(final EmulatorConfig emulatorConfig) {
+ this(emulatorConfig, System.getProperty("os.name", ""));
+ }
+
+ HookScriptExecutor(final EmulatorConfig emulatorConfig, final String osName) {
this.initHooksConfig = emulatorConfig.initHooks();
+ this.windows = HookScripts.isWindows(osName);
}
public void run(final File scriptFile) throws IOException, InterruptedException {
@@ -29,11 +35,11 @@ public class HookScriptExecutor {
}
public void run(final File hookDirectory, final String scriptFileName) throws IOException, InterruptedException {
- final String command = scriptFileName.endsWith(".py") ? "python3" : initHooksConfig.shellExecutable();
- LOG.debugv("Executing hook script {0} via {1}", scriptFileName, command);
+ final List<String> command = HookScripts.command(scriptFileName, windows, initHooksConfig.shellExecutable());
+ LOG.debugv("Executing hook script {0} via {1}", scriptFileName, command.getFirst());
// Inherit parent I/O so script output is streamed directly and does not block on unconsumed buffers.
- final Process process = new ProcessBuilder(command, scriptFileName).directory(hookDirectory).inheritIO().start();
+ final Process process = new ProcessBuilder(command).directory(hookDirectory).inheritIO().start();
run(process, scriptFileName);
}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScripts.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScripts.java
new file mode 100644
index 0000000000..0e7c165269
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/HookScripts.java
@@ -0,0 +1,68 @@
+package io.github.hectorvent.floci.lifecycle.inithook;
+
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Which hook scripts can run on this platform, and the command that runs each.
+ *
+ * <p>On Linux and macOS, {@code .sh} runs with the configured shell and {@code .py} with
+ * {@code python3}, as in the image. A native binary on Windows has no {@code /bin/sh}, so there
+ * {@code .ps1} runs with PowerShell, {@code .cmd} and {@code .bat} with {@code cmd}, {@code .py}
+ * with {@code python}, and {@code .sh} only when a shell other than the default
+ * {@code /bin/sh} is configured (Git Bash, for example). Windows file names are case-insensitive, so
+ * there {@code SETUP.BAT} is a {@code .bat} hook; elsewhere the extension must be lower case, as
+ * before.
+ */
+final class HookScripts {
+
+ static final String DEFAULT_SHELL = "/bin/sh";
+
+ private HookScripts() {
+ }
+
+ static boolean isWindows(String osName) {
+ return osName != null && osName.toLowerCase(Locale.ROOT).startsWith("windows");
+ }
+
+ /** Whether the file is a hook script at all, on any platform. */
+ static boolean isScript(String fileName, boolean windows) {
+ return extensionOf(fileName, windows) != null;
+ }
+
+ static boolean canRun(String fileName, boolean windows, String shell) {
+ String extension = extensionOf(fileName, windows);
+ if (extension == null) {
+ return false;
+ }
+ return switch (extension) {
+ case ".sh" -> !windows || !DEFAULT_SHELL.equals(shell);
+ case ".py" -> true;
+ case ".ps1", ".cmd", ".bat" -> windows;
+ default -> false;
+ };
+ }
+
+ static List<String> command(String fileName, boolean windows, String shell) {
+ String extension = extensionOf(fileName, windows);
+ if (extension == null) {
+ throw new IllegalArgumentException("Not a hook script: " + fileName);
+ }
+ return switch (extension) {
+ case ".py" -> List.of(windows ? "python" : "python3", fileName);
+ case ".ps1" -> List.of("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", fileName);
+ case ".cmd", ".bat" -> List.of("cmd", "/c", fileName);
+ default -> List.of(shell, fileName);
+ };
+ }
+
+ private static String extensionOf(String fileName, boolean windows) {
+ String name = windows ? fileName.toLowerCase(Locale.ROOT) : fileName;
+ for (String extension : List.of(".sh", ".py", ".ps1", ".cmd", ".bat")) {
+ if (name.endsWith(extension)) {
+ return extension;
+ }
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
index 938d1efb24..c20b220390 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/inithook/InitializationHook.java
@@ -1,33 +1,30 @@
package io.github.hectorvent.floci.lifecycle.inithook;
import java.io.File;
+import java.nio.file.Path;
import java.util.List;
public enum InitializationHook {
- BOOT("boot", "boot",
- List.of("/etc/floci/init/boot.d"),
- List.of("/etc/localstack/init/boot.d")),
- START("startup", "start",
- List.of("/etc/floci/init/start.d"),
- List.of("/etc/localstack/init/start.d")),
- READY("ready", "ready",
- List.of("/etc/floci/init/ready.d"),
- List.of("/etc/localstack/init/ready.d")),
- STOP("shutdown", "shutdown",
- List.of("/etc/floci/init/stop.d", "/etc/floci/init/shutdown.d"),
- List.of("/etc/localstack/init/shutdown.d"));
+ BOOT("boot", "boot", List.of("boot.d"), List.of("boot.d")),
+ START("startup", "start", List.of("start.d"), List.of("start.d")),
+ READY("ready", "ready", List.of("ready.d"), List.of("ready.d")),
+ STOP("shutdown", "shutdown", List.of("stop.d", "shutdown.d"), List.of("shutdown.d"));
+
+ /** Default of {@code floci.init-hooks.dir}: where the image expects hook directories to be mounted. */
+ public static final String DEFAULT_ROOT = "/etc/floci/init";
+ static final String COMPAT_ROOT = "/etc/localstack/init";
private final String name;
private final String responseKey;
- private final List<File> primaryPaths;
+ private final List<String> primarySubdirs;
private final List<File> compatPaths;
- InitializationHook(String name, String responseKey, List<String> primaryPaths, List<String> compatPaths) {
+ InitializationHook(String name, String responseKey, List<String> primarySubdirs, List<String> compatSubdirs) {
this.name = name;
this.responseKey = responseKey;
- this.primaryPaths = primaryPaths.stream().map(File::new).toList();
- this.compatPaths = compatPaths.stream().map(File::new).toList();
+ this.primarySubdirs = primarySubdirs;
+ this.compatPaths = compatSubdirs.stream().map(dir -> new File(COMPAT_ROOT, dir)).toList();
}
public String getName() {
@@ -39,9 +36,12 @@ public enum InitializationHook {
return responseKey;
}
- /** Floci-native directories for this phase. First occurrence of a filename wins. */
- public List<File> getPrimaryPaths() {
- return primaryPaths;
+ /**
+ * Floci-native directories for this phase under {@code root} ({@code floci.init-hooks.dir}). First
+ * occurrence of a filename wins.
+ */
+ public List<File> getPrimaryPaths(String root) {
+ return primarySubdirs.stream().map(dir -> Path.of(root, dir).toFile()).toList();
}
/** LocalStack-compat directories for this phase. Only used when a filename is not already in a primary path. */
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 886bc495d5..3f60e50807 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
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.lifecycle.inithook;
+import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -12,23 +13,55 @@ import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class InitializationHooksRunner {
private static final Logger LOG = Logger.getLogger(InitializationHooksRunner.class);
- private static final FilenameFilter SCRIPT_FILE_FILTER =
- (ignored, name) -> name.endsWith(".sh") || name.endsWith(".py");
-
private final HookScriptExecutor hookScriptExecutor;
private final InitLifecycleState initLifecycleState;
+ private final String hooksRoot;
+ private final FilenameFilter scriptFileFilter;
+ private final Set<String> warnedSkips = ConcurrentHashMap.newKeySet();
@Inject
public InitializationHooksRunner(final HookScriptExecutor hookScriptExecutor,
- final InitLifecycleState initLifecycleState) {
+ final InitLifecycleState initLifecycleState,
+ final EmulatorConfig emulatorConfig) {
+ this(hookScriptExecutor, initLifecycleState, emulatorConfig, System.getProperty("os.name", ""));
+ }
+
+ InitializationHooksRunner(final HookScriptExecutor hookScriptExecutor,
+ final InitLifecycleState initLifecycleState,
+ final EmulatorConfig emulatorConfig,
+ final String osName) {
this.hookScriptExecutor = hookScriptExecutor;
this.initLifecycleState = initLifecycleState;
+ this.hooksRoot = emulatorConfig.initHooks().dir();
+ boolean windows = HookScripts.isWindows(osName);
+ String shell = emulatorConfig.initHooks().shellExecutable();
+ this.scriptFileFilter = (dir, name) -> runnable(dir, name, windows, shell);
+ }
+
+ /**
+ * Whether a file in a hook directory runs here. Windows script types are ignored without a word
+ * on Linux and macOS; a {@code .sh} hook Windows cannot run is warned about once per file, not
+ * on every directory listing.
+ */
+ private boolean runnable(File dir, String name, boolean windows, String shell) {
+ if (!HookScripts.isScript(name, windows)) {
+ return false;
+ }
+ if (HookScripts.canRun(name, windows, shell)) {
+ return true;
+ }
+ if (windows && warnedSkips.add(new File(dir, name).getAbsolutePath())) {
+ LOG.warnv("Skipping hook script {0}: it cannot run on this platform (shell {1})", name, shell);
+ }
+ return false;
}
public boolean hasHooks(final InitializationHook hook) {
@@ -85,9 +118,9 @@ public class InitializationHooksRunner {
* Merges scripts from all primary (Floci) paths and then compat (LocalStack) paths.
* First occurrence of a filename wins; merged list is sorted lexicographically.
*/
- private static List<File> findMergedScripts(final InitializationHook hook) {
+ private List<File> findMergedScripts(final InitializationHook hook) {
final Map<String, File> merged = new LinkedHashMap<>();
- for (final File dir : hook.getPrimaryPaths()) {
+ for (final File dir : hook.getPrimaryPaths(hooksRoot)) {
collectScripts(hook.getName(), dir, merged);
}
for (final File dir : hook.getCompatPaths()) {
@@ -99,7 +132,7 @@ public class InitializationHooksRunner {
.toList();
}
- private static void collectScripts(final String hookName, final File dir,
+ private void collectScripts(final String hookName, final File dir,
final Map<String, File> target) {
if (!dir.exists()) {
LOG.debugv("{0} hook directory does not exist: {1}", hookName, dir.getAbsolutePath());
@@ -109,7 +142,7 @@ public class InitializationHooksRunner {
LOG.warnv("{0} hook path is not a directory: {1}", hookName, dir.getAbsolutePath());
return;
}
- final File[] scripts = dir.listFiles(SCRIPT_FILE_FILTER);
+ final File[] scripts = dir.listFiles(scriptFileFilter);
if (scripts == null || scripts.length == 0) {
LOG.debugv("No {0} hook scripts found in {1}", hookName, dir.getAbsolutePath());
return;
@@ -123,7 +156,7 @@ public class InitializationHooksRunner {
}
}
- private static String[] findScriptFileNames(final String hookName, final File hookDirectory) {
+ private String[] findScriptFileNames(final String hookName, final File hookDirectory) {
if (!hookDirectory.exists()) {
LOG.debugv("{0} hook directory does not exist: {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
@@ -132,7 +165,7 @@ public class InitializationHooksRunner {
LOG.warnv("{0} hook path is not a directory: {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
}
- final String[] scriptFileNames = hookDirectory.list(SCRIPT_FILE_FILTER);
+ final String[] scriptFileNames = hookDirectory.list(scriptFileFilter);
if (scriptFileNames == null || scriptFileNames.length == 0) {
LOG.debugv("No {0} hook scripts found in {1}", hookName, hookDirectory.getAbsolutePath());
return new String[0];
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 35d17cc67e..684028830d 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -307,6 +307,12 @@ floci:
allow-unsafe-network-exposure: false
allow-private-jwt-targets: false
+ init-hooks:
+ dir: /etc/floci/init # FLOCI_INIT_HOOKS_DIR: root of boot.d, start.d, ready.d, stop.d, shutdown.d (a binary on the host points it elsewhere)
+ shell-executable: /bin/sh # FLOCI_INIT_HOOKS_SHELL_EXECUTABLE: runs .sh hooks
+ timeout-seconds: 30
+ shutdown-grace-period-seconds: 2
+
tls:
enabled: false # FLOCI_TLS_ENABLED (default: false)
# cert-path: "" # FLOCI_TLS_CERT_PATH (PEM certificate file)
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptsTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptsTest.java
new file mode 100644
index 0000000000..eb604fe023
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/inithook/HookScriptsTest.java
@@ -0,0 +1,50 @@
+package io.github.hectorvent.floci.lifecycle.inithook;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+class HookScriptsTest {
+
+ @Test
+ void unixCommandsMatchTheImage() {
+ assertThat(HookScripts.command("01.sh", false, "/bin/sh"), equalTo(List.of("/bin/sh", "01.sh")));
+ assertThat(HookScripts.command("01.py", false, "/bin/sh"), equalTo(List.of("python3", "01.py")));
+ }
+
+ @Test
+ void windowsCommandsUseNativeInterpreters() {
+ assertThat(HookScripts.command("01.ps1", true, "/bin/sh"),
+ equalTo(List.of("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "01.ps1")));
+ assertThat(HookScripts.command("01.bat", true, "/bin/sh"), equalTo(List.of("cmd", "/c", "01.bat")));
+ assertThat(HookScripts.command("01.py", true, "/bin/sh"), equalTo(List.of("python", "01.py")));
+ }
+
+ @Test
+ void runnableDependsOnPlatformAndShell() {
+ assertThat(HookScripts.canRun("01.sh", false, "/bin/sh"), is(true));
+ assertThat(HookScripts.canRun("01.ps1", false, "/bin/sh"), is(false));
+ assertThat(HookScripts.canRun("01.sh", true, "/bin/sh"), is(false));
+ assertThat(HookScripts.canRun("01.sh", true, "bash.exe"), is(true));
+ assertThat(HookScripts.canRun("notes.txt", true, "/bin/sh"), is(false));
+ }
+
+ @Test
+ void windowsMatchesExtensionsInAnyCase() {
+ assertThat(HookScripts.command("SETUP.BAT", true, "/bin/sh"), equalTo(List.of("cmd", "/c", "SETUP.BAT")));
+ assertThat(HookScripts.canRun("Init.PS1", true, "/bin/sh"), is(true));
+ assertThat(HookScripts.isScript("SEED.SH", false), is(false));
+ assertThat(HookScripts.isScript("seed.sh", false), is(true));
+ }
+
+ @Test
+ void windowsIsDetectedFromOsName() {
+ assertThat(HookScripts.isWindows("Windows Server 2022"), is(true));
+ assertThat(HookScripts.isWindows("Mac OS X"), is(false));
+ assertThat(HookScripts.isWindows(null), is(false));
+ }
+}
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 3183f45de4..6afc9e6dc5 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
@@ -1,14 +1,15 @@
package io.github.hectorvent.floci.lifecycle.inithook;
+import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.lifecycle.InitLifecycleState;
import org.junit.jupiter.api.Assertions;
+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.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
-import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -30,9 +31,94 @@ class InitializationHooksRunnerTest {
@Mock
private InitLifecycleState initLifecycleStateMock;
- @InjectMocks
private InitializationHooksRunner initializationHooksRunner;
+ @BeforeEach
+ void setUp() {
+ initializationHooksRunner = runner(InitializationHook.DEFAULT_ROOT, "Linux");
+ }
+
+ private InitializationHooksRunner runner(String root, String osName) {
+ return runner(root, osName, "/bin/sh");
+ }
+
+ private InitializationHooksRunner runner(String root, String osName, String shell) {
+ EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
+ Mockito.lenient().when(config.initHooks().dir()).thenReturn(root);
+ Mockito.lenient().when(config.initHooks().shellExecutable()).thenReturn(shell);
+ return new InitializationHooksRunner(hookScriptExecutorMock, initLifecycleStateMock, config, osName);
+ }
+
+ @Test
+ void configuredDirReplacesDefaultRoot(@TempDir Path root) throws IOException, InterruptedException {
+ Files.createDirectories(root.resolve("ready.d"));
+ Files.createFile(root.resolve("ready.d").resolve("01-seed.sh"));
+
+ runner(root.toString(), "Linux").run(InitializationHook.READY);
+
+ Mockito.verify(hookScriptExecutorMock).run(root.resolve("ready.d").resolve("01-seed.sh").toFile());
+ }
+
+ @Test
+ void configuredDirKeepsBothStopDirectories(@TempDir Path root) throws IOException, InterruptedException {
+ Files.createDirectories(root.resolve("stop.d"));
+ Files.createDirectories(root.resolve("shutdown.d"));
+ Files.createFile(root.resolve("stop.d").resolve("01-a.sh"));
+ Files.createFile(root.resolve("shutdown.d").resolve("02-b.sh"));
+
+ runner(root.toString(), "Linux").run(InitializationHook.STOP);
+
+ InOrder inOrder = Mockito.inOrder(hookScriptExecutorMock);
+ inOrder.verify(hookScriptExecutorMock).run(root.resolve("stop.d").resolve("01-a.sh").toFile());
+ inOrder.verify(hookScriptExecutorMock).run(root.resolve("shutdown.d").resolve("02-b.sh").toFile());
+ }
+
+ @Test
+ void windowsRunsNativeScriptsAndSkipsShell(@TempDir Path root) throws IOException, InterruptedException {
+ Path ready = Files.createDirectories(root.resolve("ready.d"));
+ Files.createFile(ready.resolve("01-seed.ps1"));
+ Files.createFile(ready.resolve("02-seed.cmd"));
+ Files.createFile(ready.resolve("03-seed.sh"));
+
+ runner(root.toString(), "Windows 11").run(InitializationHook.READY);
+
+ Mockito.verify(hookScriptExecutorMock).run(ready.resolve("01-seed.ps1").toFile());
+ Mockito.verify(hookScriptExecutorMock).run(ready.resolve("02-seed.cmd").toFile());
+ Mockito.verify(hookScriptExecutorMock, Mockito.never()).run(ready.resolve("03-seed.sh").toFile());
+ }
+
+ @Test
+ void windowsRunsUppercaseExtensions(@TempDir Path root) throws IOException, InterruptedException {
+ Path ready = Files.createDirectories(root.resolve("ready.d"));
+ Files.createFile(ready.resolve("01-SETUP.BAT"));
+ Files.createFile(ready.resolve("02-Init.PS1"));
+
+ runner(root.toString(), "Windows 11").run(InitializationHook.READY);
+
+ Mockito.verify(hookScriptExecutorMock).run(ready.resolve("01-SETUP.BAT").toFile());
+ Mockito.verify(hookScriptExecutorMock).run(ready.resolve("02-Init.PS1").toFile());
+ }
+
+ @Test
+ void windowsRunsShellScriptsWithAConfiguredShell(@TempDir Path root) throws IOException, InterruptedException {
+ Path ready = Files.createDirectories(root.resolve("ready.d"));
+ Files.createFile(ready.resolve("01-seed.sh"));
+
+ runner(root.toString(), "Windows 11", "C:/Program Files/Git/bin/bash.exe").run(InitializationHook.READY);
+
+ Mockito.verify(hookScriptExecutorMock).run(ready.resolve("01-seed.sh").toFile());
+ }
+
+ @Test
+ void unixIgnoresWindowsScripts(@TempDir Path root) throws IOException, InterruptedException {
+ Path ready = Files.createDirectories(root.resolve("ready.d"));
+ Files.createFile(ready.resolve("01-seed.ps1"));
+
+ runner(root.toString(), "Linux").run(InitializationHook.READY);
+
+ Mockito.verifyNoInteractions(hookScriptExecutorMock);
+ }
+
@Test
@DisplayName("Should execute shell scripts in sorted order")
void shouldExecuteShellScriptsInSortedOrder() throws IOException, InterruptedException {
@@ -169,7 +255,7 @@ class InitializationHooksRunnerTest {
Files.createFile(tempDir.resolve("01-setup.sh"));
InitializationHook hook = inlineMock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
+ Mockito.when(hook.getPrimaryPaths(Mockito.anyString())).thenReturn(List.of(tempDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
@@ -181,7 +267,7 @@ class InitializationHooksRunnerTest {
Files.createFile(tempDir.resolve("01-setup.sh"));
InitializationHook hook = inlineMock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of());
+ Mockito.when(hook.getPrimaryPaths(Mockito.anyString())).thenReturn(List.of());
Mockito.when(hook.getCompatPaths()).thenReturn(List.of(tempDir.toFile()));
Assertions.assertTrue(initializationHooksRunner.hasHooks(hook));
@@ -192,7 +278,7 @@ class InitializationHooksRunnerTest {
void hasHooksShouldReturnFalseWhenDirectoryIsEmpty(@TempDir Path tempDir) {
InitializationHook hook = inlineMock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(tempDir.toFile()));
+ Mockito.when(hook.getPrimaryPaths(Mockito.anyString())).thenReturn(List.of(tempDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
@@ -203,7 +289,7 @@ class InitializationHooksRunnerTest {
void hasHooksShouldReturnFalseWhenDirectoryDoesNotExist() {
InitializationHook hook = inlineMock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("startup");
- Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(new File("/nonexistent/path")));
+ Mockito.when(hook.getPrimaryPaths(Mockito.anyString())).thenReturn(List.of(new File("/nonexistent/path")));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of());
Assertions.assertFalse(initializationHooksRunner.hasHooks(hook));
@@ -219,7 +305,7 @@ class InitializationHooksRunnerTest {
InitializationHook hook = inlineMock(InitializationHook.class);
Mockito.when(hook.getName()).thenReturn("ready");
- Mockito.when(hook.getPrimaryPaths()).thenReturn(List.of(primaryDir.toFile()));
+ Mockito.when(hook.getPrimaryPaths(Mockito.anyString())).thenReturn(List.of(primaryDir.toFile()));
Mockito.when(hook.getCompatPaths()).thenReturn(List.of(compatDir.toFile()));
initializationHooksRunner.run(hook);
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 490a51f8ee..6549114ce7 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -108,6 +108,7 @@ floci:
allow-private-jwt-targets: true
init-hooks:
+ dir: /etc/floci/init
shell-executable: /bin/sh
timeout-seconds: 5
shutdown-grace-period-seconds: 2