Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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; \
Expand Down Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<data-directory>/.truffle`), and the npm and pip caches used to install
extensions (`<data-directory>/npm/.cache`, `<data-directory>/pypi/.cache`) below this directory.
- `image-base-dir`: Fallback location for images if no resolving extension provides the asset;
defaults to `./images`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand All @@ -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;
}
Comment thread
stefan-it marked this conversation as resolved.
Resolved
if (!Files.isWritable(cacheDir)) {
// Read-only cache directory, degrade gracefully.
return;
}
System.setProperty(property, cacheDir.toString());
}

private @Nullable EnumerablePropertySource<Object> getExternalConfigSource(ConfigurableEnvironment env) {
// Look for config file path in CLI args or environment variable
String pathSpec = Stream.of(CONFIG_CLI_PROP, CONFIG_ENV_PROP)
Expand Down
16 changes: 13 additions & 3 deletions src/main/java/dev/mdz/wolpi/extension/NpmInstaller.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand All @@ -190,6 +190,7 @@ public String installExtensionFromLocalDirectory(Path localPackageDir)
npmPath,
baseDir,
processTimeout,
npmEnvironment(),
"install",
"--install-links=false",
"--no-audit",
Expand Down Expand Up @@ -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;
Expand All @@ -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<String, String> npmEnvironment() {
return Map.of("npm_config_cache", baseDir.resolve(".cache").toString());
}
}
14 changes: 13 additions & 1 deletion src/main/java/dev/mdz/wolpi/extension/PyPiInstaller.java
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ Path ensureVenv(String packageName) throws PackageInstallException {
pythonPath,
baseDir,
processTimeout,
pythonEnvironment(),
"-m",
"venv",
venvPath.toAbsolutePath().toString());
Expand All @@ -404,8 +405,10 @@ private String runPip(Path venvPath, Map<String, String> env, String... args) th
cmd.add("-m");
cmd.add("pip");
cmd.addAll(Arrays.stream(args).filter(s -> !s.isBlank()).toList());
Map<String, String> 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);
}
Expand Down Expand Up @@ -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<String, String> pythonEnvironment() {
return Map.of("PIP_CACHE_DIR", baseDir.resolve(".cache").toString(), "PIP_DISABLE_PIP_VERSION_CHECK", "1");
}
}