Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
216c0b2
[Server] Close the server on JVM shutdown
shba24 Oct 27, 2026
323568b
[Server] Stop Log4j after the JVM-shutdown drain
shba24 Oct 27, 2026
af1f380
[Server] Stop the storage cleanup before the JVM-shutdown drain
shba24 Oct 27, 2026
7be8973
[Server] Stop Log4j even when the server fails to close
shba24 Oct 27, 2026
2f21eaa
[Server] exec the JVM from start-uc-server and turn off Log4j's hook …
shba24 Oct 27, 2026
58a57c1
[Server] Run close() on SIGTERM and turn off Log4j's hook on every la…
shba24 Oct 27, 2026
fb2fee5
[Server] Close the database pool quietly in close()
shba24 Oct 27, 2026
9670a9a
[Server] Stop Log4j when the server fails to start
shba24 Oct 27, 2026
97a1676
[Server] Keep the H2 database open until the shutdown drain ends
shba24 Oct 27, 2026
96b06b6
[Server] Turn off Log4j's hook only in the start script again
shba24 Oct 27, 2026
f7356f2
[Server] Close the H2 file database with the connection pool
shba24 Oct 27, 2026
6cdf5a4
[Server] Match the shutdown-timeout comment to the docs
shba24 Oct 27, 2026
38f7cdb
[Docs] Give the two H2 URL settings separately, with an upgrade note
shba24 Oct 27, 2026
561d9a1
[Server] Interrupt requests still running after the shutdown drain
shba24 Oct 28, 2026
43ddf52
[Server] Set DB_CLOSE_DELAY=0 on the H2 URL, and give interrupted tas…
shba24 Oct 28, 2026
abb9bf9
[Server] Don't let a stuck policy refresh block shutdown
shba24 Oct 28, 2026
4db7e93
[Server] Send the CSRF header in the SCIM database-failure test
shba24 Oct 28, 2026
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
8 changes: 5 additions & 3 deletions bin/start-uc-server
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ generate_jar() {
$GENERATE_JAR_COMMAND || exit
}

# This function starts the unity catalog server
# This function starts the unity catalog server. exec makes the JVM this process, so it receives
# SIGTERM itself (as PID 1 in a container) and drains before exiting. The server stops Log4j after
# that drain, so Log4j's own shutdown hook, which would stop logging during it, is off.
run_uc_server_java_command() {
SERVER_JAVA_COMMAND="java -cp $(cat "$1") io.unitycatalog.server.UnityCatalogServer"
SERVER_JAVA_COMMAND="java -Dlog4j2.shutdownHookEnabled=false -cp $(cat "$1") io.unitycatalog.server.UnityCatalogServer"
shift
$SERVER_JAVA_COMMAND "$@" || exit
exec $SERVER_JAVA_COMMAND "$@"
}

# This function runs the server using the source code
Expand Down
5 changes: 5 additions & 0 deletions docs/server/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ The server config file is at the location `etc/conf/server.properties` (relative
any principal who can create a table can use it. Each entry must be a local path; an entry such as an `s3://` URL
fails server startup. As with `storage-root.*`, a relative path containing `/` (for example `./uc-external`) is
resolved against the server's working directory, and a directory that does not exist yet is accepted.
- `server.shutdown-timeout`: How long the server waits for in-flight requests when it stops, for example on SIGTERM.
Defaults to `PT5S`. Stopping takes longer than this: up to 5 seconds more if a storage cleanup attempt is
running, plus about 2 seconds to stop the HTTP server. With the default, give `docker stop` 15 seconds or more
(`--time`, or `--stop-timeout` on `docker run`), and keep Kubernetes' `terminationGracePeriodSeconds` above it
too; raise both when you raise this setting.

!!! note "Local `file:` locations"
A local `file:` location must name one plain path. The server rejects with `400` a location that has an encoded
Expand Down
9 changes: 9 additions & 0 deletions docs/server/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ This guide outlines how to deploy the Unity Catalog server.

- The backend database can be configured by modifying the `etc/conf/hibernate.properties` file.
- You need to provide the connection details to connect to your database server.
- With an H2 file database, set the URL as the default file does:
`jdbc:h2:file:./etc/db/h2db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=0`.
- `DB_CLOSE_ON_EXIT=FALSE` stops H2 from closing the database as soon as the JVM starts to exit. Without it,
requests still finishing during a graceful shutdown fail.
- `DB_CLOSE_DELAY=0` closes the database when the server closes its connection pool, after those requests.
Keep it in the URL: H2 stores the delay in the database file, so a database first opened with the old
`DB_CLOSE_DELAY=-1` would otherwise keep it and never close.
- When upgrading, update your own `etc/conf/hibernate.properties`, or the Helm chart's `server.db.overrideConfig`,
if it still has the old URL ending in `;DB_CLOSE_DELAY=-1`.
- Hibernate and Casbin use one HikariCP pool built from those connection properties, so total
database connections are capped by `hibernate.hikari.maximumPoolSize` (not Hibernate's pool
plus a separate Casbin connection). Optional pool settings use `hibernate.hikari.*` keys.
Expand Down
5 changes: 4 additions & 1 deletion etc/conf/hibernate.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:file:./etc/db/h2db;DB_CLOSE_DELAY=-1
# DB_CLOSE_ON_EXIT=FALSE keeps the database open while requests drain on shutdown, and
# DB_CLOSE_DELAY=0 closes it when the server closes its connection pool afterwards. H2 stores the
# delay in the database file, so it is set here to replace the -1 an older URL stored.
hibernate.connection.url=jdbc:h2:file:./etc/db/h2db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=0

# One HikariCP pool for Hibernate and Casbin (a single maximumPoolSize cap).
# Autocommit defaults to false. jdbc-adapter 2.7.0 still holds one pooled connection;
Expand Down
4 changes: 2 additions & 2 deletions etc/conf/server.properties
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ server.access-token-timeout=PT24H
# How long a graceful stop waits for in-flight HTTP requests; close then gives the blocking-work
# drain whatever is left of it. This is not a total shutdown deadline: stopping storage cleanup,
# Armeria's final event-loop shutdown (about 2s), and closing the authorizer and database pool
# add time. Leave headroom under the orchestrator grace period (Kubernetes default 30s,
# docker stop 10s).
# add time, about 12s in all with the default. Give docker stop 15s or more, and keep the
# Kubernetes grace period (default 30s) above that; see docs/server/configuration.md.
# server.shutdown-timeout=PT5S

# Authorization policy refresh across server instances that share one database.
Expand Down
2 changes: 1 addition & 1 deletion helm/templates/server/_config.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ gcs.jsonKeyFilePath.{{ $index }}=/etc/conf/gcs-credentials-{{ $index }}.json
{{ .Values.server.db.overrideConfig }}
{{- else if eq .Values.server.db.type "file" -}}
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:file:./etc/db/h2db;DB_CLOSE_DELAY=-1
hibernate.connection.url=jdbc:h2:file:./etc/db/h2db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=0
{{- else if eq .Values.server.db.type "postgresql" -}}

{{- $params := dict }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.UnaryOperator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.Configurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -74,6 +75,9 @@ public class UnityCatalogServer implements AutoCloseable {
private final HibernateConfigurator hibernateConfigurator;
private final BlockingTaskExecutor blockingTaskExecutor;

/** How long tasks interrupted at the end of the shutdown drain get to stop. */
private static final Duration INTERRUPTED_TASK_GRACE = Duration.ofMillis(500);

private final Duration shutdownTimeout;

/** True when this server built the configurator itself and must therefore close it. */
Expand Down Expand Up @@ -134,9 +138,9 @@ private UnityCatalogServer(UnityCatalogServer.Builder unityCatalogServerBuilder)
}

/**
* Shuts down the server-owned blocking executor and waits up to {@code timeout}. A task still
* running after that is left in place and shutdown continues, so a wedged JDBC call cannot hold
* the process until the orchestrator kills it.
* Shuts down the server-owned blocking executor and waits up to {@code timeout}. Tasks still
* running after that are interrupted and given a moment to stop; then shutdown continues, so a
* wedged JDBC call cannot hold the process until the orchestrator kills it.
*/
private static void closeBlockingTaskExecutor(
BlockingTaskExecutor executor, Duration timeout, Throwable primaryFailure) {
Expand All @@ -148,8 +152,15 @@ private static void closeBlockingTaskExecutor(
executor.shutdown();
try {
if (!executor.awaitTermination(timeout.toNanos(), TimeUnit.NANOSECONDS)) {
// A task blocked on a lock, a sleep or interruptible I/O stops on the interrupt, before
// the resources it uses are closed. One that ignores interrupts can still be running
// when they close, and keeps running until the process exits.
LOGGER.warn(
"Blocking task executor did not stop within {}; continuing shutdown", timeout);
"Blocking task executor did not stop within {}; interrupting its tasks", timeout);
executor.shutdownNow();
if (!executor.awaitTermination(INTERRUPTED_TASK_GRACE.toNanos(), TimeUnit.NANOSECONDS)) {
LOGGER.warn("Blocking tasks still running after the interrupt; continuing shutdown");
}
}
} catch (InterruptedException ignored) {
interrupted = true;
Expand Down Expand Up @@ -458,9 +469,23 @@ public static void main(String[] args) {
unityCatalogServer.start();
} catch (RuntimeException e) {
LOGGER.error("Failed to start the Unity Catalog server", e);
unityCatalogServer.close();
try {
unityCatalogServer.close();
} finally {
LogManager.shutdown();
}
throw e;
}
// On SIGTERM, close() runs on Armeria's shutdown thread: it stops the storage cleanup, lets
Comment thread
shba24 marked this conversation as resolved.
Resolved
// in-flight requests finish for up to server.shutdown-timeout, then closes everything else.
Comment thread
shba24 marked this conversation as resolved.
Resolved
// Log4j stops last, even when close() fails (Armeria logs that failure); bin/start-uc-server
// turns off Log4j's own shutdown hook so it doesn't stop logging during the drain. The hook is
// registered after start() so that close() can't run during a start; a SIGTERM while starting
// exits without it.
unityCatalogServer
.server
.closeOnJvmShutdown(unityCatalogServer::close)
.whenComplete((unused, failure) -> LogManager.shutdown());
}

public void start() {
Expand Down Expand Up @@ -488,7 +513,8 @@ public void stop() {
* <p>The blocking executor is drained before anything else is closed, using the time remaining
* from {@code server.shutdown-timeout}, so a handler that outlived {@link #stop()} does not see a
* closed authorizer or cleanup worker. This is not a total shutdown deadline: other resource
* cleanup and Armeria's final shutdown can add time.
* cleanup and Armeria's final shutdown can add time. A resource that fails to close is logged and
* the rest still close; only a failure from {@link #stop()} is thrown.
*/
@Override
public void close() {
Expand All @@ -502,9 +528,8 @@ public void close() {
closeQuietly(metrics, null, "the metrics registry");
closeQuietly(cleanupWorker, null, "the storage cleanup worker");
closeQuietly(authorizer instanceof AutoCloseable c ? c : null, null, "the authorizer");
if (ownsHibernateConfigurator) {
hibernateConfigurator.close();
}
closeQuietly(
ownsHibernateConfigurator ? hibernateConfigurator : null, null, "the database pool");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;
import org.slf4j.Logger;
Expand Down Expand Up @@ -59,7 +60,9 @@ private enum ProbeResult {
// System.nanoTime() of the last successful probe start; Long.MIN_VALUE if none.
private volatile long lastCompletedProbeAtNanos = Long.MIN_VALUE;

private ScheduledExecutorService executor;
// Not guarded by this object's monitor: a refresh holds it while it reads the database, and
// close() must not wait for a refresh that is stuck there.
private final AtomicReference<ScheduledExecutorService> executor = new AtomicReference<>();

public CasbinPolicyRefresher(
Runnable reloader, SessionFactory sessionFactory, Duration minProbeInterval) {
Expand All @@ -69,18 +72,19 @@ public CasbinPolicyRefresher(
}

public synchronized void start(Duration interval) {
if (executor != null) {
if (executor.get() != null) {
return;
}
executor =
ScheduledExecutorService started =
Executors.newSingleThreadScheduledExecutor(
runnable -> {
Thread thread = new Thread(runnable, "casbin-policy-refresher");
thread.setDaemon(true);
return thread;
});
executor.set(started);
long millis = Math.max(1, interval.toMillis());
executor.scheduleWithFixedDelay(this::pollQuietly, millis, millis, TimeUnit.MILLISECONDS);
started.scheduleWithFixedDelay(this::pollQuietly, millis, millis, TimeUnit.MILLISECONDS);
LOGGER.info(
"Casbin policy refresh enabled, checking every {}ms; deny-path min probe interval {}ms",
millis,
Expand Down Expand Up @@ -246,11 +250,8 @@ private Optional<Long> readMaxId() {

@Override
public void close() {
ScheduledExecutorService toShutDown;
synchronized (this) {
toShutDown = executor;
executor = null;
}
// shutdownNow() interrupts a refresh in progress, which may hold this object's monitor.
ScheduledExecutorService toShutDown = executor.getAndSet(null);
if (toShutDown == null) {
return;
}
Expand All @@ -264,7 +265,8 @@ public void close() {
}
}

synchronized boolean isRunning() {
return executor != null && !executor.isShutdown();
boolean isRunning() {
ScheduledExecutorService running = executor.get();
return running != null && !running.isShutdown();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ void closeReturnsWithinShutdownTimeoutWhenBlockingTaskIsWedged() throws Exceptio
new HibernateConfigurator(HibernateConfigurator.setupHibernateProperties(serverProperties));
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
CountDownLatch interrupted = new CountDownLatch(1);
CapturingAppender appender = new CapturingAppender();
Logger serverLogger = null;
Level previousLevel = null;
Expand All @@ -66,7 +67,8 @@ void closeReturnsWithinShutdownTimeoutWhenBlockingTaskIsWedged() throws Exceptio
.port(port)
.serverProperties(serverProperties)
.hibernateConfigurator(hibernateConfigurator)
.credentialOperations(new WedgedCredentialVendor(serverProperties, entered, release))
.credentialOperations(
new WedgedCredentialVendor(serverProperties, entered, release, interrupted))
.build();
// Attach after build(): loading UnityCatalogServer (re)initializes log4j. The test JVM may
// not find etc/conf/server.log4j2.properties and fall back to ERROR, so enable WARN here.
Expand Down Expand Up @@ -102,6 +104,9 @@ void closeReturnsWithinShutdownTimeoutWhenBlockingTaskIsWedged() throws Exceptio
.isLessThan(SHUTDOWN_TIMEOUT.plus(ARMERIA_STOP_TAIL).plusSeconds(1));
assertThat(appender.warnings())
.anyMatch(message -> message.startsWith("Blocking task executor did not stop within"));
assertThat(interrupted.await(5, TimeUnit.SECONDS))
.as("close() interrupts the request still running after the drain")
.isTrue();
} finally {
release.countDown();
if (serverLogger != null) {
Expand All @@ -126,12 +131,17 @@ private static final class WedgedCredentialVendor extends CloudCredentialVendor

private final CountDownLatch entered;
private final CountDownLatch release;
private final CountDownLatch interrupted;

private WedgedCredentialVendor(
ServerProperties serverProperties, CountDownLatch entered, CountDownLatch release) {
ServerProperties serverProperties,
CountDownLatch entered,
CountDownLatch release,
CountDownLatch interrupted) {
super(serverProperties);
this.entered = entered;
this.release = release;
this.interrupted = interrupted;
}

@Override
Expand All @@ -140,6 +150,7 @@ public TemporaryCredentials vendCredential(CredentialContext context) {
try {
release.await();
} catch (InterruptedException e) {
interrupted.countDown();
Thread.currentThread().interrupt();
}
return new TemporaryCredentials();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;

import io.unitycatalog.server.persist.model.Privileges;
import io.unitycatalog.server.persist.utils.HibernateConfigurator;
Expand Down Expand Up @@ -467,6 +468,35 @@ private static void awaitLatch(CountDownLatch latch, String description) {
}
}

@Test
void closeDoesNotWaitForARefreshStuckInsideTheLock() throws Exception {
startReplica(); // creates casbin_rule, which the refresh reads
CountDownLatch reloading = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
CasbinPolicyRefresher refresher =
new CasbinPolicyRefresher(
() -> {
reloading.countDown();
try {
release.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
},
hibernateConfigurator.getSessionFactory(),
Duration.ZERO);
try {
// The first check always reloads, so the poller ends up waiting inside the refresh lock.
refresher.start(Duration.ofMillis(10));
awaitLatch(reloading, "the refresh to start reloading");
// close() interrupts the stuck refresh instead of waiting for its lock.
assertTimeoutPreemptively(Duration.ofSeconds(3), refresher::close);
assertThat(refresher.isRunning()).isFalse();
} finally {
release.countDown();
}
}

@Test
void closeStopsTheRefreshThread() throws Exception {
JCasbinAuthorizer replica = startReplica();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ public void testScimCreateUserDatabaseFailureIsAServerError() throws Exception {
.path("/api/1.0/unity-control/scim2/Users")
.contentType(MediaType.JSON)
.add(HttpHeaderNames.COOKIE, "UC_TOKEN=" + securityContext.getServiceToken())
.add(HttpHeaderNames.X_REQUESTED_WITH, "XMLHttpRequest")
.build();
String userJson =
"{\"displayName\":\"test\",\"emails\":[{\"value\":\""
Expand Down
Loading