Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

refactor(docker): consolidate JVM options and improve dynamic memory computation (#5933)

briosf90b1474877a
diff --git a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
index 1a8786bf1d..24f9bee709 100644
--- a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
+++ b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
@@ -202,7 +202,16 @@ public class ProcessExecutor {
UnoServerPool.UnoServerLease unoLease = null;
boolean useSemaphore = true;
List<String> commandToRun = command;
- if (shouldUseUnoServerPool(command)) {
+
+ boolean useUnoServerPool = shouldUseUnoServerPool(command);
+
+ if (useUnoServerPool) {
+ // Signal the on-demand manager to start unoserver if needed, then
+ // wait on the leased endpoint itself: probing every endpoint and
+ // leasing one afterwards could pick an endpoint that never became
+ // ready. A direct soffice command never signals: it does not call
+ // an endpoint, and its demand would wake a server nobody uses.
+ signalUnoServerDemand();
try {
unoLease = unoServerPool.acquireEndpoint(timeoutDuration, TimeUnit.MINUTES);
} catch (TimeoutException e) {
@@ -212,6 +221,12 @@ public class ProcessExecutor {
+ " minutes",
e);
}
+ if (!unoServerPool.waitForEndpoint(
+ unoLease.getEndpoint(), UNO_SERVER_READY_WAIT_SECONDS, TimeUnit.SECONDS)) {
+ log.warn(
+ "No local unoserver endpoint accepted connections within {}s; continuing",
+ UNO_SERVER_READY_WAIT_SECONDS);
+ }
commandToRun = applyUnoServerEndpoint(command, unoLease.getEndpoint());
useSemaphore = false;
}
@@ -228,6 +243,9 @@ public class ProcessExecutor {
if (workingDirectory != null) {
processBuilder.directory(workingDirectory);
}
+ if (useUnoServerPool) {
+ signalUnoServerDemand();
+ }
Process process = processBuilder.start();
// Read the error stream and standard output stream concurrently
@@ -287,8 +305,41 @@ public class ProcessExecutor {
errorReaderThread.start();
outputReaderThread.start();
- // Wait for the conversion process to complete
- boolean finished = process.waitFor(timeoutDuration, TimeUnit.MINUTES);
+ Thread unoHeartbeat = null;
+ if (useUnoServerPool) {
+ unoHeartbeat =
+ Thread.ofVirtual()
+ .unstarted(
+ () -> {
+ while (!Thread.currentThread().isInterrupted()
+ && process.isAlive()) {
+ try {
+ Thread.sleep(30_000);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ signalUnoServerDemand();
+ }
+ });
+ unoHeartbeat.start();
+ }
+
+ // Wait for the conversion process to complete. The heartbeat must be
+ // stopped on every exit path, and a cancelled request must not leave
+ // the child alive still refreshing demand.
+ boolean finished;
+ try {
+ finished = process.waitFor(timeoutDuration, TimeUnit.MINUTES);
+ } catch (InterruptedException e) {
+ process.descendants().forEach(ProcessHandle::destroyForcibly);
+ process.destroyForcibly();
+ throw e;
+ } finally {
+ if (unoHeartbeat != null) {
+ unoHeartbeat.interrupt();
+ }
+ }
if (!finished) {
// Kill the entire process tree (descendants first, then the process itself)
@@ -537,6 +588,32 @@ public class ProcessExecutor {
// For relative paths, trust that PATH resolution will work or fail appropriately
}
+ /**
+ * How long a conversion waits for a local unoserver endpoint to accept connections after
+ * signalling demand. The manager notices the demand file on its own schedule and then starts
+ * soffice, which takes a few seconds; the wait is bounded so a broken setup still reaches the
+ * soffice fallback quickly.
+ */
+ private static final long UNO_SERVER_READY_WAIT_SECONDS = 15;
+
+ /**
+ * Signal the on-demand unoserver manager that a conversion is needed. Writes the current epoch
+ * timestamp to /tmp/uno-last-used. The demand manager watches this file. Skips writing when
+ * configured purely with remoteunoserver endpoints.
+ */
+ private static void signalUnoServerDemand() {
+ if (unoServerPool != null && !unoServerPool.hasLocalEndpoints()) {
+ return;
+ }
+ try {
+ Path demandFile = Path.of("/tmp/uno-last-used");
+ String epoch = String.valueOf(System.currentTimeMillis() / 1000);
+ Files.writeString(demandFile, epoch);
+ } catch (IOException e) {
+ log.debug("Could not write unoserver demand file: {}", e.getMessage());
+ }
+ }
+
public enum Processes {
LIBRE_OFFICE,
PDFTOHTML,
diff --git a/app/common/src/main/java/stirling/software/common/util/UnoServerPool.java b/app/common/src/main/java/stirling/software/common/util/UnoServerPool.java
index 3863bd5310..2e0b0231df 100644
--- a/app/common/src/main/java/stirling/software/common/util/UnoServerPool.java
+++ b/app/common/src/main/java/stirling/software/common/util/UnoServerPool.java
@@ -1,5 +1,8 @@
package stirling.software.common.util;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -14,6 +17,9 @@ import stirling.software.common.model.ApplicationProperties;
public class UnoServerPool {
+ private static final long READY_PROBE_INTERVAL_MILLIS = 250;
+ private static final int READY_PROBE_CONNECT_TIMEOUT_MILLIS = 500;
+
private final List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints;
private final BlockingQueue<Integer> availableIndices;
@@ -35,6 +41,137 @@ public class UnoServerPool {
return endpoints.isEmpty();
}
+ public boolean hasLocalEndpoints() {
+ if (endpoints.isEmpty()) {
+ return true;
+ }
+ for (ApplicationProperties.ProcessExecutor.UnoServerEndpoint ep : endpoints) {
+ if (isLocalEndpoint(ep)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean isLocalEndpoint(
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint ep) {
+ if (ep == null) {
+ return true;
+ }
+ String loc = ep.getHostLocation();
+ if ("remote".equalsIgnoreCase(loc)) {
+ return false;
+ }
+ if ("local".equalsIgnoreCase(loc)) {
+ return true;
+ }
+ String host = ep.getHost();
+ if (host == null || host.isBlank()) {
+ return true;
+ }
+ host = host.trim().toLowerCase(Locale.ROOT);
+ return "127.0.0.1".equals(host) || "localhost".equals(host) || "::1".equals(host);
+ }
+
+ /**
+ * Waits until one local endpoint accepts a TCP connection, or the timeout passes. Returns true
+ * immediately for a remote-only pool, which has nothing to wake. Callers use this after
+ * signalling demand so the first conversion after an idle shutdown does not race the server
+ * that is still starting.
+ */
+ public boolean waitForLocalEndpoint(long timeout, TimeUnit unit) throws InterruptedException {
+ List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> locals = new ArrayList<>();
+ if (endpoints.isEmpty()) {
+ locals.add(defaultEndpoint());
+ } else {
+ for (ApplicationProperties.ProcessExecutor.UnoServerEndpoint endpoint : endpoints) {
+ if (isLocalEndpoint(endpoint)) {
+ locals.add(endpoint);
+ }
+ }
+ }
+ if (locals.isEmpty()) {
+ return true;
+ }
+
+ long deadline = System.nanoTime() + unit.toNanos(timeout);
+ while (true) {
+ for (ApplicationProperties.ProcessExecutor.UnoServerEndpoint endpoint : locals) {
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ return false;
+ }
+ if (canConnect(endpoint, remaining)) {
+ return true;
+ }
+ }
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ return false;
+ }
+ Thread.sleep(clampedSleepMillis(remaining));
+ }
+ }
+
+ /**
+ * Waits until the given endpoint accepts a TCP connection, or the timeout passes. Remote
+ * endpoints return true immediately. Callers that already hold a lease use this so the probe
+ * and the leased endpoint are the same one.
+ */
+ public boolean waitForEndpoint(
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint endpoint,
+ long timeout,
+ TimeUnit unit)
+ throws InterruptedException {
+ if (!isLocalEndpoint(endpoint)) {
+ return true;
+ }
+ long deadline = System.nanoTime() + unit.toNanos(timeout);
+ while (true) {
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ return false;
+ }
+ if (canConnect(endpoint, remaining)) {
+ return true;
+ }
+ remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ return false;
+ }
+ Thread.sleep(clampedSleepMillis(remaining));
+ }
+ }
+
+ /** Probe with the connect timeout clamped to the caller's remaining budget. */
+ private static boolean canConnect(
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint endpoint, long remainingNanos) {
+ if (endpoint == null || endpoint.getHost() == null) {
+ return false;
+ }
+ int connectTimeoutMillis =
+ (int)
+ Math.max(
+ 1,
+ Math.min(
+ READY_PROBE_CONNECT_TIMEOUT_MILLIS,
+ TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ try (Socket socket = new Socket()) {
+ socket.connect(
+ new InetSocketAddress(endpoint.getHost(), endpoint.getPort()),
+ connectTimeoutMillis);
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ private static long clampedSleepMillis(long remainingNanos) {
+ return Math.min(
+ READY_PROBE_INTERVAL_MILLIS,
+ Math.max(1, TimeUnit.NANOSECONDS.toMillis(remainingNanos)));
+ }
+
public UnoServerLease acquireEndpoint() throws InterruptedException {
if (endpoints.isEmpty()) {
return new UnoServerLease(defaultEndpoint(), null, this);
diff --git a/app/common/src/test/java/stirling/software/common/util/UnoServerPoolTest.java b/app/common/src/test/java/stirling/software/common/util/UnoServerPoolTest.java
index 06d1575ef5..d76208d353 100644
--- a/app/common/src/test/java/stirling/software/common/util/UnoServerPoolTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/UnoServerPoolTest.java
@@ -2,6 +2,7 @@ package stirling.software.common.util;
import static org.junit.jupiter.api.Assertions.*;
+import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -29,6 +30,115 @@ public class UnoServerPoolTest {
lease.close(); // Should not throw
}
+ @Test
+ void testWaitForLocalEndpointSkipsRemoteOnlyPools() throws InterruptedException {
+ List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints = new ArrayList<>();
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint remote =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ remote.setHost("unoserver1");
+ remote.setPort(2002);
+ remote.setHostLocation("remote");
+ endpoints.add(remote);
+ UnoServerPool pool = new UnoServerPool(endpoints);
+
+ assertTrue(
+ pool.waitForLocalEndpoint(1, TimeUnit.MILLISECONDS),
+ "A remote-only pool has no local endpoint to wake");
+ }
+
+ @Test
+ void testWaitForLocalEndpointTimesOutWhenNothingListens() throws Exception {
+ int closedPort;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ closedPort = socket.getLocalPort();
+ }
+ List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints = new ArrayList<>();
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint local =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ local.setHost("127.0.0.1");
+ local.setPort(closedPort);
+ local.setHostLocation("local");
+ endpoints.add(local);
+ UnoServerPool pool = new UnoServerPool(endpoints);
+
+ assertFalse(
+ pool.waitForLocalEndpoint(1, TimeUnit.MILLISECONDS),
+ "A closed local port must not report ready");
+ }
+
+ @Test
+ void testWaitForLocalEndpointSeesAListeningEndpoint() throws Exception {
+ try (ServerSocket listener = new ServerSocket(0)) {
+ List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints =
+ new ArrayList<>();
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint local =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ local.setHost("127.0.0.1");
+ local.setPort(listener.getLocalPort());
+ local.setHostLocation("local");
+ endpoints.add(local);
+ UnoServerPool pool = new UnoServerPool(endpoints);
+
+ assertTrue(
+ pool.waitForLocalEndpoint(1, TimeUnit.SECONDS),
+ "A listening local port reports ready");
+ }
+ }
+
+ @Test
+ void testWaitForEndpointProbesTheGivenEndpoint() throws Exception {
+ try (ServerSocket listener = new ServerSocket(0)) {
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint local =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ local.setHost("127.0.0.1");
+ local.setPort(listener.getLocalPort());
+ local.setHostLocation("local");
+ UnoServerPool pool = new UnoServerPool(List.of(local));
+
+ assertTrue(
+ pool.waitForEndpoint(local, 1, TimeUnit.SECONDS),
+ "The leased endpoint reports ready");
+ }
+ }
+
+ @Test
+ void testWaitForEndpointHonorsTheDeadline() throws Exception {
+ int closedPort;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ closedPort = socket.getLocalPort();
+ }
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint local =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ local.setHost("127.0.0.1");
+ local.setPort(closedPort);
+ local.setHostLocation("local");
+ UnoServerPool pool = new UnoServerPool(List.of(local));
+
+ long started = System.nanoTime();
+ assertFalse(pool.waitForEndpoint(local, 50, TimeUnit.MILLISECONDS));
+ long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
+ assertTrue(
+ elapsedMillis < 200,
+ "A 50ms budget must clamp the sleep interval, took " + elapsedMillis + "ms");
+ }
+
+ @Test
+ void testWaitForEndpointClampsTheConnectTimeout() throws Exception {
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint unreachable =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ unreachable.setHost("192.0.2.1");
+ unreachable.setPort(2002);
+ unreachable.setHostLocation("local");
+ UnoServerPool pool = new UnoServerPool(List.of(unreachable));
+
+ long started = System.nanoTime();
+ assertFalse(pool.waitForEndpoint(unreachable, 50, TimeUnit.MILLISECONDS));
+ long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
+ assertTrue(
+ elapsedMillis < 300,
+ "The connect probe must clamp to the 50ms budget, took " + elapsedMillis + "ms");
+ }
+
@Test
void testSingleEndpointAcquireRelease() throws InterruptedException {
List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints =
@@ -259,6 +369,31 @@ public class UnoServerPoolTest {
}
}
+ @Test
+ void testHasLocalEndpoints() {
+ // Empty pool defaults to local
+ assertTrue(new UnoServerPool(Collections.emptyList()).hasLocalEndpoints());
+
+ // Pool with 127.0.0.1 (default auto) is local
+ assertTrue(new UnoServerPool(createEndpoints(1)).hasLocalEndpoints());
+
+ // Pool with explicit remote location is not local
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint remoteEp =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ remoteEp.setHost("unoserver1");
+ remoteEp.setHostLocation("remote");
+ UnoServerPool remotePool = new UnoServerPool(Collections.singletonList(remoteEp));
+ assertFalse(remotePool.hasLocalEndpoints());
+
+ // Pool with explicit local location is local
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint localEp =
+ new ApplicationProperties.ProcessExecutor.UnoServerEndpoint();
+ localEp.setHost("unoserver1");
+ localEp.setHostLocation("local");
+ UnoServerPool localPool = new UnoServerPool(Collections.singletonList(localEp));
+ assertTrue(localPool.hasLocalEndpoints());
+ }
+
private List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> createEndpoints(
int count) {
List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> endpoints = new ArrayList<>();
diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.properties
index 9648f6dab2..86e35ec66d 100644
--- a/app/core/src/main/resources/application.properties
+++ b/app/core/src/main/resources/application.properties
@@ -65,6 +65,7 @@ spring.devtools.restart.exclude=stirling.software.proprietary.security/**
spring.web.resources.mime-mappings.webmanifest=application/manifest+json
spring.mvc.async.request-timeout=${SYSTEM_CONNECTIONTIMEOUTMILLISECONDS:1200000}
server.jetty.max-http-request-header-size=32768
+server.jetty.connection-idle-timeout=PT5M
spring.datasource.url=jdbc:h2:file:./configs/stirling-pdf-DB-2.3.232;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL
spring.datasource.driver-class-name=org.h2.Driver
diff --git a/docker/backend/Dockerfile b/docker/backend/Dockerfile
index cd196878b6..cbacadfb89 100644
--- a/docker/backend/Dockerfile
+++ b/docker/backend/Dockerfile
@@ -111,9 +111,7 @@ RUN echo "${VERSION_TAG:-dev}" > /etc/stirling_version
ENV VERSION_TAG=$VERSION_TAG \
FORMDETECTION_PREINSTALLEDMODELDIR="/opt/stirling/preinstalled-models" \
STIRLING_AOT_ENABLE="false" \
- STIRLING_JVM_PROFILE="balanced" \
- _JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
- _JVM_OPTS_PERFORMANCE="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+AlwaysPreTouch -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
+ _JVM_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1PeriodicGCInterval=10000 -XX:G1PeriodicGCSystemLoadThreshold=0.0 -XX:+G1PeriodicGCInvokesConcurrent -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+ExplicitGCInvokesConcurrent -XX:ReservedCodeCacheSize=96m -Xss256k -XX:CICompilerCount=2 -Djdk.virtualThreadScheduler.maxPoolSize=4 -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
diff --git a/docker/embedded/Dockerfile b/docker/embedded/Dockerfile
index 3550fb03e0..3bc127b29b 100644
--- a/docker/embedded/Dockerfile
+++ b/docker/embedded/Dockerfile
@@ -147,9 +147,7 @@ RUN echo "${VERSION_TAG:-dev}" > /etc/stirling_version
ENV VERSION_TAG=$VERSION_TAG \
FORMDETECTION_PREINSTALLEDMODELDIR="/opt/stirling/preinstalled-models" \
STIRLING_AOT_ENABLE="false" \
- STIRLING_JVM_PROFILE="balanced" \
- _JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
- _JVM_OPTS_PERFORMANCE="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+AlwaysPreTouch -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
+ _JVM_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1PeriodicGCInterval=10000 -XX:G1PeriodicGCSystemLoadThreshold=0.0 -XX:+G1PeriodicGCInvokesConcurrent -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+ExplicitGCInvokesConcurrent -XX:ReservedCodeCacheSize=96m -Xss256k -XX:CICompilerCount=2 -Djdk.virtualThreadScheduler.maxPoolSize=4 -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
diff --git a/docker/embedded/Dockerfile.fat b/docker/embedded/Dockerfile.fat
index d25abbe92f..de98ea1c95 100644
--- a/docker/embedded/Dockerfile.fat
+++ b/docker/embedded/Dockerfile.fat
@@ -164,9 +164,7 @@ RUN echo "${VERSION_TAG:-dev}" > /etc/stirling_version
ENV VERSION_TAG=$VERSION_TAG \
FORMDETECTION_PREINSTALLEDMODELDIR="/opt/stirling/preinstalled-models" \
STIRLING_AOT_ENABLE="false" \
- STIRLING_JVM_PROFILE="balanced" \
- _JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
- _JVM_OPTS_PERFORMANCE="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+AlwaysPreTouch -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
+ _JVM_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=adaptive -XX:ShenandoahUncommitDelay=1000 -XX:ShenandoahGuaranteedYoungGCInterval=10000 -XX:ShenandoahGuaranteedOldGCInterval=30000 -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+ExplicitGCInvokesConcurrent -XX:ReservedCodeCacheSize=96m -Xss256k -XX:CICompilerCount=2 -Djdk.virtualThreadScheduler.maxPoolSize=4 -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
diff --git a/docker/embedded/Dockerfile.ultra-lite b/docker/embedded/Dockerfile.ultra-lite
index 6c7a38f4e0..2c669d5c7e 100644
--- a/docker/embedded/Dockerfile.ultra-lite
+++ b/docker/embedded/Dockerfile.ultra-lite
@@ -88,9 +88,7 @@ LABEL org.opencontainers.image.title="Stirling-PDF Ultra-Lite" \
# are computed dynamically by init-without-ocr.sh based on container memory limits.
ENV VERSION_TAG=$VERSION_TAG \
STIRLING_AOT_ENABLE="false" \
- STIRLING_JVM_PROFILE="balanced" \
- _JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
- _JVM_OPTS_PERFORMANCE="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+AlwaysPreTouch -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
+ _JVM_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=adaptive -XX:ShenandoahUncommitDelay=1000 -XX:ShenandoahGuaranteedYoungGCInterval=10000 -XX:ShenandoahGuaranteedOldGCInterval=30000 -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+ExplicitGCInvokesConcurrent -XX:ReservedCodeCacheSize=96m -Xss256k -XX:CICompilerCount=2 -Djdk.virtualThreadScheduler.maxPoolSize=4 -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
diff --git a/docker/embedded/compose/README-remote-uno.md b/docker/embedded/compose/README-remote-uno.md
index 45a75b5262..bd4954db99 100644
--- a/docker/embedded/compose/README-remote-uno.md
+++ b/docker/embedded/compose/README-remote-uno.md
@@ -166,6 +166,14 @@ PROCESS_EXECUTOR_AUTO_UNO_SERVER: "false"
- ❌ Slightly higher network overhead
- ❌ More complex configuration
+## Idle Shutdown
+
+Remote UNO servers must keep `UNOSERVER_IDLE_TIMEOUT_SECONDS=0` (the image
+default). A positive value stops the server after that many idle seconds and
+only restarts it when something writes a fresh timestamp to
+`/tmp/uno-last-used`; the Stirling container writes that file only for its own
+local endpoints, so an idle-stopped remote server has no wake source.
+
## Advanced Configuration
### HTTPS UNO Servers
diff --git a/docker/embedded/compose/docker-compose-latest-fat-endpoints-disabled.yml b/docker/embedded/compose/docker-compose-latest-fat-endpoints-disabled.yml
index c1d2360b53..50c311241b 100644
--- a/docker/embedded/compose/docker-compose-latest-fat-endpoints-disabled.yml
+++ b/docker/embedded/compose/docker-compose-latest-fat-endpoints-disabled.yml
@@ -25,8 +25,8 @@ services:
environment:
DISABLE_ADDITIONAL_FEATURES: "false"
SECURITY_ENABLELOGIN: "false"
- # STIRLING_JVM_PROFILE: "balanced" # Options: balanced (G1GC, default), performance (Shenandoah)
- # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active profile
+ # JAVA_BASE_OPTS: "" # Full JVM flag override (default comes from the image _JVM_OPTS)
+ # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active options
PUID: 1002
PGID: 1002
UMASK: "022"
diff --git a/docker/embedded/compose/docker-compose-latest-fat-security.yml b/docker/embedded/compose/docker-compose-latest-fat-security.yml
index 7efa65a718..6da289429c 100644
--- a/docker/embedded/compose/docker-compose-latest-fat-security.yml
+++ b/docker/embedded/compose/docker-compose-latest-fat-security.yml
@@ -24,8 +24,8 @@ services:
environment:
DISABLE_ADDITIONAL_FEATURES: "false"
SECURITY_ENABLELOGIN: "false"
- # STIRLING_JVM_PROFILE: "balanced" # Options: balanced (G1GC, default), performance (Shenandoah)
- # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active profile
+ # JAVA_BASE_OPTS: "" # Full JVM flag override (default comes from the image _JVM_OPTS)
+ # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active options
PUID: 1002
PGID: 1002
UMASK: "022"
diff --git a/docker/embedded/compose/docker-compose-latest-security-remote-uno.yml b/docker/embedded/compose/docker-compose-latest-security-remote-uno.yml
index 4f57adfa49..71abe71c4e 100644
--- a/docker/embedded/compose/docker-compose-latest-security-remote-uno.yml
+++ b/docker/embedded/compose/docker-compose-latest-security-remote-uno.yml
@@ -33,8 +33,8 @@ services:
PROCESS_EXECUTOR_UNO_SERVER_ENDPOINTS_1_PROTOCOL: "http"
# Session limit should match endpoint count for optimal concurrency
PROCESS_EXECUTOR_SESSION_LIMIT_LIBRE_OFFICE_SESSION_LIMIT: "2"
- # STIRLING_JVM_PROFILE: "balanced" # Options: balanced (G1GC, default), performance (Shenandoah)
- # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active profile
+ # JAVA_BASE_OPTS: "" # Full JVM flag override (default comes from the image _JVM_OPTS)
+ # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active options
PUID: 1002
PGID: 1002
UMASK: "022"
diff --git a/docker/embedded/compose/docker-compose-latest-security.yml b/docker/embedded/compose/docker-compose-latest-security.yml
index 42f9946dc0..ebc214b79c 100644
--- a/docker/embedded/compose/docker-compose-latest-security.yml
+++ b/docker/embedded/compose/docker-compose-latest-security.yml
@@ -21,8 +21,8 @@ services:
SECURITY_ENABLELOGIN: "false"
PROCESS_EXECUTOR_AUTO_UNO_SERVER: "true"
PROCESS_EXECUTOR_SESSION_LIMIT_LIBRE_OFFICE_SESSION_LIMIT: "1"
- # STIRLING_JVM_PROFILE: "balanced" # Options: balanced (G1GC, default), performance (Shenandoah)
- # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active profile
+ # JAVA_BASE_OPTS: "" # Full JVM flag override (default comes from the image _JVM_OPTS)
+ # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active options
PUID: 1002
PGID: 1002
UMASK: "022"
diff --git a/docker/embedded/compose/docker-compose-latest-ultra-lite.yml b/docker/embedded/compose/docker-compose-latest-ultra-lite.yml
index 11174d1064..a3c0ea25b0 100644
--- a/docker/embedded/compose/docker-compose-latest-ultra-lite.yml
+++ b/docker/embedded/compose/docker-compose-latest-ultra-lite.yml
@@ -21,8 +21,8 @@ services:
- ../../../stirling/latest/logs:/logs:rw
environment:
SECURITY_ENABLELOGIN: "false"
- # STIRLING_JVM_PROFILE: "balanced" # Options: balanced (G1GC, default), performance (Shenandoah)
- # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active profile
+ # JAVA_BASE_OPTS: "" # Full JVM flag override (default comes from the image _JVM_OPTS)
+ # JAVA_CUSTOM_OPTS: "" # Additional JVM flags appended to the active options
SYSTEM_DEFAULTLOCALE: en-US
UI_APPNAME: Stirling-PDF-Ultra-lite
UI_HOMEDESCRIPTION: Demo site for Stirling-PDF-Ultra-lite Latest
diff --git a/docker/unoserver/Dockerfile b/docker/unoserver/Dockerfile
index 3667c4bf5a..11dff0f129 100644
--- a/docker/unoserver/Dockerfile
+++ b/docker/unoserver/Dockerfile
@@ -7,6 +7,10 @@ ARG UNOSERVER_VERSION=3.7
# ~120 MB of CJK fonts — opt-in.
ARG INSTALL_CJK_FONTS=false
+# UNOSERVER_IDLE_TIMEOUT_SECONDS=0 keeps idle shutdown off. A positive value only
+# works when something sharing /tmp/uno-last-used writes a fresh timestamp (the
+# embedded Stirling container does); a standalone unoserver has no wake source
+# and would stay stopped while still reporting healthy.
ENV DEBIAN_FRONTEND=noninteractive \
LANG=C.UTF-8 \
LC_ALL=C.UTF-8 \
@@ -15,7 +19,14 @@ ENV DEBIAN_FRONTEND=noninteractive \
UNOSERVER_INTERFACE=0.0.0.0 \
UNOSERVER_CONVERSION_TIMEOUT=1800 \
UNOSERVER_RECYCLE_INTERVAL_SECONDS=0 \
- UNOSERVER_PROFILE_DIR=/var/lib/unoserver/profile
+ UNOSERVER_IDLE_TIMEOUT_SECONDS=0 \
+ UNOSERVER_PROFILE_DIR=/var/lib/unoserver/profile \
+ SAL_USE_VCLPLUGIN=svp \
+ SAL_DISABLE_PRINTERLIST=1 \
+ OOO_FORCE_DESKTOP=none \
+ SAL_LOG="-WARN-INFO" \
+ MALLOC_ARENA_MAX=2 \
+ DBUS_SESSION_BUS_ADDRESS=/dev/null
RUN set -eux; \
apt-get update; \
diff --git a/docker/unoserver/entrypoint.sh b/docker/unoserver/entrypoint.sh
index bf1b6dbc3e..6fea01a6bc 100644
--- a/docker/unoserver/entrypoint.sh
+++ b/docker/unoserver/entrypoint.sh
@@ -8,6 +8,15 @@ CONVERSION_TIMEOUT="${UNOSERVER_CONVERSION_TIMEOUT:-1800}"
RECYCLE_INTERVAL_SECONDS="${UNOSERVER_RECYCLE_INTERVAL_SECONDS:-0}"
RECYCLE_INTERVAL_FLOOR=60
PROFILE_DIR="${UNOSERVER_PROFILE_DIR:-/var/lib/unoserver/profile}"
+IDLE_TIMEOUT="${UNOSERVER_IDLE_TIMEOUT_SECONDS:-0}"
+
+# ---------- LibreOffice memory-reduction environment ----------
+export SAL_USE_VCLPLUGIN=svp # Null rendering plugin (~40 MB savings)
+export SAL_DISABLE_PRINTERLIST=1 # Skip printer enumeration
+export OOO_FORCE_DESKTOP=none # No desktop frame
+export SAL_LOG="-WARN-INFO" # Minimal logging
+export MALLOC_ARENA_MAX=2 # Limit glibc arena fragmentation (20-80 MB savings)
+export DBUS_SESSION_BUS_ADDRESS=/dev/null
log() { printf '%s %s\n' "[unoserver-entrypoint]" "$*" >&2; }
@@ -15,6 +24,7 @@ case "$PORT" in ''|*[!0-9]*) log "Invalid UNOSERVER_PORT='$PORT'"; exit 64 ;; es
case "$UNO_PORT" in ''|*[!0-9]*) log "Invalid UNOSERVER_UNO_PORT='$UNO_PORT'"; exit 64 ;; esac
case "$CONVERSION_TIMEOUT" in ''|*[!0-9]*) log "Invalid UNOSERVER_CONVERSION_TIMEOUT='$CONVERSION_TIMEOUT'"; exit 64 ;; esac
case "$RECYCLE_INTERVAL_SECONDS" in ''|*[!0-9]*) log "Invalid UNOSERVER_RECYCLE_INTERVAL_SECONDS='$RECYCLE_INTERVAL_SECONDS'"; exit 64 ;; esac
+case "$IDLE_TIMEOUT" in ''|*[!0-9]*) log "Invalid UNOSERVER_IDLE_TIMEOUT_SECONDS='$IDLE_TIMEOUT'"; exit 64 ;; esac
mkdir -p "$PROFILE_DIR"
@@ -39,63 +49,136 @@ cleanup() {
if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
kill -TERM "$XVFB_PID" 2>/dev/null || true
fi
+ rm -f /tmp/uno-idle-state 2>/dev/null || true
}
trap cleanup TERM INT EXIT
start_unoserver() {
+ rm -f /tmp/uno-idle-state 2>/dev/null || true
log "Starting unoserver on ${INTERFACE}:${PORT} (uno-port ${UNO_PORT}, timeout ${CONVERSION_TIMEOUT}s, profile ${PROFILE_DIR})"
# Pass --user-installation as a plain path; unoserver 3.6 wraps it itself
# and crashes if pre-wrapped as a file:// URI.
+ local demand_file="/tmp/uno-last-used"
unoserver \
--interface "$INTERFACE" \
--port "$PORT" \
--uno-port "$UNO_PORT" \
--user-installation "${PROFILE_DIR}" \
--conversion-timeout "$CONVERSION_TIMEOUT" \
- 2> >(grep --line-buffered -v "POST /RPC2" >&2) \
+ 2> >(while read -r line; do
+ if [[ "$line" == *"POST /RPC2"* ]]; then
+ date +%s > "$demand_file" 2>/dev/null || true
+ else
+ printf '%s\n' "$line" >&2
+ fi
+ done) \
&
UNOSERVER_PID=$!
}
# Wall-clock recycle to bound LibreOffice memory growth. wait -n is unreliable
# here because the unoserver job is wrapped in a process substitution.
+# Also supports idle-shutdown when IDLE_TIMEOUT > 0.
recycle_supervisor() {
- if [ "$RECYCLE_INTERVAL_SECONDS" -le 0 ]; then
- log "Recycle disabled (UNOSERVER_RECYCLE_INTERVAL_SECONDS=0)"
+ if [ "$RECYCLE_INTERVAL_SECONDS" -le 0 ] && [ "$IDLE_TIMEOUT" -le 0 ]; then
+ log "Recycle disabled, idle shutdown disabled"
wait "$UNOSERVER_PID"
return $?
fi
- local interval="$RECYCLE_INTERVAL_SECONDS"
- if [ "$interval" -lt "$RECYCLE_INTERVAL_FLOOR" ]; then
- log "Clamping recycle interval ${interval}s up to floor ${RECYCLE_INTERVAL_FLOOR}s"
- interval="$RECYCLE_INTERVAL_FLOOR"
+
+ local recycle_interval=0
+ if [ "$RECYCLE_INTERVAL_SECONDS" -gt 0 ]; then
+ recycle_interval="$RECYCLE_INTERVAL_SECONDS"
+ if [ "$recycle_interval" -lt "$RECYCLE_INTERVAL_FLOOR" ]; then
+ log "Clamping recycle interval ${recycle_interval}s up to floor ${RECYCLE_INTERVAL_FLOOR}s"
+ recycle_interval="$RECYCLE_INTERVAL_FLOOR"
+ fi
+ log "Recycle enabled: restart every ${recycle_interval}s"
+ fi
+
+ if [ "$IDLE_TIMEOUT" -gt 0 ]; then
+ log "Idle shutdown enabled: stop after ${IDLE_TIMEOUT}s of inactivity"
+ log "Wake source required: only a writer sharing /tmp/uno-last-used can restart it;"
+ log "keep UNOSERVER_IDLE_TIMEOUT_SECONDS=0 for standalone or remote-unoserver setups"
fi
- log "Recycle enabled: restart every ${interval}s"
+
+ # Track last activity via demand file (Java writes to this)
+ local demand_file="/tmp/uno-last-used"
+ # Mark as active at startup
+ date +%s > "$demand_file" 2>/dev/null || true
+
+ local elapsed=0
while true; do
- local elapsed=0
- while [ "$elapsed" -lt "$interval" ]; do
- if ! kill -0 "$UNOSERVER_PID" 2>/dev/null; then
- wait "$UNOSERVER_PID"
- local rc=$?
- log "unoserver exited on its own (rc=$rc); not recycling"
- return "$rc"
+ if ! kill -0 "$UNOSERVER_PID" 2>/dev/null; then
+ wait "$UNOSERVER_PID"
+ local rc=$?
+ log "unoserver exited on its own (rc=$rc)"
+ return "$rc"
+ fi
+
+ sleep 1
+ elapsed=$((elapsed + 1))
+
+ # Idle shutdown check
+ if [ "$IDLE_TIMEOUT" -gt 0 ] && [ -f "$demand_file" ]; then
+ local last_used
+ last_used=$(cat "$demand_file" 2>/dev/null || echo "0")
+ local now
+ now=$(date +%s)
+ local idle_secs=$(( now - last_used ))
+ if [ "$idle_secs" -ge "$IDLE_TIMEOUT" ]; then
+ log "Idle for ${idle_secs}s (timeout=${IDLE_TIMEOUT}s), shutting down unoserver"
+ pkill -TERM -P "$UNOSERVER_PID" 2>/dev/null || true
+ kill -TERM "$UNOSERVER_PID" 2>/dev/null || true
+ for _ in 1 2 3 4 5; do
+ kill -0 "$UNOSERVER_PID" 2>/dev/null || break
+ sleep 1
+ done
+ pkill -KILL -P "$UNOSERVER_PID" 2>/dev/null || true
+ kill -KILL "$UNOSERVER_PID" 2>/dev/null || true
+ wait "$UNOSERVER_PID" 2>/dev/null || true
+ rm -rf "${PROFILE_DIR:?}"/* 2>/dev/null || true
+ touch /tmp/uno-idle-state 2>/dev/null || true
+ log "unoserver stopped due to idle timeout, waiting for next demand"
+
+ # Wait for demand (poll the demand file for a fresh timestamp)
+ while true; do
+ if [ -f "$demand_file" ]; then
+ local demand_ts
+ demand_ts=$(cat "$demand_file" 2>/dev/null || echo "0")
+ if [ "$demand_ts" -gt "$now" ] 2>/dev/null; then
+ log "Demand detected, restarting unoserver"
+ rm -f /tmp/uno-idle-state 2>/dev/null || true
+ start_unoserver
+ break
+ fi
+ fi
+ sleep 2
+ done
+ elapsed=0
+ continue
fi
- sleep 1
- elapsed=$((elapsed + 1))
- done
- log "Recycling unoserver (pid ${UNOSERVER_PID})"
- pkill -TERM -P "$UNOSERVER_PID" 2>/dev/null || true
- kill -TERM "$UNOSERVER_PID" 2>/dev/null || true
- for _ in 1 2 3 4 5; do
- kill -0 "$UNOSERVER_PID" 2>/dev/null || break
- sleep 1
- done
- pkill -KILL -P "$UNOSERVER_PID" 2>/dev/null || true
- kill -KILL "$UNOSERVER_PID" 2>/dev/null || true
- wait "$UNOSERVER_PID" 2>/dev/null || true
- rm -rf "${PROFILE_DIR:?}"/* 2>/dev/null || true
- start_unoserver
- log "unoserver restarted (pid ${UNOSERVER_PID})"
+ fi
+
+ # Recycle check
+ if [ "$recycle_interval" -gt 0 ] && [ "$elapsed" -ge "$recycle_interval" ]; then
+ log "Recycling unoserver (pid ${UNOSERVER_PID})"
+ pkill -TERM -P "$UNOSERVER_PID" 2>/dev/null || true
+ kill -TERM "$UNOSERVER_PID" 2>/dev/null || true
+ for _ in 1 2 3 4 5; do
+ kill -0 "$UNOSERVER_PID" 2>/dev/null || break
+ sleep 1
+ done
+ pkill -KILL -P "$UNOSERVER_PID" 2>/dev/null || true
+ kill -KILL "$UNOSERVER_PID" 2>/dev/null || true
+ wait "$UNOSERVER_PID" 2>/dev/null || true
+ rm -rf "${PROFILE_DIR:?}"/* 2>/dev/null || true
+ start_unoserver
+ log "unoserver restarted (pid ${UNOSERVER_PID})"
+ elapsed=0
+ # Mark as active after recycle
+ date +%s > "$demand_file" 2>/dev/null || true
+ fi
done
}
diff --git a/docker/unoserver/healthcheck.sh b/docker/unoserver/healthcheck.sh
index 8a48d2cd0c..add0c71c83 100644
--- a/docker/unoserver/healthcheck.sh
+++ b/docker/unoserver/healthcheck.sh
@@ -4,6 +4,11 @@ set -eu
PORT="${UNOSERVER_PORT:-2003}"
+if [ -f /tmp/uno-idle-state ]; then
+ echo "Idle (intentional)"
+ exit 0
+fi
+
if command -v unoping >/dev/null 2>&1; then
unoping --host 127.0.0.1 --port "$PORT" >/dev/null 2>&1
exit $?
diff --git a/scripts/init-without-ocr.sh b/scripts/init-without-ocr.sh
index 88a10ffa28..f855590c29 100755
--- a/scripts/init-without-ocr.sh
+++ b/scripts/init-without-ocr.sh
@@ -15,6 +15,63 @@ if [ -d /scripts ] && [[ ":${PATH}:" != *":/scripts:"* ]]; then
export PATH="/scripts:${PATH}"
fi
+# === Shared environment setup ===
+# Lives here so images that call init-without-ocr.sh directly (e.g. ultra-lite)
+# get the same environment as images that go through init.sh first.
+
+_append_env_path() {
+ local target="$1" current="$2"
+ if [ -d "$target" ] && [[ ":${current}:" != *":${target}:"* ]]; then
+ [ -n "$current" ] && printf '%s' "${target}:${current}" || printf '%s' "${target}"
+ else
+ printf '%s' "$current"
+ fi
+}
+
+_python_site_dir() {
+ local venv_dir="$1" python_bin="$1/bin/python" py_tag
+ if [ -x "$python_bin" ]; then
+ if py_tag="$("$python_bin" -c 'import sys; print(f"python{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" \
+ && [ -n "$py_tag" ] && [ -d "$venv_dir/lib/$py_tag/site-packages" ]; then
+ printf '%s' "$venv_dir/lib/$py_tag/site-packages"
+ fi
+ fi
+}
+
+# LD_LIBRARY_PATH: arch-specific system libs + LibreOffice
+case "$(uname -m)" in
+ x86_64) [ -d /usr/lib/x86_64-linux-gnu ] && export LD_LIBRARY_PATH="/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ;;
+ aarch64) [ -d /usr/lib/aarch64-linux-gnu ] && export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ;;
+esac
+[ -d /usr/lib/libreoffice/program ] && export LD_LIBRARY_PATH="/usr/lib/libreoffice/program${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
+
+# Reduce soffice.bin RSS by avoiding unnecessary subsystems.
+export SAL_USE_VCLPLUGIN=svp # Null rendering plugin — avoids loading X11 toolkit (~40 MB)
+export SAL_DISABLE_PRINTERLIST=1 # Skip printer enumeration
+export OOO_FORCE_DESKTOP=none # No desktop frame
+export SAL_LOG="-WARN-INFO" # Minimal logging
+export MALLOC_ARENA_MAX=2 # Limit glibc arena fragmentation (saves 20-80 MB RSS)
+export DBUS_SESSION_BUS_ADDRESS=/dev/null # Avoid D-Bus overhead
+
+# Python venv PATH + PYTHONPATH
+for _venv_bin in /opt/venv/bin /opt/unoserver-venv/bin; do
+ PATH="$(_append_env_path "$_venv_bin" "$PATH")"
+done
+export PATH
+unset _venv_bin
+
+_py_entries=()
+for _venv in /opt/venv /opt/unoserver-venv; do
+ [ -d "$_venv" ] || continue
+ _site="$(_python_site_dir "$_venv")"
+ [ -n "${_site:-}" ] && _py_entries+=("$_site")
+done
+if [ ${#_py_entries[@]} -gt 0 ]; then
+ PYTHONPATH="$(IFS=:; printf '%s' "${_py_entries[*]}")${PYTHONPATH:+:$PYTHONPATH}"
+ export PYTHONPATH
+fi
+unset _venv _site _py_entries
+
if [ -x /scripts/stirling-diagnostics.sh ]; then
mkdir -p /usr/local/bin
ln -sf /scripts/stirling-diagnostics.sh /usr/local/bin/diagnostics
@@ -63,11 +120,22 @@ cleanup() {
wait "$AOT_GEN_PID" 2>/dev/null || true
fi
+ # Kill on-demand manager if running
+ if [ -n "${DEMAND_MANAGER_PID:-}" ] && kill -0 "$DEMAND_MANAGER_PID" 2>/dev/null; then
+ kill -TERM "$DEMAND_MANAGER_PID" 2>/dev/null || true
+ wait "$DEMAND_MANAGER_PID" 2>/dev/null || true
+ fi
+
# Signal unoserver instances to shut down
for pid in "${UNOSERVER_PIDS[@]:-}"; do
[ -n "$pid" ] && kill -TERM "$pid" 2>/dev/null || true
done
+ # Stop Xvfb if running (on-demand mode)
+ if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
+ kill -TERM "$XVFB_PID" 2>/dev/null || true
+ fi
+
# Signal Java to shut down gracefully, Spring Boot handles SIGTERM cleanly
if [ -n "${JAVA_PID:-}" ] && kill -0 "$JAVA_PID" 2>/dev/null; then
kill -TERM "$JAVA_PID" 2>/dev/null || true
@@ -294,6 +362,29 @@ start_unoserver_instance() {
LAST_UNOSERVER_PID=$!
}
+# Stop an unoserver instance and its soffice children. Child PIDs are captured
+# before signalling the parent so the PPID relationship is still visible; the
+# saved PIDs get SIGKILL after the grace period because the parent may already
+# have exited and reparented them.
+stop_unoserver_instance() {
+ local pid=${1:-}
+ if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then
+ return 0
+ fi
+ log "Stopping unoserver pid ${pid}"
+ local child_pids
+ child_pids=$(pgrep -P "$pid" 2>/dev/null || true)
+ pkill -TERM -P "$pid" 2>/dev/null || true
+ kill -TERM "$pid" 2>/dev/null || true
+ sleep 3
+ if [ -n "$child_pids" ]; then
+ # The expansion carries several PIDs on purpose.
+ # shellcheck disable=SC2086
+ kill -KILL $child_pids 2>/dev/null || true
+ fi
+ kill -KILL "$pid" 2>/dev/null || true
+}
+
start_unoserver_watchdog() {
local interval=${UNO_SERVER_HEALTH_INTERVAL:-30}
case "$interval" in
@@ -303,9 +394,9 @@ start_unoserver_watchdog() {
while true; do
local i=0
while [ "$i" -lt "${#UNOSERVER_PIDS[@]}" ]; do
- local pid=${UNOSERVER_PIDS[$i]}
- local port=${UNOSERVER_PORTS[$i]}
- local uno_port=${UNOSERVER_UNO_PORTS[$i]}
+ local pid=${UNOSERVER_PIDS[i]}
+ local port=${UNOSERVER_PORTS[i]}
+ local uno_port=${UNOSERVER_UNO_PORTS[i]}
local needs_restart=false
# Check PID and Health
@@ -318,24 +409,9 @@ start_unoserver_watchdog() {
if [ "$needs_restart" = true ]; then
log "Restarting unoserver on 127.0.0.1:${port} (uno-port ${uno_port})"
- # Kill the old process and its children (soffice) if it exists.
- # Capture child PIDs first, then send TERM to children before parent
- # so the PPID relationship is still visible. After sleep, use the
- # saved PIDs for SIGKILL since the parent may have already exited
- # and children would be reparented to init.
- if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
- local child_pids
- child_pids=$(pgrep -P "$pid" 2>/dev/null || true)
- pkill -TERM -P "$pid" 2>/dev/null || true
- kill -TERM "$pid" 2>/dev/null || true
- sleep 3
- if [ -n "$child_pids" ]; then
- kill -KILL $child_pids 2>/dev/null || true
- fi
- kill -KILL "$pid" 2>/dev/null || true
- fi
+ stop_unoserver_instance "$pid"
start_unoserver_instance "$port" "$uno_port"
- UNOSERVER_PIDS[$i]=$LAST_UNOSERVER_PID
+ UNOSERVER_PIDS[i]=$LAST_UNOSERVER_PID
fi
i=$((i + 1))
done
@@ -344,7 +420,8 @@ start_unoserver_watchdog() {
) &
}
-start_unoserver_pool() {
+# Start the unoserver pool eagerly (legacy always-on mode).
+start_unoserver_pool_eager() {
local auto
auto="$(get_unoserver_auto)"
auto="${auto,,}"
@@ -381,6 +458,178 @@ start_unoserver_pool() {
sleep 2
}
+# ---------- On-demand unoserver management ----------
+# When UNO_DEMAND_ENABLED=true, unoserver + soffice + Xvfb are only started
+# when a conversion is needed and stopped after an idle timeout.
+# This saves ~200-350 MB idle memory.
+UNO_DEMAND_FILE="/tmp/uno-last-used"
+UNO_POOL_RUNNING=false
+XVFB_PID=""
+
+start_xvfb_if_needed() {
+ if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
+ return 0
+ fi
+ if command_exists Xvfb; then
+ Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset > /dev/null 2>&1 &
+ XVFB_PID=$!
+ export DISPLAY=:99
+ sleep 1
+ log "Xvfb started on-demand (pid $XVFB_PID)"
+ fi
+}
+
+stop_xvfb() {
+ if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
+ kill -TERM "$XVFB_PID" 2>/dev/null || true
+ wait "$XVFB_PID" 2>/dev/null || true
+ log "Xvfb stopped"
+ fi
+ XVFB_PID=""
+}
+
+# Start the unoserver pool on-demand (called from the demand manager).
+start_unoserver_pool_now() {
+ if [ "$UNO_POOL_RUNNING" = true ]; then
+ return 0
+ fi
+
+ start_xvfb_if_needed
+
+ local count
+ count="$(get_unoserver_count)"
+ case "$count" in
+ ''|*[!0-9]*) count=1 ;;
+ esac
+ if [ "$count" -le 0 ]; then
+ count=1
+ fi
+
+ UNOSERVER_PIDS=()
+ UNOSERVER_PORTS=()
+ UNOSERVER_UNO_PORTS=()
+
+ local i=0
+ while [ "$i" -lt "$count" ]; do
+ local port=$((2003 + (i * 2)))
+ local uno_port=$((2004 + (i * 2)))
+ log "Starting unoserver on-demand on 127.0.0.1:${port} (uno-port ${uno_port})"
+ UNOSERVER_PORTS+=("$port")
+ UNOSERVER_UNO_PORTS+=("$uno_port")
+ start_unoserver_instance "$port" "$uno_port"
+ UNOSERVER_PIDS+=("$LAST_UNOSERVER_PID")
+ i=$((i + 1))
+ done
+
+ # Wait for readiness
+ local ready=false
+ for _ in {1..30}; do
+ if check_unoserver_ready "silent"; then
+ ready=true
+ break
+ fi
+ sleep 1
+ done
+
+ if [ "$ready" = true ]; then
+ log "unoserver pool started on-demand and ready"
+ else
+ log "WARNING: unoserver started but not ready after 30s"
+ fi
+ UNO_POOL_RUNNING=true
+}
+
+# Stop all unoserver instances and Xvfb to reclaim memory. Runs even when the
+# pool flag was never set, so a partially started pool still gets cleaned.
+stop_unoserver_pool_now() {
+ for pid in "${UNOSERVER_PIDS[@]:-}"; do
+ stop_unoserver_instance "$pid"
+ done
+
+ stop_xvfb
+
+ UNOSERVER_PIDS=()
+ UNOSERVER_PORTS=()
+ UNOSERVER_UNO_PORTS=()
+ if [ "$UNO_POOL_RUNNING" = true ]; then
+ log "unoserver pool stopped, memory reclaimed"
+ fi
+ UNO_POOL_RUNNING=false
+}
+
+# Demand manager: background loop that watches for conversion demand and manages idle timeout.
+start_unoserver_demand_manager() {
+ local idle_timeout=${UNO_IDLE_TIMEOUT_SECONDS:-120}
+ case "$idle_timeout" in
+ ''|*[!0-9]*) idle_timeout=120 ;;
+ esac
+ local check_interval=5
+
+ # This loop runs in a background subshell, so the parent's cleanup cannot see
+ # its UNOSERVER_PIDS or XVFB_PID; clean the tree up from here.
+ manager_cleanup() {
+ trap - TERM INT EXIT
+ stop_unoserver_pool_now
+ }
+ trap 'manager_cleanup; exit 0' TERM INT
+ trap manager_cleanup EXIT
+
+ log "unoserver demand manager started (idle_timeout=${idle_timeout}s)"
+
+ # Ensure demand file does not exist at startup
+ rm -f "$UNO_DEMAND_FILE"
+
+ while true; do
+ if [ -f "$UNO_DEMAND_FILE" ]; then
+ # Demand detected — ensure pool is running
+ if [ "$UNO_POOL_RUNNING" = false ]; then
+ log "unoserver demand detected, starting pool"
+ start_unoserver_pool_now
+ fi
+
+ # Check idle time
+ local last_used_epoch
+ last_used_epoch=$(cat "$UNO_DEMAND_FILE" 2>/dev/null || echo "0")
+ local now_epoch
+ now_epoch=$(date +%s)
+ local idle_secs=$(( now_epoch - last_used_epoch ))
+
+ if [ "$idle_secs" -ge "$idle_timeout" ] && [ "$UNO_POOL_RUNNING" = true ]; then
+ log "unoserver idle for ${idle_secs}s (timeout=${idle_timeout}s)"
+ stop_unoserver_pool_now
+ rm -f "$UNO_DEMAND_FILE"
+ fi
+ elif [ "$UNO_POOL_RUNNING" = true ]; then
+ # Demand file removed but pool still running — stop it
+ stop_unoserver_pool_now
+ fi
+
+ # Also health-check running instances
+ if [ "$UNO_POOL_RUNNING" = true ]; then
+ local i=0
+ while [ "$i" -lt "${#UNOSERVER_PIDS[@]}" ]; do
+ local pid=${UNOSERVER_PIDS[i]}
+ local port=${UNOSERVER_PORTS[i]}
+ local uno_port=${UNOSERVER_UNO_PORTS[i]}
+
+ if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then
+ log "unoserver PID ${pid} died for port ${port}, restarting"
+ start_unoserver_instance "$port" "$uno_port"
+ UNOSERVER_PIDS[i]=$LAST_UNOSERVER_PID
+ elif ! check_unoserver_port_ready "$port" "silent"; then
+ log "unoserver port ${port} unhealthy, restarting"
+ stop_unoserver_instance "$pid"
+ start_unoserver_instance "$port" "$uno_port"
+ UNOSERVER_PIDS[i]=$LAST_UNOSERVER_PID
+ fi
+ i=$((i + 1))
+ done
+ fi
+
+ sleep "$check_interval"
+ done
+}
+
# ---------- VERSION_TAG ----------
# Load VERSION_TAG from file if not provided via environment.
if [ -z "${VERSION_TAG:-}" ] && [ -f /etc/stirling_version ]; then
@@ -396,11 +645,13 @@ AOT_ENABLED="${STIRLING_AOT_ENABLE:-false}"
# Detects the container memory limit (in MB) from cgroups v2/v1 or /proc/meminfo.
detect_container_memory_mb() {
local mem_bytes=""
+ local no_cgroup_limit=false
# cgroups v2
if [ -f /sys/fs/cgroup/memory.max ]; then
mem_bytes=$(cat /sys/fs/cgroup/memory.max 2>/dev/null)
if [ "$mem_bytes" = "max" ]; then
mem_bytes=""
+ no_cgroup_limit=true
fi
fi
# cgroups v1 fallback
@@ -410,11 +661,33 @@ detect_container_memory_mb() {
# Use string-length heuristic (>=19 digits) to avoid shell integer overflow on Alpine/busybox
if [ "${#mem_bytes}" -ge 19 ]; then
mem_bytes=""
+ no_cgroup_limit=true
fi
fi
- # Fallback to system total memory
+ # Fallback when no cgroup memory limit is found.
+ # If running inside a container (/.dockerenv or /run/.containerenv present) with no
+ # limit set, the host's /proc/meminfo would return the full host RAM. Using that
+ # value causes InitialRAMPercentage to pre-commit gigabytes of heap against the host's
+ # RAM, making idle RSS absurdly large. Cap the effective size at 2 GB so the JVM
+ # stays proportionate. Users who need more should set -m / mem_limit in their
+ # docker-compose to get accurate sizing.
if [ -z "$mem_bytes" ]; then
- mem_bytes=$(awk '/MemTotal/ {print $2 * 1024}' /proc/meminfo 2>/dev/null)
+ local host_mem_bytes
+ host_mem_bytes=$(awk '/MemTotal/ {print $2 * 1024}' /proc/meminfo 2>/dev/null)
+ if [ "$no_cgroup_limit" = true ] && \
+ { [ -f /.dockerenv ] || [ -f /run/.containerenv ]; }; then
+ local cap_bytes=$(( 2048 * 1048576 ))
+ if [ "${host_mem_bytes:-0}" -gt "$cap_bytes" ] 2>/dev/null; then
+ log "WARNING: No container memory limit set. Host has $(( host_mem_bytes / 1048576 ))MB RAM."
+ log "Capping JVM sizing at 2048MB to avoid over-committing host memory."
+ log "Set mem_limit / -m in docker-compose or docker run to control heap sizing."
+ mem_bytes=$cap_bytes
+ else
+ mem_bytes=$host_mem_bytes
+ fi
+ else
+ mem_bytes=$host_mem_bytes
+ fi
fi
if [ -n "$mem_bytes" ] && [ "$mem_bytes" -gt 0 ] 2>/dev/null; then
echo $(( mem_bytes / 1048576 ))
@@ -423,17 +696,17 @@ detect_container_memory_mb() {
fi
}
-# Computes dynamic JVM memory flags based on detected container memory and profile.
+# Computes dynamic JVM memory flags based on detected container memory.
+# Uses performance-oriented settings (Shenandoah GC).
# Sets: DYNAMIC_INITIAL_RAM_PCT, DYNAMIC_MAX_RAM_PCT, DYNAMIC_MAX_METASPACE
compute_dynamic_memory() {
local mem_mb=$1
- local profile=${2:-balanced}
if [ "$mem_mb" -le 0 ] 2>/dev/null; then
# Cannot detect memory; use safe defaults
- DYNAMIC_INITIAL_RAM_PCT=10
- DYNAMIC_MAX_RAM_PCT=75
- DYNAMIC_MAX_METASPACE=256
+ DYNAMIC_INITIAL_RAM_PCT=2
+ DYNAMIC_MAX_RAM_PCT=70
+ DYNAMIC_MAX_METASPACE=512
return
fi
@@ -446,32 +719,26 @@ compute_dynamic_memory() {
# - Direct byte buffers, native memory
# Rule of thumb: heap% + (metaspace + ~200MB overhead) should fit in container.
if [ "$mem_mb" -le 512 ]; then
- DYNAMIC_INITIAL_RAM_PCT=30
+ DYNAMIC_INITIAL_RAM_PCT=2
DYNAMIC_MAX_RAM_PCT=55
- DYNAMIC_MAX_METASPACE=96
+ DYNAMIC_MAX_METASPACE=256
elif [ "$mem_mb" -le 1024 ]; then
- DYNAMIC_INITIAL_RAM_PCT=25
+ DYNAMIC_INITIAL_RAM_PCT=2
DYNAMIC_MAX_RAM_PCT=60
- DYNAMIC_MAX_METASPACE=128
+ DYNAMIC_MAX_METASPACE=384
elif [ "$mem_mb" -le 2048 ]; then
- DYNAMIC_INITIAL_RAM_PCT=20
+ DYNAMIC_INITIAL_RAM_PCT=2
DYNAMIC_MAX_RAM_PCT=65
- DYNAMIC_MAX_METASPACE=192
+ DYNAMIC_MAX_METASPACE=512
elif [ "$mem_mb" -le 4096 ]; then
- DYNAMIC_INITIAL_RAM_PCT=15
+ DYNAMIC_INITIAL_RAM_PCT=2
DYNAMIC_MAX_RAM_PCT=70
- DYNAMIC_MAX_METASPACE=256
+ DYNAMIC_MAX_METASPACE=512
else
- # Large memory: be conservative to leave room for off-heap (LibreOffice, Calibre, etc.)
- if [ "$profile" = "performance" ]; then
- DYNAMIC_INITIAL_RAM_PCT=20
- DYNAMIC_MAX_RAM_PCT=70
- DYNAMIC_MAX_METASPACE=512
- else
- DYNAMIC_INITIAL_RAM_PCT=10
- DYNAMIC_MAX_RAM_PCT=50
- DYNAMIC_MAX_METASPACE=256
- fi
+ # Large memory (>4GB): cap at 70% to leave room for off-heap (LibreOffice, Calibre, etc.)
+ DYNAMIC_INITIAL_RAM_PCT=2
+ DYNAMIC_MAX_RAM_PCT=70
+ DYNAMIC_MAX_METASPACE=768
fi
log "Dynamic memory: InitialRAM=${DYNAMIC_INITIAL_RAM_PCT}%, MaxRAM=${DYNAMIC_MAX_RAM_PCT}%, MaxMeta=${DYNAMIC_MAX_METASPACE}m"
@@ -688,8 +955,7 @@ save_aot_fingerprint() {
# ---------- Memory Detection ----------
CONTAINER_MEM_MB=$(detect_container_memory_mb)
-JVM_PROFILE="${STIRLING_JVM_PROFILE:-balanced}"
-compute_dynamic_memory "$CONTAINER_MEM_MB" "$JVM_PROFILE"
+compute_dynamic_memory "$CONTAINER_MEM_MB"
MEMORY_FLAGS="-XX:InitialRAMPercentage=${DYNAMIC_INITIAL_RAM_PCT} -XX:MaxRAMPercentage=${DYNAMIC_MAX_RAM_PCT} -XX:MaxMetaspaceSize=${DYNAMIC_MAX_METASPACE}m"
# ---------- Compressed Oops Detection ----------
@@ -707,32 +973,38 @@ if [ "$AOT_ENABLED" = "true" ]; then
fi
fi
-# ---------- JVM Profile Selection ----------
-# Resolve JAVA_BASE_OPTS from profile system or user override.
-# Priority: JAVA_BASE_OPTS (explicit override) > STIRLING_JVM_PROFILE > fallback defaults
+# ---------- JVM Options ----------
+# Resolve JAVA_BASE_OPTS from _JVM_OPTS or user override.
+# Priority: JAVA_BASE_OPTS (explicit override) > _JVM_OPTS > fallback defaults
+# Memory percentages are computed dynamically by compute_dynamic_memory().
+
+# Calculate ConcGCThreads dynamically based on available CPUs
+# Shenandoah defaults to ParallelGCThreads/4; we cap it for large hosts
+AVAILABLE_CPUS=$(nproc 2>/dev/null || echo "2")
+if [ "$AVAILABLE_CPUS" -ge 16 ]; then
+ CONC_GC_THREADS=4
+elif [ "$AVAILABLE_CPUS" -ge 8 ]; then
+ CONC_GC_THREADS=3
+elif [ "$AVAILABLE_CPUS" -ge 4 ]; then
+ CONC_GC_THREADS=2
+else
+ CONC_GC_THREADS=1
+fi
+
if [ -z "${JAVA_BASE_OPTS:-}" ]; then
- case "$JVM_PROFILE" in
- performance)
- if [ -n "${_JVM_OPTS_PERFORMANCE:-}" ]; then
- JAVA_BASE_OPTS="${_JVM_OPTS_PERFORMANCE}"
- log "JVM profile: performance (Shenandoah generational)"
- else
- JAVA_BASE_OPTS="${_JVM_OPTS_BALANCED:-}"
- log "Performance profile not available in this image; falling back to balanced"
- fi
- ;;
- *)
- if [ -n "${_JVM_OPTS_BALANCED:-}" ]; then
- JAVA_BASE_OPTS="${_JVM_OPTS_BALANCED}"
- log "JVM profile: balanced (G1GC)"
- else
- log "JAVA_BASE_OPTS and profiles unset; applying fallback defaults."
- JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/stirling-pdf/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true"
- fi
- ;;
- esac
+ if [ -n "${STIRLING_JVM_PROFILE:-}" ]; then
+ log "STIRLING_JVM_PROFILE is deprecated; use _JVM_OPTS or JAVA_BASE_OPTS instead"
+ fi
+ if [ -n "${_JVM_OPTS:-}" ]; then
+ STRIPPED_JVM_OPTS=$(echo "$_JVM_OPTS" | sed -E 's/-XX:ConcGCThreads=[^ ]*//g')
+ JAVA_BASE_OPTS="${STRIPPED_JVM_OPTS} -XX:ConcGCThreads=${CONC_GC_THREADS}"
+ log "Using _JVM_OPTS (ConcGCThreads=${CONC_GC_THREADS})"
+ else
+ log "JAVA_BASE_OPTS and _JVM_OPTS unset; applying fallback defaults."
+ JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/stirling-pdf/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational -XX:ShenandoahGCHeuristics=adaptive -XX:ShenandoahUncommitDelay=1000 -XX:ShenandoahGuaranteedYoungGCInterval=10000 -XX:ShenandoahGuaranteedOldGCInterval=30000 -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:+ExplicitGCInvokesConcurrent -XX:ConcGCThreads=${CONC_GC_THREADS} -XX:ReservedCodeCacheSize=96m -Xss256k -XX:CICompilerCount=2 -Djdk.virtualThreadScheduler.maxPoolSize=4 -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true"
+ fi
- # Strip any hardcoded memory/CDS/AOT flags from the profile (managed dynamically)
+ # Strip any hardcoded memory/CDS/AOT flags from the options (managed dynamically)
JAVA_BASE_OPTS=$(echo "$JAVA_BASE_OPTS" | sed -E \
's/-XX:InitialRAMPercentage=[^ ]*//g;
s/-XX:MinRAMPercentage=[^ ]*//g;
@@ -918,30 +1190,43 @@ for dir in "${CRITICAL_DIRS[@]}"; do
fi
done
-# ---------- Xvfb ----------
-# Start a virtual framebuffer for GUI-based LibreOffice interactions.
-if command_exists Xvfb; then
- log "Starting Xvfb on :99"
- Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset > /dev/null 2>&1 &
- export DISPLAY=:99
- # Brief pause so Xvfb accepts connections before unoserver tries to attach
- sleep 1
-else
- log "Xvfb not installed; skipping virtual display setup"
-fi
+# ---------- Xvfb + unoserver ----------
+# Detect whether on-demand mode is enabled.
+UNO_DEMAND_ENABLED="${UNO_DEMAND_ENABLED:-true}"
+UNO_DEMAND_ENABLED="${UNO_DEMAND_ENABLED,,}"
-# ---------- unoserver ----------
-# Start LibreOffice UNO server for document conversions.
-# Java and unoserver start in parallel, do NOT block here waiting for readiness.
-# Readiness is verified after Java is launched; the watchdog handles any restarts.
UNOSERVER_BIN="$(command -v unoserver || true)"
UNOCONVERT_BIN="$(command -v unoconvert || true)"
UNOPING_BIN="$(command -v unoping || true)"
+
if [ -n "$UNOSERVER_BIN" ] && [ -n "$UNOCONVERT_BIN" ]; then
LIBREOFFICE_PROFILE="${HOME:-/home/${RUNTIME_USER}}/.libreoffice_uno_${RUID}"
run_as_runtime_user mkdir -p "$LIBREOFFICE_PROFILE"
- start_unoserver_pool
- log "unoserver pool started (Profile: $LIBREOFFICE_PROFILE), Java starting in parallel"
+
+ if [ "$UNO_DEMAND_ENABLED" = "true" ]; then
+ # ---------- On-demand mode ----------
+ # Do NOT start Xvfb, unoserver, or soffice yet.
+ # The demand manager will start them lazily when a conversion request arrives
+ # and stop them after an idle timeout to reclaim ~200-350 MB RSS.
+ log "unoserver on-demand mode enabled (UNO_IDLE_TIMEOUT_SECONDS=${UNO_IDLE_TIMEOUT_SECONDS:-120}s)"
+ log "unoserver + soffice will start on first conversion request"
+ start_unoserver_demand_manager &
+ DEMAND_MANAGER_PID=$!
+ else
+ # ---------- Legacy always-on mode ----------
+ if command_exists Xvfb; then
+ log "Starting Xvfb on :99"
+ Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset > /dev/null 2>&1 &
+ XVFB_PID=$!
+ export DISPLAY=:99
+ sleep 1
+ else
+ log "Xvfb not installed; skipping virtual display setup"
+ fi
+
+ start_unoserver_pool_eager
+ log "unoserver pool started (Profile: $LIBREOFFICE_PROFILE), Java starting in parallel"
+ fi
else
log "unoserver/unoconvert not installed; skipping UNO setup"
fi
@@ -1014,11 +1299,8 @@ fi
JAVA_PID=$!
-# ---------- Unoserver Readiness + Watchdog ----------
-# Now that Java is running, check unoserver readiness and start the watchdog.
-# Runs in the main shell (not a subshell) so UNOSERVER_PIDS/PORTS arrays are accessible.
-# Java handles unoserver being temporarily unavailable, no fatal exit on timeout.
-if [ "${#UNOSERVER_PORTS[@]}" -gt 0 ]; then
+# ---------- Unoserver Readiness + Watchdog (legacy always-on mode only) ----------
+if [ "$UNO_DEMAND_ENABLED" != "true" ] && [ "${#UNOSERVER_PORTS[@]}" -gt 0 ]; then
log "Waiting for unoserver (Java already starting in parallel)..."
UNOSERVER_READY=false
for _ in {1..30}; do
@@ -1100,7 +1382,7 @@ if [ "$AOT_GENERATE_BACKGROUND" = true ]; then
fi
done
log "AOT: All attempts failed. App runs normally without cache."
- log "AOT: To disable, set STIRLING_AOT_ENABLE=false (or omit it, default is off)"
+ log "AOT: To disable, set STIRLING_AOT_ENABLE=false"
) &
AOT_GEN_PID=$!
log "AOT: Background generation scheduled (PID $AOT_GEN_PID, arch=$(uname -m))"
diff --git a/scripts/init.sh b/scripts/init.sh
index bc5a4208a1..39eb5e6c6d 100644
--- a/scripts/init.sh
+++ b/scripts/init.sh
@@ -1,102 +1,26 @@
#!/bin/bash
-# This script initializes environment variables and paths,
-# prepares Tesseract data directories, and then runs the main init script.
+# OCR entrypoint wrapper.
+# Sets up Tesseract tessdata, then delegates all startup logic to init-without-ocr.sh.
+# All shared environment setup (LD_LIBRARY_PATH, Python PATH, temp dirs) lives in
+# init-without-ocr.sh so that images calling it directly (e.g. ultra-lite) work correctly.
set -euo pipefail
-append_env_path() {
- local target="$1" current="$2" separator=":"
- if [ -d "$target" ] && [[ ":${current}:" != *":${target}:"* ]]; then
- if [ -n "$current" ]; then
- printf '%s' "${target}${separator}${current}"
- else
- printf '%s' "${target}"
- fi
- else
- printf '%s' "$current"
- fi
-}
-
-python_site_dir() {
- local venv_dir="$1"
- local python_bin="$venv_dir/bin/python"
- if [ -x "$python_bin" ]; then
- local py_tag
- if py_tag="$("$python_bin" -c 'import sys; print(f"python{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null)" \
- && [ -n "$py_tag" ] \
- && [ -d "$venv_dir/lib/$py_tag/site-packages" ]; then
- printf '%s' "$venv_dir/lib/$py_tag/site-packages"
- fi
- fi
-}
-
-# === LD_LIBRARY_PATH ===
-# Adjust the library path depending on CPU architecture.
-ARCH=$(uname -m)
-case "$ARCH" in
- x86_64)
- [ -d /usr/lib/x86_64-linux-gnu ] && export LD_LIBRARY_PATH="/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
- ;;
- aarch64)
- [ -d /usr/lib/aarch64-linux-gnu ] && export LD_LIBRARY_PATH="/usr/lib/aarch64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
- ;;
-esac
-
-# Add LibreOffice program directory to library path if available.
-if [ -d /usr/lib/libreoffice/program ]; then
- export LD_LIBRARY_PATH="/usr/lib/libreoffice/program${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
-fi
-
-# === Python PATH ===
-# Add virtual environments to PATH and PYTHONPATH.
-for dir in /opt/venv/bin /opt/unoserver-venv/bin; do
- PATH="$(append_env_path "$dir" "$PATH")"
-done
-export PATH
-
-PYTHON_PATH_ENTRIES=()
-for venv in /opt/venv /opt/unoserver-venv; do
- if [ -d "$venv" ]; then
- site_dir="$(python_site_dir "$venv")"
- [ -n "${site_dir:-}" ] && PYTHON_PATH_ENTRIES+=("$site_dir")
- fi
-done
-if [ ${#PYTHON_PATH_ENTRIES[@]} -gt 0 ]; then
- PYTHONPATH="$(IFS=:; printf '%s' "${PYTHON_PATH_ENTRIES[*]}")${PYTHONPATH:+:$PYTHONPATH}"
- export PYTHONPATH
-fi
-
-# # === tessdata ===
-# # Prepare Tesseract OCR data directory.
-# In Debian, tesseract looks in /usr/share/tesseract-ocr/5/tessdata
-# For backwards compatibility, copy any user-mounted files from /usr/share/tessdata
+# === Tessdata (OCR-specific) ===
+# In Debian, tesseract looks in /usr/share/tesseract-ocr/5/tessdata.
+# For backwards compatibility, copy any user-mounted files from /usr/share/tessdata.
TESSDATA_SYSTEM="/usr/share/tesseract-ocr/5/tessdata"
TESSDATA_MOUNT="/usr/share/tessdata"
-log_warn() {
- echo "[init][warn] $*" >&2
-}
-
-# Ensure system tessdata directory exists
mkdir -p "$TESSDATA_SYSTEM" 2>/dev/null || true
-# For backwards compatibility: if user mounted custom languages to /usr/share/tessdata,
-# copy them to the system location where Tesseract actually looks
if [ -d "$TESSDATA_MOUNT" ] && [ "$(ls -A "$TESSDATA_MOUNT" 2>/dev/null)" ]; then
- log_warn "Found user-mounted tessdata in $TESSDATA_MOUNT, copying to system location $TESSDATA_SYSTEM"
+ echo "[init][warn] Found user-mounted tessdata in $TESSDATA_MOUNT, copying to $TESSDATA_SYSTEM" >&2
cp -rn "$TESSDATA_MOUNT"/* "$TESSDATA_SYSTEM"/ 2>/dev/null || true
fi
-# Set TESSDATA_PREFIX to system location
export TESSDATA_PREFIX="$TESSDATA_SYSTEM"
-log_warn "Using TESSDATA_PREFIX=$TESSDATA_PREFIX"
-
-# === Temp dir ===
-# Ensure the temporary directory exists and has proper permissions.
-mkdir -p /tmp/stirling-pdf
-chown -R stirlingpdfuser:stirlingpdfgroup /tmp/stirling-pdf || true
-chmod -R 755 /tmp/stirling-pdf || true
+echo "[init][warn] Using TESSDATA_PREFIX=$TESSDATA_PREFIX" >&2
-# === Start application ===
-# Run the main init script that handles the full startup logic.
+# === Delegate to main startup script ===
exec /scripts/init-without-ocr.sh
diff --git a/testing/test.sh b/testing/test.sh
index 5a1bbf5276..d14caf3a95 100644
--- a/testing/test.sh
+++ b/testing/test.sh
@@ -426,7 +426,15 @@ compare_file_lists() {
# Check if we at least have the after file to look for temp files
if [ -s "$after_file" ]; then
echo "Checking for temp files in the after snapshot..."
- grep -i "tmp\|temp" "$after_file" > "${diff_file}.tmp"
+ grep -i "tmp\|temp" "$after_file" \
+ | grep -v '/jpdfium-' \
+ | grep -v '\.libreoffice_uno_' \
+ | grep -v '\.X99-lock' \
+ | grep -v 'uno-last-used' \
+ | grep -v 'xdg-' \
+ | grep -v 'dconf' \
+ | grep -v 'fontconfig' \
+ > "${diff_file}.tmp" || true
if [ -s "${diff_file}.tmp" ]; then
echo "WARNING: Temporary files found:"
cat "${diff_file}.tmp"
@@ -456,8 +464,16 @@ compare_file_lists() {
# Exclude JPDFium native cache + merge seed temp files
# (both deleteOnExit-registered, not leaks).
+ # Also exclude LibreOffice instance folders, X11 locks, and dconf caches
+ # which are transient and normal during container operation.
grep -i "tmp\|temp" "${diff_file}.added" \
| grep -v '/jpdfium-' \
+ | grep -v '\.libreoffice_uno_' \
+ | grep -v '\.X99-lock' \
+ | grep -v 'uno-last-used' \
+ | grep -v 'xdg-' \
+ | grep -v 'dconf' \
+ | grep -v 'fontconfig' \
> "${diff_file}.tmp" || true
if [ -s "${diff_file}.tmp" ]; then
echo "WARNING: Temporary files detected:"