diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b0f2d9..8a51ffa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (UID/GID `10001`) by default. Existing bind mounts or volumes for `/app/data` that are owned by root must be writable by this user (or, in Kubernetes, use `securityContext.fsGroup: 10001`). Mounted configuration and image files must - be readable by this user. The default user can be changed. + be readable by this user. The default user can be changed. The image itself does not + require a writable home directory: GraalVM's native resource cache and the npm and pip + caches used for installing extensions live below the data directory. - **Breaking:** Client conditional headers (`If-None-Match`, `If-Modified-Since`) are no longer forwarded to HTTP image sources. Wolpi evaluates them after reading the source, so a conditional request may download the full source before returning `304`, including when the HTTP source cache diff --git a/Dockerfile b/Dockerfile index 7031a33..b6c2e58 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,8 +39,8 @@ ENV LD_PRELOAD="/usr/local/lib/libjemalloc.so" # Configure jemalloc to use background thread for purging dirty and muzzy pages after 5s ENV MALLOC_CONF="background_thread:true,dirty_decay_ms:5000,muzzy_decay_ms:5000" -ENV GRAALVM_URL="https://gds.oracle.com/download/graal/25/archive/graalvm-jdk-25.0.5_linux-x64_bin.tar.gz" -ARG GRAALVM_SHA256="2ae8b03dfcb0a5bbcb55ffd122e8ffee24e3afce04bccc82932789acd005d1e1" +ENV GRAALVM_URL="https://gds.oracle.com/download/graal/25/archive/graalvm-jdk-25.0.5.1_linux-x64_bin.tar.gz" +ARG GRAALVM_SHA256="b3505b8e8f73726885044820f7de593c7b0273c691286655cdb7ece2a23ad75a" RUN set -eux; \ curl --fail --show-error --location "${GRAALVM_URL}" \ --output /tmp/graalvm.tar.gz; \ @@ -82,7 +82,10 @@ RUN java -Djarmode=tools -jar /app.jar extract && \ rm -rf /app/app # Install the IIIF Image API validator +# The Truffle, npm and pip caches are instance-local and would be root-owned from this build step, +# drop them so the unprivileged runtime user can populate them itself. RUN wolpi install-validator && \ + rm -rf /app/data/.truffle /app/data/npm/.cache /app/data/pypi/.cache && \ mv /app/data /app/.data_preinstalled && \ mkdir -p /app/data diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 972f087..ec1ded4 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -18,7 +18,9 @@ You can specify a different configuration file location by either: Top-level configuration keys: - `data-directory`: Location where Wolpi stores extensions installed from packages; defaults to - `./data`. + `./data`. Wolpi also keeps its HTTP source cache, the native resources GraalVM extracts for the + extension runtime (`/.truffle`), and the npm and pip caches used to install + extensions (`/npm/.cache`, `/pypi/.cache`) below this directory. - `image-base-dir`: Fallback location for images if no resolving extension provides the asset; defaults to `./images`. diff --git a/src/main/java/dev/mdz/wolpi/config/WolpiEnvironmentPostProcessor.java b/src/main/java/dev/mdz/wolpi/config/WolpiEnvironmentPostProcessor.java index d1e07df..db1e5fa 100644 --- a/src/main/java/dev/mdz/wolpi/config/WolpiEnvironmentPostProcessor.java +++ b/src/main/java/dev/mdz/wolpi/config/WolpiEnvironmentPostProcessor.java @@ -3,6 +3,7 @@ import dev.mdz.wolpi.config.WolpiConfig.LogFormat; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; @@ -74,6 +75,8 @@ public void postProcessEnvironment(ConfigurableEnvironment environment, SpringAp } WolpiConfig config = bound.get(); + configureTruffleResourceCache(config); + CompositePropertySource src = new CompositePropertySource("wolpi-overrides"); src.addPropertySource(getLoggingOverrides(config)); @@ -90,6 +93,34 @@ public void postProcessEnvironment(ConfigurableEnvironment environment, SpringAp environment.getPropertySources().addFirst(src); } + /// Keep Truffle's extracted native resources inside the data directory. + /// + /// Truffle extracts its attach library into `$HOME/.cache` by default and silently falls back to + /// an interpreter-only runtime when that location is not writable, which slows down every + /// JavaScript and Python extension hook. Deployments without a writable home directory (e.g. the + /// container image running as an unprivileged user) would otherwise lose the optimized runtime. + /// + /// An explicitly configured `polyglot.engine.userResourceCache` always wins, so operators can + /// point it elsewhere. + private static void configureTruffleResourceCache(WolpiConfig config) { + String property = "polyglot.engine.userResourceCache"; + if (System.getProperty(property) != null) { + return; + } + Path cacheDir = config.dataDirectory().toAbsolutePath().normalize().resolve(".truffle"); + try { + Files.createDirectories(cacheDir); + } catch (IOException | RuntimeException e) { + // Read-only data directory: leave Truffle's default in place, it degrades gracefully. + return; + } + if (!Files.isWritable(cacheDir)) { + // Read-only cache directory, degrade gracefully. + return; + } + System.setProperty(property, cacheDir.toString()); + } + private @Nullable EnumerablePropertySource getExternalConfigSource(ConfigurableEnvironment env) { // Look for config file path in CLI args or environment variable String pathSpec = Stream.of(CONFIG_CLI_PROP, CONFIG_ENV_PROP) diff --git a/src/main/java/dev/mdz/wolpi/extension/NpmInstaller.java b/src/main/java/dev/mdz/wolpi/extension/NpmInstaller.java index b428a1a..c3472b0 100644 --- a/src/main/java/dev/mdz/wolpi/extension/NpmInstaller.java +++ b/src/main/java/dev/mdz/wolpi/extension/NpmInstaller.java @@ -151,7 +151,7 @@ public void installExtension( args.add(2, customTempConfig.toString()); } try { - CommandRunner.runCommand(npmPath, baseDir, processTimeout, args.toArray(String[]::new)); + CommandRunner.runCommand(npmPath, baseDir, processTimeout, npmEnvironment(), args.toArray(String[]::new)); } catch (IOException | InterruptedException e) { throw new PackageInstallException(e); } finally { @@ -179,7 +179,7 @@ public String installExtensionFromLocalDirectory(Path localPackageDir) "npm executable not found or configured, cannot install package in " + localPackageDir); } - log.info("Installing Python extension from {}", localPackageDir.toAbsolutePath()); + log.info("Installing JavaScript extension from {}", localPackageDir.toAbsolutePath()); if (!Files.isDirectory(localPackageDir) || !Files.isRegularFile(localPackageDir.resolve("package.json"))) { throw new PackageInstallException( "localPackageDir must exist and contain a package.json: " + localPackageDir); @@ -190,6 +190,7 @@ public String installExtensionFromLocalDirectory(Path localPackageDir) npmPath, baseDir, processTimeout, + npmEnvironment(), "install", "--install-links=false", "--no-audit", @@ -297,7 +298,7 @@ public boolean supportsPackageLiveReload() { return false; } try { - var version = CommandRunner.runCommand(npmPath, null, Duration.ofSeconds(10), "--version") + var version = CommandRunner.runCommand(npmPath, null, Duration.ofSeconds(10), npmEnvironment(), "--version") .trim(); int major = Integer.parseInt(version.split("\\.")[0]); return major >= 10; @@ -320,4 +321,13 @@ private void verifyInstalledPackage(String packageName) throws ExtensionLoadExce throw new ExtensionLoadException("Failed to verify installed package: " + packageName, cause); } } + + /// Environment for npm invocations. + /// + /// npm writes its cache and logs below `$HOME` by default, which does not exist (or is not + /// writable) for the unprivileged user in the container image. Keeping them inside the + /// installation directory means npm needs no home directory at all. + private Map npmEnvironment() { + return Map.of("npm_config_cache", baseDir.resolve(".cache").toString()); + } } diff --git a/src/main/java/dev/mdz/wolpi/extension/PyPiInstaller.java b/src/main/java/dev/mdz/wolpi/extension/PyPiInstaller.java index a3d3286..8ca4c50 100644 --- a/src/main/java/dev/mdz/wolpi/extension/PyPiInstaller.java +++ b/src/main/java/dev/mdz/wolpi/extension/PyPiInstaller.java @@ -382,6 +382,7 @@ Path ensureVenv(String packageName) throws PackageInstallException { pythonPath, baseDir, processTimeout, + pythonEnvironment(), "-m", "venv", venvPath.toAbsolutePath().toString()); @@ -404,8 +405,10 @@ private String runPip(Path venvPath, Map env, String... args) th cmd.add("-m"); cmd.add("pip"); cmd.addAll(Arrays.stream(args).filter(s -> !s.isBlank()).toList()); + Map pipEnv = new HashMap<>(pythonEnvironment()); + pipEnv.putAll(env); try { - return CommandRunner.runCommand(pythonInVenv, baseDir, processTimeout, env, cmd.toArray(new String[0])); + return CommandRunner.runCommand(pythonInVenv, baseDir, processTimeout, pipEnv, cmd.toArray(new String[0])); } catch (IOException | InterruptedException e) { throw new PackageInstallException(e); } @@ -443,4 +446,13 @@ private void verifyInstalledExtension(String packageName) throws ExtensionLoadEx public record EntryPoint(String module, String function) {} private record ParsedPackage(String name, String version) {} + + /// Environment for Python invocations. + /// + /// pip caches downloads below `$HOME` by default, which does not exist (or is not writable) for + /// the unprivileged user in the container image. Keeping the cache inside the installation + /// directory means pip and the GraalPy wheel builds it spawns need no home directory at all. + private Map pythonEnvironment() { + return Map.of("PIP_CACHE_DIR", baseDir.resolve(".cache").toString(), "PIP_DISABLE_PIP_VERSION_CHECK", "1"); + } }