Skip to content

[Server] Shut down gracefully on SIGTERM - #2059

Merged
yili-db merged 17 commits into
unitycatalog:mainfrom
shba24:stack/uc-jvm-shutdown
Oct 28, 2026
Merged

yili-db merged 17 commits into
unitycatalog:mainfrom
shba24:stack/uc-jvm-shutdown

Conversation

@shba24

@shba24 shba24 commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

🥞 Stacked PR

Use this link to review incremental changes.


PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added or modified a feature, documentation in docs is updated

Description of changes

On SIGTERM (docker stop, or Kubernetes stopping a pod), the server doesn't shut down cleanly. In the Docker image the JVM never even receives the signal: bin/start-uc-server runs java as a child of the shell, so docker stop waits 10s and kills it. This PR:

  • execs the JVM from bin/start-uc-server, so it receives SIGTERM;
  • on SIGTERM, runs the server's close() from Armeria's shutdown hook: it stops the storage cleanup, lets in-flight requests finish for up to server.shutdown-timeout, and closes the rest of the server (blocking executor, authorizer, Hikari pool). Log4j stops last;
  • turns off Log4j's own JVM hook on that java command line, so lines logged during the drain are kept;
  • changes the default H2 URLs (etc/conf/hibernate.properties and the Helm chart) from DB_CLOSE_DELAY=-1 to DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=0, so H2's own JVM hook doesn't close the database while requests drain, and the database closes when the server closes its pool.

docs/server/configuration.md now documents server.shutdown-timeout, and docs/server/deployment.md the H2 setting.

Compatibility: after SIGTERM the process can take up to server.shutdown-timeout (default 5s) to drain requests, plus up to 5s if a storage cleanup attempt is running, plus about 2s for Armeria's final stop. With the default, give docker stop 15s or more, and raise it and terminationGracePeriodSeconds when you raise server.shutdown-timeout.

📐 Design notes & details

Before and after, on the Docker image:

Before After
PID 1 start-uc-server (bash), with java as a child java
docker stop 10s, then SIGKILL (exit 137) about 3s, exit 143
server.log at shutdown nothing Unity Catalog server stopped., then Hikari's Shutdown completed.

Kafka (bin/kafka-run-class.sh), Pulsar (bin/pulsar), Elasticsearch (its Docker entrypoint) and Polaris (run-java.sh) also exec the JVM.

Order on SIGTERM. Everything runs on Armeria's hook thread, so it finishes before the JVM exits.

  1. closeOnJvmShutdown(unityCatalogServer::close) runs close() as its whenClosing step. close() stops the cleanup worker, drains requests through server.stop(), then drains the blocking executor with the time left and closes the other resources. SIGTERM and close() share one shutdown path.
  2. Armeria's own server.close() then finds the server stopped and returns at once.
  3. Log4j stops last, through whenComplete, so it stops even if close() fails. Armeria logs that failure.

Policy refresh. With policy refresh on, close() interrupts a refresh still running instead of waiting for it: a refresh holds the refresher's lock while it reads the database, and close() used to need that lock first, so a refresh stuck in JDBC blocked shutdown.

Leftover requests. If requests are still running when the drain's time is up, close() interrupts them and waits up to 500 ms for them to stop before it closes the resources they use. One that ignores the interrupt keeps running until the process exits.

Failures. A resource that fails to close is logged and the rest still close. The database pool now closes the same way in close(); before, a failure there replaced an earlier failure from stop(). If the server fails to start, main closes it and then stops Log4j, since the script turns Log4j's own hook off.

Startup window. The hook is registered after start(), so close() can't run during a start. A SIGTERM while the server is starting exits without it, as before this PR.

Why Log4j's hook is off. JVM shutdown hooks run concurrently, and Log4j's own hook stopped logging while Armeria was still draining. The flag is on the java line, as Pulsar does it and as Elasticsearch's launcher adds it, so only the server started by the script is affected; the CLI, tests and apps that embed the server keep Log4j's hook. Running the server another way (java -jar, sbt server/run) still drains on SIGTERM, but may lose the lines logged during the drain, as before.

Log4j's config-file switch (shutdownHook = disable) doesn't work here. Log4j starts with its default config when UnityCatalogServer loads, and registers its hook then. The server applies etc/conf/server.log4j2.properties later.

Why H2 keeps the database open. H2 closes a file database from its own JVM hook as soon as the JVM starts to exit, so a request still draining fails when it touches the database ("Database is already closed"). With DB_CLOSE_ON_EXIT=FALSE, it stays open during the drain. DB_CLOSE_DELAY=0 closes the database when close() closes the pool. It must be in the URL, not just -1 removed: H2 stores the delay in the database file, so a database first opened with -1, including the shipped etc/db/h2db, keeps it and would never close.

Tests. No automated test: a JVM hook only runs when the process exits, and the CI jobs that start the server through the script or the image are disabled. A forked-JVM test is tracked in #2064. This was checked by hand:

  • locally through bin/start-uc-server, 3 runs: the script's PID is java; after SIGTERM the process exits with 143 in about 2.4s and server.log has Unity Catalog server stopped., which close() logs after the drain, and Hikari's Shutdown completed. from its last step. Started with plain java (no flag), both lines were missing in 2 of 2 runs;
  • H2 (2.2.224): a query from a JVM shutdown hook fails with the old URL and succeeds with DB_CLOSE_ON_EXIT=FALSE. A database created with DB_CLOSE_DELAY=-1 (as the shipped sample was) and reopened without it still reports -1 and stays open after its last connection closes; reopened with DB_CLOSE_DELAY=0, it closes, and a second process can open it. A catalog created before SIGTERM is still there after a restart;
  • on an image built from this branch: the table above;
  • start failure: with port 8080 already taken, the process exits with 1, logs the bind error, and closes the database pool before Log4j stops.

UnityCatalogServerTest and UnityCatalogServerShutdownTest pass.

This pull request and its description were written by Isaac.

@shba24 shba24 changed the title [Server] Close the server on JVM shutdown [Server] Shut down gracefully on SIGTERM Oct 27, 2026
@shba24
shba24 marked this pull request as ready for review October 27, 2026 04:07
@yili-db

yili-db commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

/review

1 similar comment
@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Nice, running close() from the hook is much better: SIGTERM and close() now share one shutdown path.

Two things are still open, inline. On tests: UnityCatalogServerShutdownTest already covers the drain inside close(), but nothing covers the hook itself or what happens at JVM exit (Log4j's and H2's own hooks). Removing the exec or the hook fails no test. Can we add a subprocess test, here or as a tracked follow-up? For example: a test main that builds the server on an H2 file URL with a credential vendor that waits a fixed time and then queries the DB; send a request, call process.destroy() (SIGTERM), and assert a 200 and exit code 143. That test would also catch the H2 issue below.

@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

/review

1 similar comment
@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review, @yili-db. On the subprocess test: filed #2064 for the forked-JVM SIGTERM test you described, and linked it from the description. For this PR it is verified by hand: script and image runs, start failure, and the H2 hook check.

@shba24
shba24 requested a review from yili-db October 27, 2026 07:19
@shba24

shba24 commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

/review

shba24 and others added 8 commits October 28, 2026 00:24
On SIGTERM the process exited without stopping Armeria, so in-flight requests
were cut off. main() now calls Armeria's closeOnJvmShutdown(), which stops
accepting requests and drains in-flight ones for up to server.shutdown-timeout.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
Log4j's own JVM hook runs alongside Armeria's drain and stops logging before it
ends, so the drained requests' log lines were lost. Turn that hook off (unless
log4j2.shutdownHookEnabled is set explicitly) and call LogManager.shutdown()
once the server is closed, as Elasticsearch, Pulsar and Spring Boot do.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
Run the cleanup worker's stop() as Armeria's whenClosing step, the same order
UnityCatalogServer.stop() uses, so no cleanup runs while the server drains.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
thenRun skips its step when the stage before it fails; whenComplete always runs.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
…there

In the Docker image the script was PID 1 and ran java as a child, so SIGTERM
never reached the JVM: docker stop waited 10s and killed it. exec makes the JVM
PID 1, as Kafka, Pulsar and Polaris do. Log4j's own hook is now turned off on
that java command line, as Pulsar does, instead of from a static block.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
…unch

Armeria's shutdown hook now runs UnityCatalogServer.close(), so SIGTERM closes
the same resources, in the same order, as close() does. Log4j's own hook is
turned off in log4j2.component.properties instead of on the start script's java
command line, so it is off however the server is launched.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
A failure closing the pool is now logged like the other resources, instead of
replacing an earlier failure from stop().

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
With Log4j's own hook off, main now stops Log4j after closing a server that
failed to start. Comments say why the hook is registered after start() and that
embedders stop Log4j themselves.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
shba24 and others added 6 commits October 28, 2026 00:24
H2 closes a file database from its own JVM hook as soon as the JVM starts to
exit, so a request still draining after SIGTERM failed when it touched the
database. The default H2 URLs (etc/conf and the Helm chart) set
DB_CLOSE_ON_EXIT=FALSE; the server closes the pool after the drain. Docs cover
the H2 setting and server.shutdown-timeout, and close()'s Javadoc says close
failures are logged.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
log4j2.component.properties turned the hook off in every JVM that loads the
server jar, including the CLI, tests and embedders that never stop Log4j
themselves. The flag is back on the java line in bin/start-uc-server.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
With DB_CLOSE_DELAY=-1 and DB_CLOSE_ON_EXIT=FALSE together, nothing closed the
H2 database: it stayed open after the pool closed and was still open at exit.
Without DB_CLOSE_DELAY=-1, H2 closes when close() closes the pool, after the
drain.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
When the blocking executor doesn't finish within the time left of
server.shutdown-timeout, close() now interrupts its remaining tasks before it
closes the resources they use.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@shba24
shba24 force-pushed the stack/uc-jvm-shutdown branch from 78d8ab1 to 561d9a1 Compare October 28, 2026 00:28
@shba24

shba24 commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

/review

…ks a moment to stop

H2 stores DB_CLOSE_DELAY in the database file, so a database first opened with
the old DB_CLOSE_DELAY=-1, including the shipped sample, kept it and never
closed. The URLs now set 0 explicitly. After interrupting leftover blocking
tasks, close() waits up to 500 ms for them before closing what they use.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@shba24

shba24 commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

/review

A Casbin policy refresh holds the refresher's lock while it reads the database,
and close() took the same lock before it interrupted the refresh, so a refresh
stuck in JDBC blocked close() with no bound. SIGTERM now runs close(), so the
refresher keeps its executor outside that lock and close() interrupts it first.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@shba24

shba24 commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

/review

unitycatalog#1994 requires X-Requested-With: XMLHttpRequest on cookie-authenticated writes.
testScimCreateUserDatabaseFailureIsAServerError, added by unitycatalog#1999, sends a SCIM
create with the UC_TOKEN cookie and no such header, so it now gets 403 instead
of the 500 it checks, and fails on main.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@yili-db
yili-db merged commit 734defa into unitycatalog:main Oct 28, 2026
19 checks passed
yili-db pushed a commit that referenced this pull request Oct 31, 2026
… pod (#2060)

## 🥞 Stacked PR
-
[**stack/ep3-helm-graceful-shutdown**](#2060)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2060/files)]
-
[stack/ep14-helm-readyz](#2063)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2063/files)]

---------
**PR Checklist**

- [x] A description of the changes is added to the description of this
PR.
- [ ] If there is a related issue, make sure it is linked to this PR.
- [ ] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

**Description of changes**

When Kubernetes stops a server pod (an upgrade, a scale-down), it can
keep routing requests to the pod for a few seconds after sending
SIGTERM. This adds two optional values so operators can roll out with
zero downtime:

- `server.deployment.lifecycle`, for a `preStop` sleep that keeps the
server serving until traffic stops arriving;
- `server.deployment.terminationGracePeriodSeconds`, so that sleep plus
`server.shutdown-timeout` fits before Kubernetes kills the pod.

Both are unset by default, so the rendered chart doesn't change.
`helm/ci/graceful-shutdown-values.yaml` sets both so that chart lint
renders them.

**Relies on #2059 (merged).** The graceful drain needs the server to
receive SIGTERM. #2059 makes `bin/start-uc-server` `exec` the JVM;
without it, the shell launcher doesn't forward the signal.

<details><summary><b>📐 Design notes &amp; details</b></summary>

**Why.** Kubernetes removes a terminating pod from Service endpoints
asynchronously, so requests can still reach it after SIGTERM. UC's drain
on SIGTERM (#2059) has a 1ms quiet period, so it turns those late
requests away. A `preStop` sleep delays the SIGTERM until routing has
caught up.

**Precedent.** Apache Polaris's chart has the same pair
(`containerLifecycle`, `terminationGracePeriodSeconds`). Both are unset
by default there too, with a `preStop` sleep given as the example.

**Example**, also added to `docs/server/helm.md`:

```yaml
server:
  deployment:
    lifecycle:
      preStop:
        exec:
          command: ["sleep", "10"]
    terminationGracePeriodSeconds: 30
```

**Checks.**
- `helm lint` passes.
- With both values unset, `helm template` renders the same output as the
PR below, apart from the randomly generated signing key.
- With the example values, `terminationGracePeriodSeconds` lands in the
pod spec and `lifecycle` in the `server` container.
- `helm/README.md` was regenerated with helm-docs; only the two new rows
were added.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
yili-db pushed a commit that referenced this pull request Nov 5, 2026
## 🥞 Stacked PR
-
[**uc-audit-records**](#2028)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2028/files)]
← _this PR_
-
[stack/uc-audit-permissions](#2029)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2029/files/cf57b065909bab74d0e7596a5256eb3c88a09d5d..fad9e62d824956a3fb14385636d2e3816f230892)]
-
[stack/uc-audit-cleanup-join](#2030)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2030/files/fad9e62d824956a3fb14385636d2e3816f230892..295bf3803ac83ff7861e50cabc0f2a2d4f26ed52)]

---------
**PR Checklist**

- [x] A description of the changes is added to the description of this
PR.
- [ ] If there is a related issue, make sure it is linked to this PR.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

**Description of changes**

Operators can't tell today who received storage credentials. With
`server.audit.sink` set, the server writes one audit record per issued
storage credential: for the caller (`CLIENT`), for its own use in a
request (`SERVER`), or for the background cleanup (`CLEANUP`). Cache
hits are included. Records never contain secrets. The built-in
`FileAuditSink` writes JSON lines to `etc/logs/audit.log`; a custom
`AuditSink` class can send them elsewhere. Unset (the default), nothing
changes.

```json
{"time":"2026-10-20T10:02:00.000Z","action":"ISSUE_CREDENTIAL","user":"[email protected]","request_id":"…","purpose":"CLIENT","location":"s3://bucket/root/tables/7f3a…","access":"READ","expires_at":"2026-10-20T11:02:00.000Z"}
```

**Open for discussion:** should audit be on by default? This PR keeps it
off.

**Compatibility:** `StorageCredentialVendor` is now an interface; `new
StorageCredentialVendor(...)` becomes `new
StorageCredentialVendorImpl(...)`, and `vendCredential(path,
privileges)` becomes `vendCredential(path, privileges, CredentialUse)`.
Code compiled against the old class fails to link
(`IncompatibleClassChangeError`), so embedders must rebuild against this
release. `FileOperations.getCleanupFileIO` also takes the dropped
object's ID now (`getCleanupFileIO(rootPath, resourceId, deadline)`), so
a `FileOperations` implementation or `fileOperationsDecorator` must add
the parameter and pass it through.

<details><summary><b>📐 Design notes &amp; details</b></summary>

**Stack.**
- This builds on #2059 (merged), which closes the server on SIGTERM.
- #2029 adds permission changes on top of this.
- #2030 then links a drop to its storage cleanup.

**Where records are made.** `StorageCredentialVendor` is split into an
interface and `StorageCredentialVendorImpl`, as with
`FileOperations`/`FileOperationsImpl`. When the sink is set, an audit
decorator wraps the vendor before `FileOperationsImpl` gets it. So it
sits above the credential cache and sees every credential.

**Purpose.**
- `vendCredential` takes a `CredentialUse`, which has only three values:
`CredentialUse.CLIENT`, `CredentialUse.SERVER`, and
`CredentialUse.cleanup(id)` for the dropped object's ID. So a purpose
and a resource ID cannot disagree, and there is no default.
- `FileOperationsImpl.getFileIO` passes `SERVER`, and `getCleanupFileIO`
passes `cleanup(id)`. Every other caller is a client-facing service and
passes `CLIENT`.
- Local `file:` paths have no credential, but a client's request is
still recorded, without `expires_at`, through every API. Iceberg's
`getFileIOConfig` used to return before the vendor for them; it now
calls the vendor and still returns an empty config. The vendor returns
empty credentials for local paths before the external-location lookup,
whose result it ignored for them anyway. The server's own local reads,
writes and cleanup are not recorded.
- A cleanup record's user is `system:storage-cleanup`.
- Its `resource_id` is the dropped object's ID, which the cleanup worker
passes to the credential vend.

**No secrets.** `location` keeps scheme, authority and path, and drops
the query, the fragment and user info. ABFS keeps `container@account`
when the part before the `@` looks like a container name (3 to 63
lowercase letters, digits and hyphens), and writes `[REDACTED]` in its
place otherwise.

**Failures.** Anything a sink throws is caught, and the request
continues. Failures are logged at ERROR in `server.log` at most once a
minute, with a count. A location that can't be parsed is logged at WARN,
and the record is written without that field. At startup, the server
fails if the sink class can't be loaded. It also fails if
`FileAuditSink`'s `audit` logger:
- is missing, or has no appender;
- is additive;
- doesn't enable INFO;
- has a file or console appender that ignores exceptions or has a
filter. Other appenders, for example one that ships records to a cloud
service, are not checked.

That keeps audit lines out of `server.log`.

**Lifecycle.**
- `UnityCatalogServer.close()` closes the sink once.
- SIGTERM runs `close()` (#2059), so the sink closes after the drain and
before Log4j stops, and drained requests' records are written.

**Log file.**
- The `audit` appender in `etc/conf/server.log4j2.properties` mirrors
`server.log`'s rollover. The Helm template rolls `audit.log` the same
way; there, `server.log` goes to the console.
- `createOnDemand` means no file appears while audit is off.
- `server.log` is unchanged.
- Archives follow `server.log`'s policy: hourly, kept for up to 7 days
or 1GB. The docs still say to ship `audit.log` continuously, since a
busy server cannot hold every record on disk for long.

**Helm.** No new values. Turn audit on with
`server.config.extraProperties`, and ship the file with a sidecar that
shares the log directory.

**Plugin compatibility.**
- `AuditRecord` is a final class with a builder, not a Java record, so
adding fields doesn't break compiled sinks.
- `time` and `action` are always set.
- New `AuditSink` methods are `default` only.
- `access` and `purpose` are the record's own `Access` and `Purpose`
enums (`CredentialUse` uses `AuditRecord.Purpose`), so the public record
depends on neither generated API types nor server-internal packages.

**Tests.**
- `AuditorTest`: the cleanup record and its exact JSON, vended through
the decorator together with a plain client vend (recorded as `CLIENT`
with `READ` access), location stripping (including ABFS), sink failures,
startup checks, and decorators forwarding default methods.
- `AuditCredentialVendingIntegrationTest`: an s3 catalog with
authorization off, a request ID on every record, plus server close.
- Purpose checks in `FileOperationsTest`. The integration test can't see
`SERVER`/`CLEANUP`, because its test-only `LocalMappingFileOperations`
serves those calls itself.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants