Repository navigation
[Server] Shut down gracefully on SIGTERM - #2059
Conversation
|
/review |
1 similar comment
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[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.
|
/review |
|
/review |
1 similar comment
|
/review |
|
/review |
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]>
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]>
Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
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]>
78d8ab1 to
561d9a1
Compare
|
/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]>
|
/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]>
|
/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]>
… 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 & 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]>
## 🥞 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 & 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]>
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updatedDescription 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-serverrunsjavaas a child of the shell, sodocker stopwaits 10s and kills it. This PR:execs the JVM frombin/start-uc-server, so it receives SIGTERM;close()from Armeria's shutdown hook: it stops the storage cleanup, lets in-flight requests finish for up toserver.shutdown-timeout, and closes the rest of the server (blocking executor, authorizer, Hikari pool). Log4j stops last;javacommand line, so lines logged during the drain are kept;etc/conf/hibernate.propertiesand the Helm chart) fromDB_CLOSE_DELAY=-1toDB_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.mdnow documentsserver.shutdown-timeout, anddocs/server/deployment.mdthe 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, givedocker stop15s or more, and raise it andterminationGracePeriodSecondswhen you raiseserver.shutdown-timeout.📐 Design notes & details
Before and after, on the Docker image:
start-uc-server(bash), withjavaas a childjavadocker stopserver.logat shutdownUnity Catalog server stopped., then Hikari'sShutdown completed.Kafka (
bin/kafka-run-class.sh), Pulsar (bin/pulsar), Elasticsearch (its Docker entrypoint) and Polaris (run-java.sh) alsoexecthe JVM.Order on SIGTERM. Everything runs on Armeria's hook thread, so it finishes before the JVM exits.
closeOnJvmShutdown(unityCatalogServer::close)runsclose()as itswhenClosingstep.close()stops the cleanup worker, drains requests throughserver.stop(), then drains the blocking executor with the time left and closes the other resources. SIGTERM andclose()share one shutdown path.server.close()then finds the server stopped and returns at once.whenComplete, so it stops even ifclose()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, andclose()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 fromstop(). If the server fails to start,maincloses it and then stops Log4j, since the script turns Log4j's own hook off.Startup window. The hook is registered after
start(), soclose()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
javaline, 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 whenUnityCatalogServerloads, and registers its hook then. The server appliesetc/conf/server.log4j2.propertieslater.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=0closes the database whenclose()closes the pool. It must be in the URL, not just-1removed: H2 stores the delay in the database file, so a database first opened with-1, including the shippedetc/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:
bin/start-uc-server, 3 runs: the script's PID isjava; after SIGTERM the process exits with 143 in about 2.4s andserver.loghasUnity Catalog server stopped., whichclose()logs after the drain, and Hikari'sShutdown completed.from its last step. Started with plainjava(no flag), both lines were missing in 2 of 2 runs;DB_CLOSE_ON_EXIT=FALSE. A database created withDB_CLOSE_DELAY=-1(as the shipped sample was) and reopened without it still reports-1and stays open after its last connection closes; reopened withDB_CLOSE_DELAY=0, it closes, and a second process can open it. A catalog created before SIGTERM is still there after a restart;UnityCatalogServerTestandUnityCatalogServerShutdownTestpass.This pull request and its description were written by Isaac.