Repository navigation
[Server] Audit: record queued storage cleanup to link it to the drop - #2030
Conversation
de600db to
e106b49
Compare
e106b49 to
4440fdd
Compare
35ee04a to
4446154
Compare
|
/review |
1 similar comment
|
/review |
b068ae2 to
412cffb
Compare
|
/review |
1 similar comment
|
/review |
43ed6d0 to
504b6c2
Compare
|
/review |
30a0961 to
b0361b6
Compare
|
/review |
1 similar comment
|
/review |
3b0fc58 to
e6e03d5
Compare
## 🥞 Stacked PR Use this [link](https://github.com/unitycatalog/unitycatalog/pull/2059/files) to review incremental changes. - [**stack/uc-jvm-shutdown**](#2059) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2059/files)] ← _this PR_ - [uc-audit-records](#2028) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2028/files/4db7e939a4129e4ae46752bff44a5e628a20e44e..6ad246f2cb7a16489d89c910e2ec111c32848222)] - [stack/uc-audit-permissions](#2029) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2029/files/6ad246f2cb7a16489d89c910e2ec111c32848222..b4ccca6f0196d58cbf94d102ccfce35ffef018d7)] - [stack/uc-audit-cleanup-join](#2030) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2030/files/b4ccca6f0196d58cbf94d102ccfce35ffef018d7..e6e03d5c059544262cb0f79ff118fae34fc83e49)] --------- **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] 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** 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: - `exec`s 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`. <details><summary><b>📐 Design notes & details</b></summary> **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. </details> This pull request and its description were written by Isaac. --------- Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
e6e03d5 to
802d394
Compare
|
/review |
4 similar comments
|
/review |
|
/review |
|
/review |
|
/review |
|
/review |
## 🥞 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 #2028 is merged, so this PR's Files changed tab shows only its own changes. - [uc-audit-records](#2028) (merged) - [**stack/uc-audit-permissions**](#2029) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2029/files)] ← _this PR_ - [stack/uc-audit-cleanup-join](#2030) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2030/files/9c3a95bbdbbdd9933e3619a6c4710eb9475b22fe..978a53b5390cbe04aaee3e50564f4dbd732b3744)] --------- **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** Builds on #2028 (merged). The Java API changes of #2028 (`StorageCredentialVendor` is an interface, and `FileOperations.getCleanupFileIO` takes the dropped object's ID) are described there; this PR adds none. With audit and authorization on, the server also records each permission change: `GRANT` and `REVOKE` (including the implicit `OWNER` on create and the admin grant at first start), `CLEAR_RESOURCE_GRANTS` when an object is dropped, and `CLEAR_PRINCIPAL_GRANTS` when a user is deleted. A grant is recorded when it adds one. A revoke or a clear is recorded once it finishes without throwing, whether or not it removed a grant: with several servers on one database, a server can't always tell whether its own copy of the grants changed. If the database delete fails, the request fails and nothing is recorded. It also pins `dev.failsafe:failsafe` to 3.2.3. `iceberg-aws` brings Failsafe 3.3.2, which removed `ExecutionContext.getLastFailure`; jdbc-adapter 2.13.0 (the latest release) still calls it when a policy write keeps failing, so a failed revoke threw `NoSuchMethodError` instead of the adapter's `Error` wrapping the `SQLException`. `iceberg-aws` only uses Failsafe APIs that 3.2.3 has. A `TODO` links the upstream fix ([apache/casbin-jcasbin-jdbc-adapter#94](apache/casbin-jcasbin-jdbc-adapter#94), merged, not yet released); the pin goes once a release includes it. `JCasbinAuthorizerTest.failedDeleteThrowsTheDatabaseError` failed before the pin and passes with it. <details><summary><b>📐 Design notes & details</b></summary> **Fields.** Each record has: - the acting user; - `principal_id`, whose grants changed; - `resource_id`; - `privilege`, using the API's names, for example `USE CATALOG`. **Where.** - An `AuditingAuthorizer` decorator wraps `JCasbinAuthorizer` before `initializeAdmin`, so the admin grant is recorded. - A grant is recorded when the delegate returns `true`. A revoke or a clear is recorded whenever the call returns, because with several servers on one database the returned flag only says whether this server's in-memory policy changed. - It forwards `refreshAuthorizations` and `close`. - It is package-private and only reachable through `Auditor.wrap(UnityCatalogAuthorizer)`. - With authorization off (`AllowingAuthorizer`), grants are no-ops and nothing is recorded. **User outside a request.** A record made without a request names the service user `system:server`. Today that's only the admin grant at startup. Cleanup credentials keep `system:storage-cleanup`. **Tests.** `SdkTableAccessControlCRUDTest.auditRecordsGrantsRevokeDropAndUserDelete` covers: - grant and repeated grant; - a revoke sent twice, with the resource ID checked, since the second finds nothing to remove and is still recorded; - the admin grant; - OWNER on create; - a table credential with the admin as user; - grants cleared by a drop and by a user delete; - `principal_id` in the record and in the JSON. The decorator check in `AuditorTest` covers the new class. </details> This pull request and its description were written by Isaac. --------- Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
When a drop queues a storage cleanup, the server writes a QUEUE_CLEANUP audit record after the drop's transaction commits. Its resource_id is the dropped object's ID, the same ID the cleanup's CLEANUP credential records carry, so the two can be matched. Claim and CleanupFailureReport move into the new CleanupTaskRepository interface, which AuditingCleanupTaskRepository wraps. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
f6e3c3e to
c094e76
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Thanks for this. The after-commit mechanism checks out against Hibernate 6.5.0: the callback sees STATUS_COMMITTED only on commit, and the guard is needed because commit() rolls back and rethrows when a synchronization throws. No blockers.
A few notes:
- PR description, Compatibility paragraph: it lists the StorageCredentialVendor, getCleanupFileIO and 5-argument Repositories changes, which are already on main from #2028 and #2029. Could it name only what this commit changes?
- Docs, configuration.md line 241 (outside this diff): the sentence that file: storage writes no record now sits next to the new QUEUE_CLEANUP record for file: drops. Could it say that background cleanup of file: storage writes no record, so it is not read as covering the drop?
| credential records do not carry it. | ||
| `CLEAR_PRINCIPAL_GRANTS`). On a `QUEUE_CLEANUP` record and on a `CLEANUP` credential, the ID of the | ||
| dropped object, so match the two on `resource_id`; they can be written in either order. Other | ||
| credential records do not carry it. A `CLEANUP` record can have no matching `QUEUE_CLEANUP` |
There was a problem hiding this comment.
[AI Assisted] Could the unmatched-record note also list the cases that leave a CLEANUP record without a QUEUE_CLEANUP? That covers the process stopping after the drop commits, the sink throwing, and an unknown commit outcome. Consumers would then not treat these as tampering.
There was a problem hiding this comment.
Thanks. The note says "for example", and the best-effort paragraph just below it already covers a failing sink and shutdown, so I kept it as is. I left out the unknown-commit-outcome case on purpose: in Hibernate 6.5 a failed JDBC commit marks the transaction FAILED_COMMIT and never reaches the after-commit callback as STATUS_UNKNOWN, so adding it would describe a path that doesn't happen.
| StorageCleanupTaskDAO task = | ||
| delegate.create(session, resourceType, resourceId, resourceName, storageLocation); | ||
| String location = task.getStorageLocation(); | ||
| auditor.afterCommit(session, () -> auditor.recordQueueCleanup(resourceId, location)); |
There was a problem hiding this comment.
[AI Assisted] The resource_id join is what this PR is for, but no test checks it end to end. Could one existing cloud cleanup test assert that the CLEANUP credential's resource_id equals the QUEUE_CLEANUP record's? It holds today, since the task ID flows into both, but nothing would catch a change to either side.
There was a problem hiding this comment.
Each step of the join is already asserted, in separate tests: QUEUE_CLEANUP against the task ID (the cleanup suites' @AfterEach), the claim against the task (StorageCleanupTaskRepositoryTest), the worker passing it on (StorageCleanupWorkerTest), the credential request (FileOperationsTest) and the CLEANUP record (AuditorTest). To check, I replaced the ID with a random one in the decorator, the worker and FileOperationsImpl: 20 tests went red, at least one in each of those classes. A single end-to-end assertion would need a real cloud credential request, which the cleanup E2E test mocks out, so I left it.
…ecord Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
|
/review |
1 similar comment
|
/review |
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updatedDescription of changes
Builds on #2029. Cleanup credentials are recorded as
system:storage-cleanup, so they don't say who dropped the object. This PR recordsQUEUE_CLEANUPwith the dropping user when a drop queues storage cleanup. Itsresource_idmatches the cleanup's credential records. It is written only after the drop commits.Compatibility:
Repositories.getStorageCleanupTaskRepository()now returns the newCleanupTaskRepositoryinterface, and itsClaimandCleanupFailureReportrecords moved there fromStorageCleanupTaskRepository. Rebuild against this release: the nested class names, the getter's return type and theStorageCleanupWorkerconstructor changed. UseCleanupTaskRepository.ClaimandCleanupTaskRepository.CleanupFailureReport.📐 Design notes & details
Where.
StorageCleanupTaskRepository.createis the only place cleanup tasks are made: table, volume, model and model-version drops. The class keeps its name and implements the newCleanupTaskRepositoryinterface, so an audit decorator can wrap it.RepositoriesandStorageCleanupWorkeruse the interface type.After commit. The decorator registers a Hibernate
Synchronizationand records onSTATUS_COMMITTEDonly. With UC's resource-local transactions, Hibernate reports a rollback asSTATUS_UNKNOWN, which is why the check is "committed" rather than "not rolled back". Hibernate rethrows exceptions fromafterCompletionout ofcommit(), which would turn a committed drop into an error. So the whole callback is guarded, and failures are logged like other audit failures.Tests.
SdkTableAccessControlCRUDTest.auditRecordsGrantsRevokeDropAndUserDelete: a drop writesQUEUE_CLEANUPand thenCLEAR_RESOURCE_GRANTS, both from the admin.AuditorTest.afterCommitRunsOnlyOnCommitAndNeverFailsIt: on a real session, a rolled-back transaction runs nothing, and an action that throws does not fail the commit.@AfterEachthat each task has exactly oneQUEUE_CLEANUPrecord with its ID and location, across rolled-back and cascading drops (for exampletaskInsertFailureRollsBackTableDeletion).AuditorTest.This pull request and its description were written by Isaac.