Compare commits

...

29 Commits

Author SHA1 Message Date
Cursor Agent e7b5b29abf fix(ci): retry Jepsen unit tests when Clojars drops a jar
The checker job failed while transferring jepsen and generator from Clojars. Retry the download and test three times before reporting a failure.

Co-authored-by: RustFS <hello@rustfs.com>
2026-11-27 18:16:48 +00:00
Cursor Agent 4fee593499 fix(ci): register the Jepsen unit workflow
Allow the results.edn filename, clear checkout credentials, install Leiningen before the same step calls it, and record the workflow as an event-driven check with no freshness monitor.

Co-authored-by: RustFS <hello@rustfs.com>
2026-11-27 16:32:40 +00:00
Cursor Agent 7a9024ab8b test(jepsen): add 1.0.7 consistency suite for 4x4 and 3x2
Add a Clojure Jepsen project that installs the official 1.0.7 zip and checks single-key object histories with Elle and Knossos under the stock Nemesis. The Mac mini runbook runs the 16-drive cluster, then the 6-drive cluster, and does not start both at once.

Co-authored-by: RustFS <hello@rustfs.com>
2026-11-27 16:20:26 +00:00
Chris An 17808b9fe5 fix(heal): stop retrying committed deletes on generation conflicts (#9685) 2026-11-27 23:06:27 +08:00
Chris An c3f2636c6b fix(security): drop expired rsa 0.9.10 advisory exception (#9678)
openidconnect 4.1.0 is the only consumer of rsa 0.9.10 and has no
released rsa 0.10 build. Vendor that crate, retarget JWS verification
to rsa 0.10, and remove the exception that expired on 2026-07-31.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Chris An <overtrue@users.noreply.github.com>
2026-11-27 21:27:55 +08:00
Chris An 2e5e99a994 fix(admin): harden admin authz context, scoping, and input validation (#9677)
Propagate verified proxy transport/client context and request-scoped
server context slots across admin authentication and authorization,
including task-scoped IAM root credential lookup so multi-instance
embedded servers do not leak ambient credentials across server domains.

Fail closed with InvalidArgument on non-empty AddOrUpdateUserReq.policy
in both the add-user admin handler and IamSys::create_user, normalizing
empty policy strings to None before persistence and site-replication
hooks.

Wrap GetKmsStatusHandler authorization denials in KmsAdminAudit::gate_admin
using KmsAdminOperation::Status, apply bucket-scoped authorization
symmetrically across bucket quota write and read handlers, and restore the
guardrail comment documenting direct is_allowed evaluation in
service_account.rs.

Enable bucket and object resource matching for scoped admin actions
(SetBucketQuota, GetBucketTarget, SetBucketTarget, InspectData) in the
policy evaluator and wire resource-scoped authorization into replication
remote-target and inspect-data handlers. Align bulk access-key routes on
ListUsersAdminAction for cross-user queries and enforce strict S3 bucket
name validation on quota and table-catalog warehouse parameters.

Refs: rustfs/backlog#1469, rustfs/backlog#1246, rustfs/backlog#1886, rustfs/backlog#2526
2026-11-27 20:20:08 +08:00
Chris An f9a9aa75d5 test(bucket): align PutBucketPolicy audit status expectation with 204 (#9676) 2026-11-27 20:19:54 +08:00
Chris An b9d958ee82 fix(scanner): walk directories with an explicit stack (#9674)
Port the scanner folder walker from #9623 onto current main so nested
directory polls no longer grow the worker stack. Keep later main
behavior for object metadata, lifecycle, heal discovery, and child
errors.

Refs rustfs/backlog#3293

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Chris An <overtrue@users.noreply.github.com>
2026-11-27 19:15:57 +08:00
Chris An 365ef6d557 fix(swift): bound bodies, enforce quotas and default SSE/KMS authz (#9667)
Harden the Swift protocol layer across request body boundaries, storage
quotas, FormPost redirects, and server-side encryption:

- Bound control-plane and streaming request bodies at the HTTP frame and
  decompression boundaries (bulk-delete, bulk-extract tar/gzip/bzip2,
  FormPost multipart, SLO PUT) and cap bulk path/error/part/field counts.
- Enforce MAX_OBJECT_SIZE for unknown-length and mismatched-length object
  uploads via a contract-safe streaming byte-cap reader, reject negative or
  malformed Content-Length headers, and enforce container byte/count quotas
  across PUT, bulk extract, FormPost, SLO, DLO, and COPY with serialized
  in-flight reservations and immediate usage-overlay updates.
- Reject unauthenticated or expired FormPost requests with 401 without
  issuing a redirect, validate signed redirect schemes, restrict unsigned
  redirect_error targets to the signed redirect origin, and preserve binary
  upload payloads losslessly.
- Honor bucket default SSE-S3/SSE-KMS on Swift writes (failing closed on
  unreadable encryption config or missing Content-Length) and authorize
  kms:Decrypt before DEK unwrap on Swift GET and COPY.
- Fix an unconditional SessionContext import in dummy_storage.rs so
  rustfs-protocols compiles under both default and swift features.

Refs: rustfs/backlog#1471, rustfs/backlog#1474, rustfs/backlog#1473, rustfs/backlog#2702
2026-11-27 19:15:28 +08:00
Chris An 78486916d5 ci(security): gate advisories with time-bounded exception registry (#9663)
Add .config/advisory-exceptions.toml (schema_version=1) and scripts/security/check_advisories.py to enforce pinned cargo-deny (0.20.2), advisory-db freshness (<=24h verified cache fallback), bidirectional deny.toml alignment, 90-day max UTC validity windows, exact version scope matching, and PR base-diff approval checks.

Wire security-advisories into ci.yml (ALWAYS_JOBS, required-checks, alert-on-failure, PLAN_CONTRACT=10), align daily audit.yml while preserving all four cargo-deny categories, and register --self-test in make script-tests.

Historical RUSTSEC-2023-0071 (transitive rsa 0.9.10 via openidconnect 4.1.0; direct rsa upgraded to patched 0.10.0 in PR #9492) retains its expired 2026-07 review window and intentionally fails closed until maintainer risk acceptance or upstream upgrade lands.

Refs: rustfs/backlog#2668
2026-11-27 18:59:33 +08:00
Chris An c2b92cfb58 fix(gateway): harden post-cutover S3 auth, body limits, and isolation (#9660)
fix(gateway): harden post-cutover S3 auth, body limits, and context isolation

Address nine post-cutover parity and isolation regressions against rustfs/gateway:
- Keep expired STS sessions enabled in gateway-adapter so gateway returns 400 ExpiredToken (retiring c-cred-0020 ruling) while disabled/invalid STS and expired service accounts remain disabled.
- Remove pre-auth 20 MiB ControlBodyDigestService buffering from S3/gateway listeners, preserving console-listener route isolation via ConsoleListenerRouteService and post-auth SigV2 Content-MD5 checks on DeleteObjects and non-empty config PUTs.
- Stop copying unsigned wire x-amz-server-side-encryption* headers into PostObjectPolicyHeaders during preflight authorization.
- Source live_root() credentials and token signing key strictly from ServerContextSlot rather than process globals.
- Configure max_framed_upload_bytes(5 GiB) and upload_object_ceiling(5 GiB) on GatewayStack.
- Initialize S3 and ListObjects metrics on GatewayStack::assemble.
- Inject ServerContextSlot into NativeConsoleEdgeService request extensions.
- Scope ProtocolStorageClient is_owner and list_buckets IAM lookup to ServerContextSlot without breaking direct-write BucketGenerationGuard invariants.
- Wire verify_paths_double_encoded_under(TABLE_CATALOG_PREFIXES) in native admin, record 204 NO_CONTENT on PutBucketPolicy audit entries, and set explicit 500 status on HeadObject ErrMeta.
2026-11-27 18:59:13 +08:00
Chris An fbe7471ba6 docs(security,kms): add KMS version policy and close doc/compat gaps (#9661) 2026-11-27 17:29:38 +08:00
Chris An def2fb7e47 fix(storage,obs): bound read memory, log disk growth, and part staging (#9668) 2026-11-27 16:41:58 +08:00
Ramakrishna Chilaka d838137c3a perf(ecstore): reuse multipart part-txn lock handles and pre-rename stamps (#9666) 2026-11-27 06:14:01 +00:00
Chris An 52377c1478 ci(security): pin cache-cargo-install-action v3.0.8 for sha pinning (#9662)
Update taiki-e/cache-cargo-install-action in .github/workflows/ci.yml to v3.0.8 (9ee83daaa7b96a6fab930949ecf1122bba04a389), which pins its nested actions/cache reference to commit SHA 55cc8345863c7cc4c66a329aec7e433d2d1c52a9 (v6.1.0).

This removes the sole unpinned nested composite action across all 39 unique third-party actions in the repository and unblocks enabling GitHub repository sha_pinning_required.

Refs: rustfs/backlog#1602
2026-11-27 01:51:12 +00:00
Peter van Mourik 7d41d22e5f fix(ecstore): skip rebalance re-copy when target holds the version (#9588)
* fix(ecstore): skip rebalance re-copy when target holds the version

A rebalance that stops after an object version is committed on the target pool and before its source copy is removed leaves that version in both pools. The next run uploaded every part of a multipart object again and only found the existing copy when the create-only completion was refused, so a retry cost the whole object.

Look up the pool the copy would be written to before starting the multipart upload, and settle on it when it already holds the strictly equivalent version. Decommission with a capacity owner already does this; callers without one now do too. A lookup that fails or finds no equivalent copy falls through to the unchanged copy path.

* fix(ecstore): require write quorum before skipping the rebalance re-copy

The pre-check settled on the target copy whenever an object read returned the equivalent version. That read answers from read quorum: on a 2+2 set with two drives offline it still returns matching metadata, the entry reported the version as moved, and the source copy was removed while the target held two readable shards. The copy path it replaced needs a write quorum to start, so it kept the source in that state.

Count the drives of the target set that hold the version in the committed data directory, once per drive slot and in one fanout, and settle only when a write quorum of them agree. A copy below that leaves the decision to the unchanged copy path.

Add a rebalance entry test on a 2+2 target: with two target drives offline the source survives and stays readable; with the drives back the entry completes on the committed copy without rewriting it.

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 05:17:59 +08:00
hector 08575786c6 ci: remove schedule-only rio-v2 lanes from CI (#9652)
The rio-v2 test, debug-binary, and e2e jobs in ci.yml ran only on the
nightly schedule and manual dispatch. Drop them, the ci-feat-rio cache
warm job that existed for them, and the merge-gate entries that named
them. The rio-v2 feature and minio-interop workflow stay. Default debug,
e2e, and S3 lanes are unchanged.

Bump the CI plan contract so a base planner that still lists those jobs
cannot authorize the new required set.

Co-authored-by: hector <majinghe@users.noreply.github.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-27 05:17:00 +08:00
Chris An ac6253cf38 fix(policy,s3select,rpc): harden policy, S3 Select, and RPC auth (#9640)
* fix(policy): scope NotAction Allow to named action families

Confine Allow statements built from NotAction to the action families named in their exclusion list so S3 NotAction policies on wildcard or bucket resources cannot implicitly grant admin, STS, or KMS actions. Fail closed when both Action and NotAction are empty, preserve explicit Deny + NotAction reach across all action families, and preserve explicit admin NotAction coverage for sibling admin actions.

Refs: rustfs/backlog#3321

* fix(policy,utils): eliminate exponential wildcard matching

Replace recursive backtracking in wildcard matching (rustfs-policy and rustfs-utils) with iterative O(name.len())-space dynamic programming that collapses consecutive '*' wildcards and preserves allocation-free fast paths for literal and single-'*' patterns. Also cap versioning ExcludedPrefixes count (100) and byte length (1024) in validate_bucket_versioning_update as defense in depth.

Refs: rustfs/backlog#3318

* fix(policy): prefer parent over raw sub for aws:userid variable

Share a single resolve_userid_values helper between VariableResolver::resolve and resolve_multiple that prefers the issuer-scoped parent claim over raw sub, aligning the ${aws:userid} policy variable with the aws:userid condition key derived in auth facts while retaining sub as a fallback when parent is absent.

Refs: rustfs/backlog#3339

* fix(policy): treat anonymous-matching principals as public

Add Principal::is_public() matching either '*' or the empty anonymous account '' through the same wildcard matcher used during request authorization, and switch execute_put_bucket_policy and execute_get_bucket_policy_status to use it so empty and leading-'?' principals cannot bypass BlockPublicPolicy or evade public status classification.

Refs: rustfs/backlog#3357

* fix(s3select): restrict SQL functions to an explicit allowlist

Replace unfiltered DataFusion default scalar, aggregate, and window UDF registration in SimpleFunctionMetadataManager with an explicit S3 Select allowlist, register allowlisted scalar aliases directly, and remove the session scalar-function fallback from MetadataProvider::get_function_meta.

Wrap retained expanding scalar functions (concat, concat_ws, to_char) and any manually registered count-sized functions (repeat, lpad, rpad) with a pre-allocation result-size guard that also re-wraps scalar UDFs produced during expression simplification.

Refs: rustfs/backlog#3317

* fix(s3select): bound SQL operator and nesting depth at parse

Add BoundedRustFsDialect enforcing a per-parse infix/postfix operator budget (MAX_SELECT_OPERATORS) via Dialect::parse_infix returning ParserError::RecursionLimitExceeded, and wire it into both ExtParser::parse_sql and legacy_json_source_from_input.

Also bound set-operation keyword counts before parsing (preventing deeply nested SetExpr chains from overflowing on drop) and bound nested field-access chains during statement preparation.

Refs: rustfs/backlog#3319

* fix(s3select): bound uncompressed record sizes and decoding

Apply RecordSizeTracker (MAX_SELECT_RECORD_BYTES) across uncompressed plain, ScanRange, and ScanRange header reads in EcObjectStore, recognizing CR, LF, and CRLF line endings for default CSV inputs without a custom RecordDelimiter.

Bound session batch sizes and disable batch coalescing for CSV and JSON Lines, replace DataFusion's unbounded stock listing table scan with a byte-bounded, memory-pool-accounted DelimitedSelectTable, keep multi-record JSON Lines schema sampling within the session memory pool budget, and add a StreamFilterOutput physical optimizer rule so FilterExec streams filtered batches without re-coalescing.

Refs: rustfs/backlog#3348

* fix(rpc): gate gRPC boot-epoch proofs on verified signatures

Stop computing and attaching secret-keyed boot-epoch, replay-cache, and msgpack capability response proofs before gRPC authentication runs in RpcRequestPathService::call.

Gate proof generation on an RpcSignatureVerified request marker raised by check_auth only after the internode HMAC signature has verified, including post-HMAC rejections (stale boot epoch, replay-scope retries, replay detection, and replay-cache/background admission resource exhaustion) required for cluster recovery.

Verify the method-bound v2 HMAC signature before returning replay_scope_required in verify_tonic_rpc_signature_with_policy so unsigned, legacy-only, or forged callers never trigger a post-HMAC rejection reason or consume replay-cache capacity.

Refs: rustfs/backlog#3326

* fix(keystone): namespace parent_user by Keystone user ID

Set Credentials.parent_user in KeystoneAuthProvider::keystone_token_to_credentials to the namespaced Keystone identity (keystone:<user_id>, matching access_key) instead of the bare Keystone username.

This prevents an external Keystone username from colliding with a local IAM user or the root access key in service-account ownership checks and the is-admin handler while keeping the username available in Credentials.name and claims["keystone_username"].

Update the keystone unit tests and HTTP/3 external stack test expectations, and add regression coverage verifying colliding usernames are never placed in parent_user.

Refs: rustfs/backlog#3362

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-27 05:16:41 +08:00
Hauser Zhi 5d8974ea40 fix(ecstore): bound PUT waits on a departing peer (#9642)
* fix(ecstore): stop bucket presence checks at read quorum

A metadata-only bucket probe can finish after the existing read quorum has confirmed the volume. Preserve full error reduction when quorum has not been reached and keep ordered bucket info and mutation callers on their existing path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): bound PUT rename dialing after write quorum

Share a post-quorum connection deadline across remote rename producers. Unresolved connections can be skipped before dispatch while active mutations drain under the normal namespace owner.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): simplify quorum probes and rename fanout

Keep presence-only probes typed as unit results and share their cross-set error reduction with bucket-info queries. Reuse one path owner across disk rename tasks and allocate a connect deadline only when there is a spare.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): bound PUT rename preparation after quorum

Apply a single pre-dispatch deadline to remote routing and permit admission. Encode the request once those resources are available and keep existing ownership for dispatched mutations.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test: fix SSE-C lint and native multipart copy-heal setup

Count warning matches directly and bind native multipart staging to the real bucket incarnation while preserving the historical version fixture.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(ecstore): qualify retention fixture metadata type

The default test build includes this fixture without the test-util imports.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(scanner): seed checkpoint owner metadata directly

Keep the production object threshold and physical checkpoint barriers while avoiding a full PUT for every fixture entry.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(ecstore): serialize Windows trash cleanup per entry

Keep the per-path lease in the physical deletion worker and compile Unix-only test helpers only on their supported platforms.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 03:56:43 +08:00
Hauser Zhi 594488a650 fix(sosapi): distinguish pending and invalid usage proof (#9655)
* fix(sosapi): distinguish pending and invalid usage proof

Expose neutral bucket usage states from the existing snapshot cache. Maintain the legacy scalar projection and map only pending certification to undefined SOSAPI usage.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* ci(test): isolate three disk-bound ECStore probes

Reserve nextest capacity for the physical Apply barrier and the two same-name multipart probes in the CI profile. Preserve their deadlines, assertions, and internal concurrency.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 03:15:34 +08:00
Hauser Zhi 0ef63577e8 fix(s3): correct Object Lock read responses (#9654)
* fix(s3): correct Object Lock read responses

Classify missing bucket, key, version, and lock metadata through the shared Object Lock read path. Reuse bucket metadata authority to avoid a duplicate namespace probe on Legal Hold reads.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(ecstore): drain fixture writes before cache publication

Wait for the fixture PUT rename fanout before exercising the cache generation fence. Report a read that ends before the publication barrier immediately.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 01:29:57 +08:00
Hauser Zhi 2e9e206d02 fix(ecstore): reject startup without a local endpoint (#9638)
* fix(ecstore): reject startup without a local endpoint

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* perf(ecstore): resolve startup DNS once per host

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(ecstore): reject zero-port storage endpoints

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(ecstore): bound startup DNS by the topology deadline

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(server): exit promptly after a startup DNS timeout

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* perf(ecstore): skip unused endpoint identity scans

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(log-analyzer): track startup DNS failures

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* test(ecstore): preserve fresh copy-heal upload initiation

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

---------

Signed-off-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 01:18:31 +08:00
Hauser Zhi 4eb6f3d624 perf(obs): export stage peaks with less summary contention (#9658)
Track the maximum of each sampled stage window. Keep the existing
summary API and row format while exposing the maxima separately.
Unlock before sorting and format stage rows into shared buffers.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:37:22 +08:00
Hauser Zhi 9f536da60d fix(ecstore): preserve grouped directory fsync admission (#9657)
Keep each writer's disk permit with the physical directory sync
and acquire one global permit per admitted batch. Route non-inline
grouped commits through the same admission and rollback path.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:16 +08:00
Hauser Zhi a66c7c986f fix(s3): skip redundant reads for plain bulk deletes (#9649)
* fix(s3): skip redundant reads for plain bulk deletes

Plain unversioned DeleteObjects entries use source metadata read under the storage write lock. Skip the advisory read that duplicates lock acquisition per request entry, preserve condition and version boundaries, and exercise 16 duplicate DELETE entries while a writer holds the key.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(s3): use the storage facade for the delete barrier

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(s3): skip redundant bulk preflight for suspended versions

Apply the same locked-source path to unconditioned, versionless entries in suspended buckets. Verify that duplicate requests reach storage while a writer owns the object and that the suspended delete publishes its marker.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(test): import the delete barrier through the public API

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:11 +08:00
Hauser Zhi dbb9ca60fc fix(perf): validate steady Warp rates and tail latency (#9637)
* fix(perf): validate steady Warp rates and tail latency

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(server): count plaintext SSE-C warnings directly

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:05 +08:00
Hauser Zhi 873f728e55 fix(ecstore): size workers and batch deletes by available CPUs (#9636)
* fix(ecstore): size workers and batch deletes by available CPUs

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): route delete markers only when needed

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:00 +08:00
Hauser Zhi 94f8ec5706 perf(ecstore): diagnose PUT snapshots and trim bucket stat allocations (#9644)
* feat(obs): split single PUT Object Lock snapshot timings

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): borrow bucket names during stat fanout

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(ci): restore SSE-C lint and storage regression coverage

Require quorum evidence before treating missing multipart part directories as empty. Keep historical object times separate from upload initiation and align the IAM, quota, namespace lock, and retention fixtures with their current contracts.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(e2e): expect tagging authorization on tagged writes

Backport the OPA contract assertions from 961b0c79c8 and their formatting from c269a1233d.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:34:52 +08:00
Hauser Zhi 9a65ac95f7 fix(ecstore): bound compressed GetObject range reads (#9639)
* fix(ecstore): bound compressed GetObject range reads

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(ci): tighten compressed reader error ratchet

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): stream object ranges directly to callers

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(ecstore): decode compression indexes without reframing

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(rio): reuse verified plaintext block buffers

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(server): count SSE-C warnings without collecting

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* test(admin): distinguish explicit and implicit IAM denials

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:34:45 +08:00
300 changed files with 46162 additions and 6002 deletions
+50
View File
@@ -0,0 +1,50 @@
# Machine-enforced RustSec advisory exception registry.
#
# Validated by `scripts/security/check_advisories.py` in both `ci.yml`
# (`security-advisories`, required via `Test and Lint`) and daily `audit.yml`.
#
# Rules (rustfs/backlog#2668):
# - Every `[advisories].ignore` entry in `deny.toml` must match an entry here
# bidirectionally; comment-only or untracked ignores fail closed.
# - Timestamps use strict UTC RFC 3339 (`YYYY-MM-DDTHH:MM:SSZ`).
# - Maximum validity window is 90 days (`expires_at - approved_at <= 90d`).
# - Expired exceptions fail closed; renewals require explicit maintainer review
# and cannot be auto-extended or self-approved in a PR.
schema_version = 1
[[exceptions]]
advisory_id = "RUSTSEC-2026-0543"
crate = "chrono"
affected_versions = "=0.4.45"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0555"
crate = "chrono-tz"
affected_versions = "=0.10.4"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0542"
crate = "humantime"
affected_versions = "=2.4.0"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
-14
View File
@@ -59,20 +59,6 @@ failures = [
]
expires = 2027-02-01
# Tracked IAM gap (R-065): https://github.com/rustfs/backlog/issues/2684#issuecomment-7163283798
[[ruling]]
case = "c-cred-0020"
ledger = "R-065"
reason = "Tracked IAM gap (rustfs/rustfs#9559, rustfs/backlog#2684): expired STS session token returns 403 InvalidAccessKeyId instead of 400 ExpiredToken."
failures = [
"[expect/status] at /expect/status: exchange #1, attempt 1: expected status 400, observed 403",
"[expect/error.code] at /expect/error/code: exchange #1, attempt 1: expected <Code>ExpiredToken</Code>, the body carried <Code>InvalidAccessKeyId</Code>",
"[expect/body.exact_utf8] at /expect/body: exchange #1, attempt 1: bodies differ at byte 52 (expected 196 bytes, observed 200 bytes)\n expected: …F-8\\\"?>\\n<Error><Code>ExpiredToken</Code><Message>the session …\n observed: …F-8\\\"?>\\n<Error><Code>InvalidAccessKeyId</Code><Message>The Ac…",
"[expect/body.not_contains_utf8] at /expect/body: exchange #1, attempt 1: the body must not contain \"InvalidAccessKeyId\", found at byte 52",
]
expires = 2027-02-01
# Outer CORS middleware and HTTP/2 OPTIONS parity: https://github.com/rustfs/backlog/issues/2684#issuecomment-7163283798
[[ruling]]
+3
View File
@@ -43,6 +43,7 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_internode_msgpack_peer_canary.py
./scripts/test_internode_msgpack_peer_canary_runner.sh
./scripts/test_object_batch_bench_enhanced.sh
$(RUSTFS_PYTHON_BIN) ./scripts/test_warp_raw_quality.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_inline_docker_lab.py
./scripts/test_package_service_scripts.sh
./scripts/test_hotpath_warp_ab_gate.sh
@@ -64,6 +65,7 @@ script-tests: ## Run shell script tests
./scripts/test_fuzz_runner.sh
./scripts/test_python_bin.sh
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_doc_paths.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_check_kms_format_versions.py
./scripts/check_embedded_secrets.sh --self-test
./scripts/check_s3s_footprint.sh --self-test
./scripts/test_check_test_count_ratchet.sh
@@ -92,6 +94,7 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_ci_merge_queue.py
$(RUSTFS_PYTHON_BIN) -m unittest discover -s scripts/ci -p 'test_*.py'
$(RUSTFS_PYTHON_BIN) ./scripts/check_security_coverage.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/security/check_advisories.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/check_scheduled_validation_freshness.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/test_security_workflow.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_nightly_candidate.py
+12
View File
@@ -416,6 +416,18 @@ threads-required = "num-test-threads"
filter = 'package(rustfs-ecstore) & test(/^store::object::tests::(canceled_create_retains_usage_cleanup_namespace_owner|batch_delete_excludes_recovery_on_nonzero_pool|delete_excludes_recovery_with_(disjoint|identical|overlapping)_pool_lock_clients)$/)'
threads-required = "num-test-threads"
# Isolate the physical Apply barrier and same-name multipart lock probes from
# competing disk fixtures. Keep their deadlines and internal concurrency.
[[profile.ci.overrides]]
filter = """
package(rustfs-ecstore) & (
test(=core::pools::native_recovery::integration_tests::pool_meta_native_physical_runtime_fork_after_apply_latches_original_gate)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_key_writes_succeed_on_unversioned_versioned_and_hard_quota_buckets)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_object_write_lock_does_not_block_other_keys_on_versioned_bucket)
)
"""
threads-required = "num-test-threads"
# These eight-disk decommission fixtures exercise concurrent retries,
# free-version cleanup, and real capacity probes under production lock deadlines.
# Reserve the run's capacity so unrelated IO cannot exhaust those budgets.
+21
View File
@@ -1097,6 +1097,27 @@
"policy_reason": "Preserve operator-disabled state; enabling requires a separate policy decision.",
"origin": "baseline"
},
{
"workflow": ".github/workflows/jepsen-unit.yml",
"name": "Jepsen unit",
"roles": [
"pr"
],
"events": [
"pull_request",
"push"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "jepsen-unit.yml",
"disposition": "Runs the Jepsen checker unit tests. It does not start a RustFS cluster.",
"monitor_reason": "Runs when the Jepsen project changes and has no periodic freshness obligation.",
"origin": "added"
},
{
"workflow": ".github/workflows/manual-main-packages.yml",
"name": "Manual Linux packages",
+1 -1
View File
@@ -43,7 +43,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
`Swatinem/rust-cache` builds its key from the OS, architecture, toolchain and lockfile. It does not include the runner label or image, so a cache written on an `sm-standard-4` pod and one written on `ubuntu-latest` would overwrite each other under the same `shared-key`.
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-rio`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every reader in `ci.yml` and `reference-parity.yml` name it.
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted`, `e2e-upgrade-server-hosted`, `e2e-upgrade-tests-hosted`).
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
+33 -2
View File
@@ -21,6 +21,9 @@ on:
- '**/Cargo.toml'
- '**/Cargo.lock'
- 'deny.toml'
- '.config/advisory-exceptions.toml'
- 'scripts/security/check_advisories.py'
- 'scripts/security/test_check_advisories.py'
- '.github/actions/**'
- '.github/workflows/**'
- 'scripts/release/**'
@@ -46,6 +49,9 @@ on:
- '**/Cargo.toml'
- '**/Cargo.lock'
- 'deny.toml'
- '.config/advisory-exceptions.toml'
- 'scripts/security/check_advisories.py'
- 'scripts/security/test_check_advisories.py'
- '.github/actions/**'
- '.github/workflows/**'
- 'scripts/release/**'
@@ -107,6 +113,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
fetch-depth: 2
persist-credentials: false
# cargo-deny compiles nothing, so the full setup composite (apt packages,
@@ -134,12 +141,36 @@ jobs:
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install cargo-deny
id: install-cargo-deny
uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2
with:
tool: cargo-deny
tool: cargo-deny@0.20.2
- name: Run cargo-deny
run: cargo deny check --hide-inclusion-graph advisories sources bans licenses
run: cargo deny --locked check --hide-inclusion-graph advisories sources bans licenses
- name: Enforce time-bounded advisory exception registry
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
env:
GH_TOKEN: ${{ github.token }}
CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
if [[ -n "$CI_BASE_SHA" ]]; then
git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA"
fi
mkdir -p artifacts/advisories
python3 scripts/security/check_advisories.py \
--output artifacts/advisories/advisories-gate.json \
--raw-log artifacts/advisories/cargo-deny.log
- name: Upload advisory audit evidence
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: audit-advisories-${{ github.run_number }}-${{ github.run_attempt }}
path: artifacts/advisories
if-no-files-found: error
retention-days: 7
workflow-pin-report:
name: Workflow Pin Report
-37
View File
@@ -197,43 +197,6 @@ jobs:
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# Readers: test-and-lint-rio-v2 (nightly schedule, merge group, dispatch),
# build-rustfs-debug-binary-rio-v2 (nightly schedule / manual dispatch only —
# dormant rio-v2 variant, see rustfs/backlog#1835 and
# docs/architecture/minio-file-format-compat.md).
# The second build below stays despite the reduced cadence: it warms the
# rio-v2,e2e-test-hooks feature resolution the scheduled build restores,
# which keeps that lane inside its 30-minute timeout.
warm-ci-feat-rio:
name: Warm ci-feat-rio
runs-on: sm-standard-4
timeout-minutes: 120
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
id: setup
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-rio
cache-save-if: 'true'
install-build-packaging-tools: 'false'
- name: Build ci-feat-rio superset
if: steps.setup.outputs.cache-hit != 'true'
env:
# --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2"
run: |
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
# sequence rather than as `--features swift,sftp`, which is a combination no
# lane actually compiles; running both leaves the union in target/.
+59 -173
View File
@@ -113,7 +113,7 @@ jobs:
printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT"
echo "Base CI policy unavailable; running the full matrix."
fi
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=8$' "$GITHUB_OUTPUT"; then
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=10$' "$GITHUB_OUTPUT"; then
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
echo "Base policy does not cover this workflow contract; retaining the full matrix."
fi
@@ -168,6 +168,60 @@ jobs:
- name: Run shared quick checks
uses: ./.github/actions/quick-checks
# Required dependency advisory and time-bounded exception gate (rustfs/backlog#2668).
# Runs on every non-closed event, including documentation-only PRs, because a
# RustSec advisory can be published or an exception can expire without lockfile edits.
security-advisories:
name: Security Advisories
if: github.event_name != 'pull_request' || github.event.action != 'closed'
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
fetch-depth: 2
persist-credentials: false
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Setup Rust cache
uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-all-crates: false
cache-on-failure: true
shared-key: rustfs-cargo-deny
save-if: 'false'
- name: Install cargo-deny
id: install-cargo-deny
uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2
with:
tool: cargo-deny@0.20.2
- name: Run security advisories gate
env:
GH_TOKEN: ${{ github.token }}
CI_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
run: |
if [[ -n "$CI_BASE_SHA" ]]; then
git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA"
fi
mkdir -p artifacts/advisories
python3 scripts/security/check_advisories.py \
--output artifacts/advisories/advisories-gate.json \
--raw-log artifacts/advisories/cargo-deny.log
- name: Upload security advisories evidence
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: security-advisories-${{ github.run_number }}-${{ github.run_attempt }}
path: artifacts/advisories
if-no-files-found: error
retention-days: 7
# Clippy runs beside the test-binary build instead of in front of it. The two
# share no compiler output: Clippy writes check-mode metadata, the archive
# needs codegen and linked test binaries, and both restore the third-party
@@ -531,73 +585,9 @@ jobs:
done
cargo clippy --locked -p rustfs --lib "${args[@]}" -- -D warnings
test-and-lint-rio-v2:
name: Test and Lint (rio-v2)
# Specialized boundary, hardware and alternate-feature lanes run only on
# the nightly schedule and manual dispatch. They do not gate a merge: the
# nightly run reports a regression within a day, and repeating these builds
# on every PR revision and merge group bought no earlier signal worth the
# runner occupancy. Workspace lint and tests, the core contract, the debug
# build, E2E smoke and the S3 lanes remain the pull-request gate.
if: needs.classify-changes.outputs.mode == 'full' && contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name)
needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4
timeout-minutes: 90
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-rio
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Protect Connect test home
run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
- name: Run rio-v2 feature tests
shell: bash
env:
# Match the main nextest lane's #5394 link-I/O guard. A cold feature
# cache otherwise fans out enough rust-lld processes to exhaust this
# job's 90-minute budget before any test starts.
CARGO_BUILD_JOBS: "2"
run: |
# --profile ci so the quarantine list (and its junit flaky markers)
# covers this leg too; the default profile is the local no-retry
# profile and silently ignored quarantined flakes here (rustfs#6703).
mkdir -p artifacts/workspace
rm -f target/nextest/ci/junit.xml
./scripts/ci/resource_sampler.sh start nextest-rio-v2
trap './scripts/ci/resource_sampler.sh stop' EXIT
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2
- name: Upload rio-v2 test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: junit-test-and-lint-rio-v2-${{ github.run_number }}-${{ github.run_attempt }}
path: |
target/nextest/ci/junit.xml
artifacts/workspace
retention-days: 3
if-no-files-found: error
test-and-lint-protocols:
name: "Test and Lint (${{ matrix.features.name }})"
# Same cadence as test-and-lint-rio-v2 above.
# Nightly schedule and manual dispatch only. This lane does not gate a merge.
if: needs.classify-changes.outputs.mode == 'full' && contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name)
needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4
@@ -774,47 +764,6 @@ jobs:
if-no-files-found: error
retention-days: 1
build-rustfs-debug-binary-rio-v2:
name: Build RustFS Debug Binary (rio-v2)
# Dormant rio-v2 variant (rustfs/backlog#1835): the feature ships in no
# default build, so this full-suite lane runs only on the nightly schedule
# and manual dispatch. Per-PR cfg-seam coverage stays with
# test-and-lint-rio-v2. Lifecycle and the promote-or-delete condition:
# docs/architecture/minio-file-format-compat.md ("rio-v2 variant lifecycle").
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
needs: [ quick-checks ]
runs-on: sm-standard-4
timeout-minutes: 30
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-rio
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Build debug binary with rio-v2
run: python3 scripts/e2e_binary.py build --bins --features rio-v2,e2e-test-hooks
- name: Upload debug binary
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-debug-binary-rio-v2
overwrite: true
path: |
target/debug/rustfs
target/debug/rustfs.e2e.json
if-no-files-found: error
retention-days: 1
uring-integration:
name: io_uring Integration (real)
# The pull_request trigger includes `closed` purely so the concurrency
@@ -1033,7 +982,7 @@ jobs:
run: sudo apt-get install -y build-essential cmake pkg-config
- name: Install s3s-e2e test tool
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2
uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3.0.8
with:
tool: s3s-e2e
git: https://github.com/s3s-project/s3s.git
@@ -1252,65 +1201,6 @@ jobs:
if-no-files-found: warn
retention-days: 7
e2e-tests-rio-v2:
name: End-to-End Tests (rio-v2)
# Inherits the schedule/dispatch-only gate through needs: on every other
# event build-rustfs-debug-binary-rio-v2 is skipped, so this job skips
# with it (see the dormant-variant comment on that job).
needs: [ build-rustfs-debug-binary-rio-v2 ]
runs-on: sm-standard-2
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Clean up previous test run
run: |
rm -rf /tmp/rustfs
rm -f /tmp/rustfs.log
- name: Download debug binary
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: rustfs-debug-binary-rio-v2
path: target/debug
- name: Make binary executable
run: chmod +x ./target/debug/rustfs
- name: Setup Rust toolchain for s3s-e2e installation
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
# The sm-standard-* custom runner images (introduced in #4884) ship no C
# toolchain, unlike GitHub-hosted ubuntu-latest. Installing s3s-e2e below
# compiles it from source on a cache miss, and build scripts need cc.
- name: Install build tools for s3s-e2e compilation
run: |
sudo apt-get update
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
- name: Install s3s-e2e test tool
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2
with:
tool: s3s-e2e
git: https://github.com/s3s-project/s3s.git
rev: 62cb4a71dd759a6ec56b64c4c42fcc183a2c6a52
- name: Run end-to-end tests
run: |
s3s-e2e --version
python3 scripts/e2e_binary.py run --features rio-v2,e2e-test-hooks -- ./scripts/e2e-run.sh ./target/debug/rustfs /tmp/rustfs
- name: Upload test logs
if: failure()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-test-logs-rio-v2-${{ github.run_number }}-${{ github.run_attempt }}
path: /tmp/rustfs.log
retention-days: 3
s3-implemented-tests:
name: S3 Implemented Tests
needs: [ build-rustfs-debug-binary ]
@@ -1434,21 +1324,19 @@ jobs:
- classify-changes
- typos
- quick-checks
- security-advisories
- workspace-clippy
- workspace-lint-and-build
- workspace-tests
- core-contract
- connect-feature-boundaries
- fips-provider
- test-and-lint-rio-v2
- test-and-lint-protocols
- build-rustfs-debug-binary
- uring-integration
- e2e-tests
- s3-implemented-tests
- s3-lifecycle-behavior-tests
- build-rustfs-debug-binary-rio-v2
- e2e-tests-rio-v2
- e2e-full
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -1471,18 +1359,16 @@ jobs:
- required-checks
- typos
- quick-checks
- security-advisories
- workspace-clippy
- workspace-lint-and-build
- workspace-tests
- core-contract
- test-and-lint-rio-v2
- test-and-lint-protocols
- build-rustfs-debug-binary
- build-rustfs-debug-binary-rio-v2
- uring-integration
- e2e-tests
- e2e-full
- e2e-tests-rio-v2
- s3-implemented-tests
- s3-lifecycle-behavior-tests
if: >-
+62
View File
@@ -0,0 +1,62 @@
# Copyright 2024 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: Jepsen unit
on:
pull_request:
paths:
- "jepsen/**"
- ".github/workflows/jepsen-unit.yml"
push:
branches: [main]
paths:
- "jepsen/**"
- ".github/workflows/jepsen-unit.yml"
jobs:
lein-test:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with:
distribution: temurin
java-version: "21"
- name: Install Leiningen
run: |
set -euo pipefail
mkdir -p "$HOME/bin"
curl -fsSL -o "$HOME/bin/lein" https://raw.githubusercontent.com/technomancy/leiningen/2.11.2/bin/lein
chmod +x "$HOME/bin/lein"
echo "$HOME/bin" >> "$GITHUB_PATH"
"$HOME/bin/lein" version
- name: Run Jepsen checker tests
working-directory: jepsen
run: |
set -euo pipefail
# Clojars occasionally drops the jepsen and generator jars mid-download.
for attempt in 1 2 3; do
if lein test; then
exit 0
fi
echo "lein test attempt ${attempt} failed"
if [ "$attempt" -eq 3 ]; then
exit 1
fi
sleep $((attempt * 15))
done
Generated
+12 -69
View File
@@ -6312,9 +6312,6 @@ name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
dependencies = [
"spin 0.9.9",
]
[[package]]
name = "lexical-core"
@@ -7231,22 +7228,6 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
dependencies = [
"lazy_static",
"libm",
"num-integer",
"num-iter",
"num-traits",
"rand 0.8.8",
"smallvec",
"zeroize",
]
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -7271,16 +7252,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
@@ -7659,8 +7630,6 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "openidconnect"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -7675,7 +7644,7 @@ dependencies = [
"p256",
"p384",
"rand 0.8.8",
"rsa 0.9.10",
"rsa",
"serde",
"serde-value",
"serde_json",
@@ -8358,17 +8327,6 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pkcs1"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [
"der 0.7.10",
"pkcs8 0.10.2",
"spki 0.7.3",
]
[[package]]
name = "pkcs1"
version = "0.8.0"
@@ -9672,26 +9630,6 @@ dependencies = [
"xmlparser",
]
[[package]]
name = "rsa"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
dependencies = [
"const-oid 0.9.6",
"digest 0.10.7",
"num-bigint-dig",
"num-integer",
"num-traits",
"pkcs1 0.7.5",
"pkcs8 0.10.2",
"rand_core 0.6.4",
"signature 2.2.0",
"spki 0.7.3",
"subtle",
"zeroize",
]
[[package]]
name = "rsa"
version = "0.10.0"
@@ -9704,7 +9642,7 @@ dependencies = [
"crypto-primes",
"digest 0.11.3",
"hmac 0.13.0",
"pkcs1 0.8.0",
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.1",
@@ -9808,13 +9746,13 @@ dependencies = [
"p521",
"pageant",
"pbkdf2 0.13.0",
"pkcs1 0.8.0",
"pkcs1",
"pkcs5 0.8.1",
"pkcs8 0.11.0",
"polyval",
"rand 0.10.4",
"rand_core 0.10.1",
"rsa 0.10.0",
"rsa",
"russh-cryptovec",
"russh-util",
"salsa20 0.11.0",
@@ -10007,7 +9945,7 @@ dependencies = [
"regex",
"reqwest 0.13.5",
"rmp-serde",
"rsa 0.10.0",
"rsa",
"rust-embed",
"rustfs-audit",
"rustfs-common",
@@ -10216,7 +10154,7 @@ dependencies = [
"jsonwebtoken 12.0.0",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rsa 0.10.0",
"rsa",
"serde",
"serde_json",
"sha2 0.11.1",
@@ -11195,14 +11133,18 @@ dependencies = [
"russh-sftp",
"rustfs-config",
"rustfs-credentials",
"rustfs-data-usage",
"rustfs-ecstore",
"rustfs-gateway-stream",
"rustfs-gateway-types",
"rustfs-iam",
"rustfs-keystone",
"rustfs-kms",
"rustfs-madmin",
"rustfs-policy",
"rustfs-rio",
"rustfs-s3-types",
"rustfs-sse",
"rustfs-storage-api",
"rustfs-test-utils",
"rustfs-tls-runtime",
@@ -11217,6 +11159,7 @@ dependencies = [
"socket2",
"subtle",
"sync_wrapper",
"temp-env",
"tempfile",
"thiserror 2.0.21",
"time",
@@ -12903,7 +12846,7 @@ dependencies = [
"p384",
"p521",
"rand_core 0.10.1",
"rsa 0.10.0",
"rsa",
"sec1",
"serde",
"sha1 0.11.0",
+4 -1
View File
@@ -73,7 +73,7 @@ members = [
"crates/zip", # ZIP file handling and compression
"crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13
]
exclude = ["vendor/hyper"]
exclude = ["vendor/hyper", "vendor/openidconnect"]
resolver = "3"
[workspace.package]
@@ -243,6 +243,7 @@ chacha20poly1305 = { version = "0.11.0" }
crc-fast = "1.10.0"
hmac = { version = "0.13.0" }
jsonwebtoken = { version = "12.0.0" }
# Patched onto rsa 0.10 in vendor/openidconnect until upstream releases that dependency.
openidconnect = { default-features = false, version = "4.1.0" }
pbkdf2 = "0.13.0"
p256 = { version = "0.14.0", features = ["ecdsa", "pkcs8"] }
@@ -460,4 +461,6 @@ strip = "none"
[patch.crates-io]
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
# Remove after openidconnect releases an rsa >= 0.10 build (ramosbugs/openidconnect-rs#140).
openidconnect = { path = "vendor/openidconnect" }
zstd = { path = "crates/zstd-compat" }
+2
View File
@@ -53,6 +53,8 @@ RTO = "RTO"
rto = "rto"
# rustix OFlags variant (POSIX O_WRONLY equivalent).
WRONLY = "WRONLY"
# Jepsen writes Extensible Data Notation result files named results.edn.
edn = "edn"
[files]
extend-exclude = []
+2
View File
@@ -106,6 +106,8 @@ when restoring `/rustfs/console` for a custom OEM build.
## Distributed endpoint locality
- `RUSTFS_LOCAL_ENDPOINT_HOST` identifies this server's host in a distributed `RUSTFS_VOLUMES` topology without resolving every peer during startup. Set it to exactly one host, without a scheme, port, or path. It is accepted only for orchestrated URL topologies and must match at least one endpoint on the RustFS server port; invalid or unmatched values fail startup. Leave it unset to retain DNS-based locality discovery.
- DNS-based discovery resolves each configured hostname once successfully per startup and reuses the result across drives and pools. If discovery finds no local endpoint, startup exits before opening the service listener. Check that this member's advertised hostname resolves to an address on a local interface and that its endpoint port matches `RUSTFS_ADDRESS`. The next start resolves the hosts again.
- A finite, positive `RUSTFS_STARTUP_TOPOLOGY_WAIT_TIMEOUT` bounds how long endpoint discovery waits for DNS, including lookups and retry delays. If it expires during startup, the CLI reports the error and exits without waiting for an already-running system resolver call.
## Scanner environment aliases
+1
View File
@@ -271,6 +271,7 @@ pub const ENV_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: &str = "RUSTFS_ENCRYPTI
///
/// Default value: false
/// Environment variable: RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE
// RUSTFS_COMPAT_TODO(backlog-2703-multipart-segment-nonce): keep 0x03 multipart segment-nonce writes off by default during rolling upgrades while older nodes or ciphertext-passthrough targets lack 0x03 read support. Remove after the minimum supported release (and warm/replication passthrough targets) reads 0x03 frames and the default flips to true.
pub const DEFAULT_RUSTFS_ENCRYPTION_MULTIPART_SEGMENT_NONCE: bool = false;
/// Environment variable for server KMS backend.
+22
View File
@@ -86,3 +86,25 @@ pub const ENV_OBJECT_MMAP_READ_MAX_LENGTH: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_L
/// materialize up to `data_shards x cap` bytes; raising the cap raises that
/// per-request bound proportionally.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_LENGTH: usize = 32 * 1024 * 1024;
/// Environment variable capping total process-wide in-flight bytes retained by
/// buffered local shard reads (both batch positioned reads and mmap-copy reads).
///
/// Bounding only individual shard length still allows many concurrent unread or
/// slow-consumed `GetObject` responses to accumulate unbounded in-memory shard
/// buffers. When this process-wide budget cannot admit a read, the read falls
/// back to the bounded streaming reader path; reserved bytes are released on
/// `Drop` (including reader cancellation).
///
/// - Purpose: Bound process-wide heap memory retained by in-memory shard reads
/// - Acceptable values: byte count as an unsigned integer; `0` disables
/// in-memory buffered shard reads so every read streams
/// - Example: `export RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES=268435456`
pub const ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES";
/// Default process-wide in-flight byte budget for buffered shard reads: 256 MiB.
///
/// Large enough to keep the fast in-memory path active for concurrent typical
/// reads (including multiple full 32 MiB/shard reads) while placing a strict
/// process-wide ceiling on unread in-memory shard allocations.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: usize = 256 * 1024 * 1024;
+30
View File
@@ -75,7 +75,26 @@ pub const ENV_OBS_LOG_SPAN_EVENTS: &str = "RUSTFS_OBS_LOG_SPAN_EVENTS";
/// Log cleanup related configurations
pub const ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES";
/// Dedicated byte budget for compressed log archives (`.gz` / `.zst`).
/// When unset, compressed archives share the remaining
/// `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget with surviving rolled logs.
/// Setting an explicit non-zero value enforces an independent archive budget;
/// `0` removes the byte cap on archives (retention days still apply).
pub const ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES";
pub const ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES";
/// Maximum number of rolled log files compressed in a single cleanup pass.
/// Bounds per-pass CPU spikes on large backlogs; `0` means unlimited.
/// Over-budget files beyond this cap are deleted directly without compression
/// so the disk budget still holds in one pass.
pub const ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: &str = "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS";
/// Maximum number of log events per second admitted to the file sink across all
/// callsites. `0` disables sink-side rate limiting.
pub const ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC";
/// Maximum number of log events per second admitted to the file sink from any
/// single callsite bucket so one noisy site cannot starve other log sites.
/// When unset, derived as `(sink_max_events_per_sec / 4).max(1)`; `0` disables
/// per-callsite isolation while keeping the global sink ceiling.
pub const ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC";
pub const ENV_OBS_LOG_COMPRESS_OLD_FILES: &str = "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES";
pub const ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL: &str = "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL";
pub const ENV_OBS_LOG_COMPRESSION_ALGORITHM: &str = "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM";
@@ -100,6 +119,10 @@ pub const DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: u64 = 0; // No per-file tr
/// the active file is bounded only by the rotation period, and the cleaner
/// never touches the active file. An explicit `0` keeps size rolling off.
pub const DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES: u64 = 256 * 1024 * 1024; // 256 MiB
/// Default maximum rolled log files compressed in a single cleanup pass.
pub const DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: usize = 32;
/// Default global file-sink event rate ceiling (events/second).
pub const DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: u64 = 10_000;
pub const DEFAULT_OBS_LOG_COMPRESS_OLD_FILES: bool = true;
pub const DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL: u32 = 6;
pub const DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP: &str = "gzip";
@@ -184,7 +207,14 @@ mod tests {
assert_eq!(ENV_OBS_GET_STAGE_LOCAL_SUMMARY_FILE, "RUSTFS_OBS_GET_STAGE_LOCAL_SUMMARY_FILE");
// Test log cleanup related env keys
assert_eq!(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS");
assert_eq!(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC");
assert_eq!(
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
"RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC"
);
assert_eq!(ENV_OBS_LOG_COMPRESS_OLD_FILES, "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES");
assert_eq!(ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL");
assert_eq!(ENV_OBS_LOG_COMPRESSION_ALGORITHM, "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM");
+1 -1
View File
@@ -192,7 +192,7 @@ the same profile for membership and execution with one nightly worker.
| --- | --- | --- |
| Smoke subset (`e2e-smoke` profile) | `e2e-tests` job, every PR | **Active** (backlog#1149 ci-4) |
| Full single-node suite (`e2e-full` profile) | `e2e-full` job, merge queue + main | **Active** (backlog#1149 ci-5) |
| `s3s-e2e` black-box | `e2e-tests` + `e2e-tests-rio-v2` jobs | **Active** (external conformance tool) |
| `s3s-e2e` black-box | `e2e-tests` job | **Active** (external conformance tool) |
| ILM / lifecycle (ignored) | `test-ilm-integration-serial` lane, `-j1` | **Active** (backlog#1148 ilm-1) |
| KMS suite | `e2e-full` job, merge queue + main | **Active** |
| Direct and mixed-version rolling upgrades from pinned previous release | `e2e-upgrade.yml`, release tags + weekly schedule + manual dispatch | **Active** |
@@ -680,13 +680,11 @@ async fn test_copy_object_does_not_inherit_source_legal_hold() {
.key("implicit-copy")
.send()
.await
.unwrap();
.expect_err("copy should not inherit the source hold");
assert_eq!(implicit_legal_hold.raw_response().map(|response| response.status().as_u16()), Some(404));
assert_eq!(
implicit_legal_hold
.legal_hold()
.and_then(|value| value.status())
.map(|value| value.as_str()),
Some("OFF")
implicit_legal_hold.as_service_error().and_then(ProvideErrorMetadata::code),
Some("NoSuchObjectLockConfiguration")
);
client
@@ -2028,12 +2026,12 @@ async fn test_copy_object_retention_uses_destination_policy() {
.key("no-default-copy")
.send()
.await
.unwrap();
let no_default_retention = no_default_retention
.retention()
.expect("retention response should be present");
assert!(no_default_retention.mode().is_none());
assert!(no_default_retention.retain_until_date().is_none());
.expect_err("copy should have no retention without a destination default");
assert_eq!(no_default_retention.raw_response().map(|response| response.status().as_u16()), Some(404));
assert_eq!(
no_default_retention.as_service_error().and_then(ProvideErrorMetadata::code),
Some("NoSuchObjectLockConfiguration")
);
let retained_version_id = put_object_with_retention(
&client,
+13 -11
View File
@@ -230,10 +230,10 @@ pub mod bucket {
ObjectLockConfigState, ScannerBucketIncarnationReadGuard, acquire_bucket_metadata_transaction_lock,
acquire_bucket_metadata_transaction_lock_for_incarnation, acquire_scanner_bucket_incarnation_fence,
acquire_scanner_bucket_incarnation_read_fence, capture_bucket_metadata_incarnation, delete, delete_if_incarnation,
delete_if_incarnation_at, delete_under_transaction_lock, get, get_accelerate_config, get_bucket_policy,
get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config, get_durability_config,
get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config, get_notification_config,
get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
delete_if_incarnation_at, delete_under_transaction_lock, find_object_lock_config_state, get, get_accelerate_config,
get_bucket_policy, get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config,
get_durability_config, get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config,
get_notification_config, get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
get_on_demand_migration_config_in, get_public_access_block_config, get_quota_config, get_replication_config,
get_request_payment_config, get_s3_tagging_config, get_sse_config, get_tagging_config, get_versioning_config,
get_website_config, init_bucket_metadata_sys, list_bucket_targets, reload_bucket_metadata, remove_bucket_metadata,
@@ -452,13 +452,15 @@ pub mod data_usage {
#[cfg(feature = "test-util")]
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
pub use crate::data_usage::{
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached,
load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size,
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend, verified_account_bucket_usage,
@@ -212,17 +212,18 @@ pub fn get_global_transition_state() -> Arc<TransitionState> {
crate::runtime::global::current_ctx().transition_state()
}
fn resolve_transition_worker_count() -> (i64, i64, i64) {
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
fn resolve_transition_worker_count(parallelism: std::num::NonZeroUsize) -> (i64, i64, i64) {
let configured = env::var(ENV_TRANSITION_WORKERS)
.ok()
.and_then(|value| value.parse::<i64>().ok())
.filter(|value| *value > 0)
.unwrap_or(fallback);
let mut effective = configured;
.unwrap_or_else(|| {
i64::try_from(parallelism.get())
.unwrap_or(i64::MAX)
.min(DEFAULT_TRANSITION_WORKERS_CAP)
});
let absolute_max = resolve_transition_workers_absolute_max();
effective = std::cmp::min(effective, absolute_max);
(configured, absolute_max, effective)
(configured, absolute_max, configured.min(absolute_max))
}
fn resolve_transition_workers_absolute_max() -> i64 {
@@ -2085,7 +2086,7 @@ impl TransitionState {
}
pub async fn init(api: Arc<ECStore>) {
let (configured, absolute_max, n) = resolve_transition_worker_count();
let (configured, absolute_max, n) = resolve_transition_worker_count(api.ctx.worker_parallelism());
let transition_state = runtime_sources::transition_state_handle();
debug!(
event = EVENT_LIFECYCLE_WORKER_STATE,
@@ -2100,8 +2101,7 @@ impl TransitionState {
"Lifecycle worker configuration resolved"
);
//self.objAPI = objAPI
Self::update_workers(api, n).await;
Self::resize_workers_to(api, n, n, absolute_max);
}
pub fn pending_tasks(&self) -> usize {
@@ -2270,18 +2270,15 @@ impl TransitionState {
Self::update_workers_inner(api, n).await;
}
pub async fn update_workers_inner(api: Arc<ECStore>, n: i64) {
let mut n = n;
let requested = n;
if n == 0 {
let (_, _, effective) = resolve_transition_worker_count();
n = effective;
}
// Allow environment override of maximum workers
let absolute_max = resolve_transition_workers_absolute_max();
n = n.clamp(0, absolute_max);
Self::resize_workers_to(api, n, requested, absolute_max);
pub async fn update_workers_inner(api: Arc<ECStore>, requested: i64) {
let (effective, absolute_max) = if requested == 0 {
let (_, absolute_max, effective) = resolve_transition_worker_count(api.ctx.worker_parallelism());
(effective, absolute_max)
} else {
let absolute_max = resolve_transition_workers_absolute_max();
(requested.clamp(0, absolute_max), absolute_max)
};
Self::resize_workers_to(api, effective, requested, absolute_max);
}
fn resize_workers_to(api: Arc<ECStore>, n: i64, requested: i64, absolute_max: i64) {
@@ -2477,19 +2474,16 @@ fn is_lifecycle_expiry_already_gone(err: &Error) -> bool {
/// `_RUSTFS_ILM_EXPIRATION_WORKERS` silent override and the
/// `RUSTFS_DEFAULT_EXPIRY_WORKERS` zero-fallback were undocumented, unset in
/// every known deployment, and are removed (backlog#1832).
fn expiry_worker_count() -> usize {
let default = std::cmp::min(num_cpus::get(), 16);
match env::var(ENV_MAX_EXPIRY_WORKERS) {
Ok(value) => match value.parse::<usize>() {
Ok(workers) if workers > 0 => workers,
_ => default,
},
Err(_) => default,
}
fn expiry_worker_count(parallelism: std::num::NonZeroUsize) -> usize {
env::var(ENV_MAX_EXPIRY_WORKERS)
.ok()
.and_then(|value| value.parse::<usize>().ok())
.filter(|workers| *workers > 0)
.unwrap_or(parallelism.get().min(16))
}
pub async fn init_background_expiry(api: Arc<ECStore>) {
let workers = expiry_worker_count();
let workers = expiry_worker_count(api.ctx.worker_parallelism());
ExpiryState::resize_workers(workers, api.clone()).await;
let _ = spawn_tier_free_version_recovery_once(api.clone(), &TIER_FREE_VERSION_RECOVERY_STARTED);
@@ -9740,19 +9734,24 @@ mod tests {
#[test]
#[serial]
fn expiry_worker_count_resolves_all_env_states() {
let default = std::cmp::min(num_cpus::get(), 16);
let default = std::thread::available_parallelism().map_or(1, usize::from).min(16);
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
with_expiry_worker_env(None, || {
assert_eq!(expiry_worker_count(), default, "unset env must fall back to min(cpus, 16)");
assert_eq!(expiry_worker_count(parallelism), default, "unset env must fall back to min(cpus, 16)");
});
with_expiry_worker_env(Some("0"), || {
assert_eq!(expiry_worker_count(), default, "zero must fall back instead of spawning zero workers");
assert_eq!(
expiry_worker_count(parallelism),
default,
"zero must fall back instead of spawning zero workers"
);
});
with_expiry_worker_env(Some("4"), || {
assert_eq!(expiry_worker_count(), 4, "a valid positive value must win");
with_expiry_worker_env(Some("32"), || {
assert_eq!(expiry_worker_count(parallelism), 32, "an explicit count may exceed the default cap");
});
with_expiry_worker_env(Some("not-a-number"), || {
assert_eq!(expiry_worker_count(), default, "garbage must fall back to the default");
assert_eq!(expiry_worker_count(parallelism), default, "garbage must fall back to the default");
});
}
@@ -9948,9 +9947,13 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_uses_fallback_when_env_missing() {
with_transition_worker_env(None, None, || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
let fallback = i64::try_from(cpus)
.expect("available parallelism fits in i64")
.min(DEFAULT_TRANSITION_WORKERS_CAP);
assert_eq!(configured, fallback);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
assert_eq!(effective, fallback);
@@ -9961,7 +9964,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_honors_positive_env_value() {
with_transition_worker_env(Some("4"), Some("32"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, 32);
@@ -9973,7 +9976,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_clamps_to_absolute_max() {
with_transition_worker_env(Some("64"), Some("16"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 64);
assert_eq!(absolute_max, 16);
@@ -9985,7 +9988,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_ignores_non_positive_absolute_max() {
with_transition_worker_env(Some("4"), Some("0"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
@@ -9993,7 +9996,7 @@ mod tests {
});
with_transition_worker_env(Some("4"), Some("-1"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
@@ -10005,9 +10008,13 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_falls_back_for_zero_value() {
with_transition_worker_env(Some("0"), Some("32"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
let fallback = i64::try_from(cpus)
.expect("available parallelism fits in i64")
.min(DEFAULT_TRANSITION_WORKERS_CAP);
assert_eq!(configured, fallback);
assert_eq!(absolute_max, 32);
assert_eq!(effective, fallback);
+61 -33
View File
@@ -151,6 +151,15 @@ pub enum ObjectLockConfigState {
Fabricated,
}
// Only namespace probes can name the requested bucket. Internal metadata
// storage errors must not be mistaken for absence of that bucket.
fn bucket_namespace_error(bucket: &str, error: Error) -> Error {
match error {
Error::VolumeNotFound => Error::BucketNotFound(bucket.to_owned()),
error => error,
}
}
enum BucketMetadataAuthority {
Authoritative(Arc<BucketMetadata>),
Fabricated,
@@ -1695,6 +1704,24 @@ pub async fn get_object_lock_config_state(bucket: &str) -> Result<ObjectLockConf
bucket_meta_sys.get_object_lock_config_state(bucket).await
}
/// Read Object Lock state from authoritative bucket metadata.
///
/// `Ok(None)` means the bucket is confirmed missing. An existing bucket with
/// no Object Lock configuration returns `Some(ConfirmedAbsent)`.
///
/// # Errors
///
/// Returns storage, migration, or validation errors when the state cannot be read.
pub async fn find_object_lock_config_state(bucket: &str) -> Result<Option<ObjectLockConfigState>> {
let bucket_meta_sys_lock = get_bucket_metadata_sys()?;
let bucket_meta_sys = bucket_meta_sys_lock.read().await.clone();
match bucket_meta_sys.find_object_lock_config_state(bucket).await {
Err(Error::BucketNotFound(name)) if name == bucket => Ok(None),
result => result,
}
}
pub(crate) async fn get_object_lock_config_state_in(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
@@ -3201,15 +3228,15 @@ impl BucketMetadataSys {
Box::pin(async {
let store = self.object_store();
let options = crate::storage_api_contracts::bucket::BucketOptions::default();
let info = if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await
if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await.map(|_| ())
} else {
store.get_bucket_info_from_sets_at_read_quorum(bucket, &options).await
};
info.map(|_| ())
store.check_bucket_presence_at_read_quorum(bucket).await
}
}),
)
.await?;
.await
.map_err(|err| bucket_namespace_error(bucket, err))?;
if guard.is_lock_lost() {
return Err(Error::other(format!(
"bucket namespace lock was lost before lazy bucket metadata publish: {bucket}"
@@ -3369,14 +3396,18 @@ impl BucketMetadataSys {
}
pub async fn get_object_lock_config_state(&self, bucket: &str) -> Result<ObjectLockConfigState> {
match self.get_metadata_authority(bucket).await? {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
BucketMetadataAuthority::Fabricated => match self.migrate_legacy_metadata(bucket).await? {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
BucketMetadataAuthority::Fabricated => Ok(ObjectLockConfigState::Fabricated),
},
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
self.find_object_lock_config_state(bucket).await?.ok_or(Error::ConfigNotFound)
}
async fn find_object_lock_config_state(&self, bucket: &str) -> Result<Option<ObjectLockConfigState>> {
let authority = match self.get_metadata_authority(bucket).await? {
BucketMetadataAuthority::Fabricated => self.migrate_legacy_metadata(bucket).await?,
authority => authority,
};
match authority {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm).map(Some),
BucketMetadataAuthority::Fabricated => Ok(Some(ObjectLockConfigState::Fabricated)),
BucketMetadataAuthority::MissingBucket => Ok(None),
}
}
@@ -3516,7 +3547,8 @@ impl BucketMetadataSys {
self.object_store()
.get_bucket_info_from_sets(bucket, &crate::storage_api_contracts::bucket::BucketOptions::default()),
)
.await?;
.await
.map_err(|err| bucket_namespace_error(bucket, err))?;
let (mut metadata, persisted) = await_bucket_namespace_operation(
Some(&namespace_guard),
@@ -3769,19 +3801,12 @@ impl BucketMetadataSys {
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
let (bucket_presence_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata snapshot existence check",
async {
store
.get_bucket_info_from_sets_at_read_quorum(
bucket,
&crate::storage_api_contracts::bucket::BucketOptions::default(),
)
.await
},
store.check_bucket_presence_at_read_quorum(bucket),
)),
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -3790,8 +3815,8 @@ impl BucketMetadataSys {
load_bucket_metadata_parse_with_presence(Arc::clone(&store), bucket, false),
)),
);
match bucket_info_res {
Ok(_) => {}
match bucket_presence_res {
Ok(()) => {}
Err(Error::VolumeNotFound) => return Ok(BucketMetadataAuthority::MissingBucket),
Err(err) => return Err(err),
}
@@ -4564,14 +4589,17 @@ mod tests {
sys.get_bucket_policy("migration-write-failure").await,
Err(Error::ConfigNotFound)
));
assert!(sys.get_object_lock_config_state("migration-write-failure").await.is_err());
assert!(sys.find_object_lock_config_state("migration-write-failure").await.is_err());
assert!(sys.get("migration-write-failure").await.is_err());
sys.legacy_migration_write_error.store(false, Ordering::Relaxed);
let loads_before = sys.lazy_disk_loads.load(Ordering::Relaxed);
assert!(sys.find_object_lock_config_state("missing-bucket").await.unwrap().is_none());
assert!(matches!(
sys.get_object_lock_config_state("missing-bucket").await,
Err(Error::ConfigNotFound)
));
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), loads_before + 1);
assert!(matches!(sys.get_bucket_policy("missing-bucket").await, Err(Error::ConfigNotFound)));
assert!(matches!(sys.get_bucket_policy_raw("missing-bucket").await, Err(Error::ConfigNotFound)));
@@ -5290,14 +5318,14 @@ mod tests {
// be lazily republished as a live bucket generation.
let mut deleted_lazy = BucketMetadata::new("deleted-lazy-bucket");
deleted_lazy.policy_config_json = b"stale-generation".to_vec();
sys.persist_and_set(deleted_lazy)
sys.persist_new_and_set(deleted_lazy)
.await
.expect("stale metadata should persist");
.expect("stale committed metadata should persist");
sys.metadata_map.write().await.remove("deleted-lazy-bucket");
assert!(
sys.get_config("deleted-lazy-bucket").await.is_err(),
"lazy load must fail when the physical bucket no longer exists"
);
assert!(matches!(
sys.get_config("deleted-lazy-bucket").await,
Err(Error::BucketNotFound(name)) if name == "deleted-lazy-bucket"
));
assert!(sys.get("deleted-lazy-bucket").await.is_err());
// (d) The namespace generation fence must be acquired before lazy
@@ -2175,6 +2175,10 @@ fn verify_tonic_rpc_signature_with_policy(
&& has_v2_auth_headers(headers)
&& tonic_boot_epoch_challenge(headers).is_ok_and(|challenge| challenge.is_some());
if replay_scope_strict && !bootstrap {
// The server answers this rejection with its boot-epoch proof so a signed peer can retry
// with a replay scope. Verify the method-bound v2 HMAC first so unsigned, legacy-only, or
// forged callers are rejected for the signature itself without consuming replay-cache slots.
verified_tonic_rpc_nonce(audience, path, headers, true)?;
return Err(std::io::Error::other("RPC replay-scoped authentication required"));
}
@@ -3291,6 +3295,64 @@ mod tests {
);
}
#[test]
fn replay_scope_strictness_reports_missing_scope_only_to_signed_callers() {
ensure_test_rpc_secret();
let path = "/node_service.NodeService/ReadVersion";
let mut headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "ReadVersion", None)
.expect("v2 compatibility headers should build");
let signed = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("strict replay scope must reject a signed v2-only request");
assert_eq!(signed.to_string(), "RPC replay-scoped authentication required");
assert_eq!(tonic_rpc_auth_failure_reason(&signed), "replay_scope_required");
// A body-digested v2-only mutation must also verify its v2 HMAC before reporting
// `replay_scope_required`, without inserting its nonce into the replay cache for a
// request that is rejected prior to execution.
let digest = hex_simd::encode_to_string(Sha256::digest(b"strict-body"), hex_simd::AsciiCase::Lower);
let mutation_path = "/node_service.NodeService/WriteAll";
let mutation_headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "WriteAll", Some(&digest))
.expect("body-digested v2 headers should build");
let mutation_nonce = Uuid::parse_str(
mutation_headers[RPC_NONCE_HEADER]
.to_str()
.expect("v2 nonce header must be ASCII"),
)
.expect("body-digested v2 nonce must be a UUID");
let mutation_rejected =
verify_tonic_rpc_signature_with_policy("node-a:9000", mutation_path, &mutation_headers, false, true, false)
.expect_err("strict replay scope must reject a signed body-digested v2-only request");
assert_eq!(mutation_rejected.to_string(), "RPC replay-scoped authentication required");
assert!(
!LOCAL_RPC_NONCE_CACHE
.lock()
.expect("nonce cache lock")
.contains_nonce(&mutation_nonce),
"rejected replay_scope_required requests must not consume replay-cache slots"
);
let cross_method =
verify_tonic_rpc_signature_with_policy("node-a:9000", "/node_service.NodeService/Ping", &headers, false, true, false)
.expect_err("a v2 signature bound to another method must not report replay_scope_required");
assert_eq!(cross_method.to_string(), "Invalid RPC v2 signature");
let wrong_audience = verify_tonic_rpc_signature_with_policy("node-b:9000", path, &headers, false, true, false)
.expect_err("a v2 signature bound to another audience must not report replay_scope_required");
assert_eq!(wrong_audience.to_string(), "Invalid RPC v2 signature");
headers.insert(RPC_SIGNATURE_V2_HEADER, HeaderValue::from_static("invalid"));
let forged = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("a forged v2 signature must be rejected as invalid_v2_signature");
assert_eq!(forged.to_string(), "Invalid RPC v2 signature");
let legacy = gen_signature_headers(TONIC_RPC_PREFIX, &Method::GET).expect("legacy auth headers should build");
for unsigned_or_legacy in [legacy, HeaderMap::new()] {
let error = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &unsigned_or_legacy, false, true, false)
.expect_err("a request without v2 metadata must be rejected as v2_required");
assert_eq!(error.to_string(), "RPC v2 authentication required");
}
}
#[test]
fn boot_epoch_response_proof_binds_audience_challenge_and_epoch() {
ensure_test_rpc_secret();
+240 -48
View File
@@ -32,8 +32,8 @@ use crate::disk::{
DeleteRecoveryInspection, DeleteRecoveryPage, DeleteRecoveryRpcOperation, DeleteRecoveryRpcReply, DiskAPI, DiskInfo,
DiskInfoOptions, DiskLocation, DiskOption, FileInfoVersions, FileReader, FileWriter, GuardedDeleteVersionsPayload,
GuardedFileInfoVersions, PartTransactionAction, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo,
WalkDirOptions, batch_read_version_one_by_one,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataGuards, RenameDataObservation, RenameDataResp,
RenameDispatchDeadline, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, batch_read_version_one_by_one,
disk_store::{
DEFAULT_RUSTFS_DRIVE_ACTIVE_MONITORING, ENV_RUSTFS_DRIVE_ACTIVE_MONITORING, SKIP_IF_SUCCESS_BEFORE,
get_drive_active_check_interval, get_drive_active_check_timeout, get_drive_disk_info_timeout, get_drive_list_dir_timeout,
@@ -3313,6 +3313,25 @@ fn validate_decoded_file_info(file_info: &FileInfo) -> Result<()> {
file_info.validate_for_metadata_read().map_err(Into::into)
}
// Dropping preparation is safe only before the mutation enters the transport.
async fn before_rename_dispatch<T>(mut deadline: Option<RenameDispatchDeadline>, prepare: impl Future<Output = T>) -> Option<T> {
let Some(deadline) = deadline.as_mut() else {
return Some(prepare.await);
};
tokio::select! {
biased;
result = prepare => Some(result),
() = async {
let at = deadline.wait_for(Option::is_some).await.ok().and_then(|deadline| *deadline);
if let Some(at) = at {
time::sleep_until(at).await;
} else {
std::future::pending::<()>().await;
}
} => None,
}
}
impl RemoteDisk {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed(
@@ -3335,6 +3354,7 @@ impl RemoteDisk {
dst_volume: &str,
dst_path: &str,
items: Vec<RenameBatchClientItem<'_>>,
dispatch_deadline: Option<RenameDispatchDeadline>,
) -> std::result::Result<RemoteRenameBatchStream, RenameBatchStartError> {
if self.rename_admission.is_none() || items.is_empty() || items.len() > 16 {
return Err(RenameBatchStartError::NotDispatched(DiskError::UnsupportedDisk));
@@ -3354,20 +3374,35 @@ impl RemoteDisk {
if let Some(error) = self.offline_bypass_error() {
return Err(RenameBatchStartError::NotDispatched(error));
}
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let mut client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let prepared = before_rename_dispatch(dispatch_deadline, async {
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let admission = self
.acquire_rename_admission_until(items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok((client, guard))
})
.await
.ok_or(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))?;
let (mut client, mut guard) = prepared?;
let mut request_items = Vec::with_capacity(items.len());
for item in items {
let item_index = u32::try_from(item.slot)
@@ -3393,21 +3428,11 @@ impl RemoteDisk {
crate::cluster::rpc::set_tonic_canonical_body_digest(&mut request, &canonical_body)
.map_err(Error::other)
.map_err(RenameBatchStartError::NotDispatched)?;
let admission = self
.acquire_rename_admission_until(request.get_ref().items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let call_timeout = deadline.saturating_duration_since(tokio::time::Instant::now());
if call_timeout == Duration::ZERO {
guard.release_without_quarantine();
return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout));
}
let mut guard = guard;
guard.mark_dispatched();
let response = match self
.execute_peer_batch_with_timeout(
@@ -3433,7 +3458,6 @@ impl RemoteDisk {
Ok(guard.into_stream(response.into_inner(), expected_mask))
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed_with_fence(
&self,
src_volume: &str,
@@ -3443,6 +3467,36 @@ impl RemoteDisk {
dst_path: &str,
scanner_publication_lease_token: Option<Uuid>,
) -> Result<RenameDataResp> {
self.rename_data_observed(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
RenameDataGuards {
scanner_publication_lease_token,
..Default::default()
},
)
.await
.result
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_observed(
&self,
src_volume: &str,
src_path: &str,
fi: &FileInfo,
dst_volume: &str,
dst_path: &str,
guards: RenameDataGuards,
) -> RenameDataObservation {
let RenameDataGuards {
scanner_publication_lease_token,
dispatch_deadline,
..
} = guards;
let multipart_rename = src_volume == crate::disk::RUSTFS_META_MULTIPART_BUCKET;
let pool_meta_cas = rustfs_utils::http::metadata_compat::contains_key_str(
&fi.metadata,
@@ -3453,7 +3507,7 @@ impl RemoteDisk {
|| dst_path != "pool.bin"
|| scanner_publication_lease_token.is_some())
{
return Err(DiskError::UnsupportedDisk);
return RenameDataObservation::unknown(Err(DiskError::UnsupportedDisk));
}
trace!(
event = EVENT_REMOTE_DISK_RPC,
@@ -3469,11 +3523,36 @@ impl RemoteDisk {
"Remote disk RPC started"
);
self.execute_with_timeout_for_op(
let mut dispatch_expired = false;
let result = Self::execute_with_timeout_for_op(
self,
"rename_data",
|| async {
let prepare_started = rustfs_io_metrics::put_stage_timer();
let collect_prepare_timing = prepare_started.is_some();
let prepared = before_rename_dispatch(dispatch_deadline, async {
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (client, policy) = client?;
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok::<_, DiskError>((client, policy, rename_admission_guard))
})
.await;
let Some(prepared) = prepared else {
dispatch_expired = true;
return Err(DiskError::DiskNotFound);
};
let (mut client, mut policy, mut rename_admission_guard) = prepared?;
let msgpack_encode_started = collect_prepare_timing.then(Instant::now);
let file_info_bin = Bytes::from(encode_file_info_msgpack(fi)?);
rustfs_io_metrics::record_put_object_stage_duration_from(
@@ -3486,13 +3565,6 @@ impl RemoteDisk {
file_info_bin.len(),
);
}
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (mut client, mut policy) = client?;
let bucket_incarnation_id = crate::store::bucket_heal_scope_for_object(dst_volume, dst_path)
.map(|scope| Bytes::copy_from_slice(scope.incarnation.as_bytes()))
.unwrap_or_default();
@@ -3504,13 +3576,6 @@ impl RemoteDisk {
let scanner_publication_lease = scanner_publication_lease_token
.map(|token| Bytes::copy_from_slice(token.as_bytes()))
.unwrap_or_default();
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let mut rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let rpc_kind = if multipart_rename {
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_MULTIPART
} else if pool_meta_cas {
@@ -3673,7 +3738,11 @@ impl RemoteDisk {
},
get_max_timeout_duration(),
)
.await
.await;
RenameDataObservation {
result,
rejected_before_publication: dispatch_expired,
}
}
/// Delete a path while binding the target-side operation to a scanner
@@ -6484,6 +6553,66 @@ mod tests {
}
}
#[tokio::test(start_paused = true)]
async fn rename_dispatch_budget_only_starts_after_the_quorum_signal() {
use futures::FutureExt as _;
let (tx, rx) = tokio::sync::watch::channel(None);
let mut dial = std::pin::pin!(before_rename_dispatch(Some(rx), std::future::pending::<()>()));
assert!(dial.as_mut().now_or_never().is_none());
time::advance(Duration::from_secs(2)).await;
assert!(dial.as_mut().now_or_never().is_none(), "quorum has not been reached");
tx.send_replace(Some(time::Instant::now() + Duration::from_secs(1)));
assert!(dial.as_mut().now_or_never().is_none(), "quorum grants a connection grace period");
time::advance(Duration::from_secs(1)).await;
assert_eq!(dial.await, None, "only the unresolved connection expires");
assert_eq!(before_rename_dispatch(Some(tx.subscribe()), std::future::ready(8)).await, Some(8));
}
#[tokio::test]
async fn rename_dispatch_budget_does_not_cancel_a_dispatched_rpc() {
use futures::FutureExt as _;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename peer");
peer.peer.serve_rename_data();
let gate = Arc::new(TestFormatReadGate::default());
*peer.peer.rename_data_reply_gate.lock().expect("rename reply gate") = Some(gate.clone());
let disk = remote_disk_for_addr(&peer.addr).await;
let (tx, rx) = tokio::sync::watch::channel(None);
let file_info = sample_rename_data_file_info();
let mut rename = std::pin::pin!(disk.rename_data_observed(
"tmp",
"source",
&file_info,
"bucket",
"object",
RenameDataGuards {
dispatch_deadline: Some(rx),
..Default::default()
},
));
time::timeout(Duration::from_secs(5), async {
tokio::select! {
() = gate.entered.notified() => {},
_ = rename.as_mut() => panic!("rename completed before the peer received it"),
}
})
.await
.expect("peer should receive the authenticated mutation");
tx.send_replace(Some(time::Instant::now()));
assert!(rename.as_mut().now_or_never().is_none(), "the dispatched mutation must continue to drain");
gate.release.cancel();
let observed = rename.await;
assert!(!observed.rejected_before_publication());
observed.result.expect("remote rename should return success");
peer.stop().await;
}
#[tokio::test]
async fn multipart_rename_old_peer_rejects_without_legacy_fallback() {
runtime_sources::ensure_test_rpc_secret();
@@ -6540,7 +6669,7 @@ mod tests {
for (object, calls) in [("object", 1), ("other-object", 2)] {
let result = remote
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos), None)
.await;
assert!(matches!(result, Err(RenameBatchStartError::UnsupportedBeforeStream)));
assert_eq!(
@@ -6577,7 +6706,7 @@ mod tests {
for width in [2_usize, 4] {
let file_infos = (0..width).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("{width}-item real batch must start"));
assert_eq!(
@@ -6615,6 +6744,62 @@ mod tests {
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_dispatch_budget_releases_waiting_batch_admission_without_dispatch() {
use std::task::Poll;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename batch peer");
peer.peer.serve_rename_batch_results(usize::MAX);
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let capacity = rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT;
let held = Arc::clone(&gate)
.acquire_many_owned(u32::try_from(capacity - 1).expect("valid permit count"))
.await
.expect("reserve all but one permit");
let file_infos = [sample_rename_data_file_info(), sample_rename_data_file_info()];
let (tx, rx) = tokio::sync::watch::channel(None);
let mut rename = std::pin::pin!(remote.start_rename_data_batch(
"tmp",
"source",
"bucket",
"object",
rename_batch_client_items(&file_infos),
Some(rx),
));
time::timeout(
Duration::from_secs(5),
std::future::poll_fn(|cx| {
assert!(rename.as_mut().poll(cx).is_pending(), "batch must wait for two permits");
if gate.available_permits() == 0 {
Poll::Ready(())
} else {
Poll::Pending
}
}),
)
.await
.expect("the queued batch must reserve the spare permit");
tx.send_replace(Some(time::Instant::now()));
let result = time::timeout(Duration::from_secs(5), rename)
.await
.expect("elapsed dispatch budget must release the batch waiter");
assert!(matches!(result, Err(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))));
assert_eq!(peer.peer.rename_batch_calls(), 0, "expiry must not send a mutation to the peer");
assert_eq!(gate.available_permits(), 1, "the cancelled acquire must release its reservation");
drop(held);
assert_eq!(gate.available_permits(), capacity);
})
.await;
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_real_partial_eof_quarantines_only_missing_items() {
@@ -6633,7 +6818,7 @@ mod tests {
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let file_infos = (0..4).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("real partial batch must start"));
@@ -7200,7 +7385,7 @@ mod tests {
fn msgpack_eligible_requests_bind_one_policy_and_bounded_local_retry() {
let source = rustfs_protos::compat_manifest::production_source(include_str!("remote_disk.rs"), "remote_disk.rs");
for function in [
"rename_data_borrowed_with_fence",
"rename_data_observed",
"write_metadata",
"update_metadata",
"read_version",
@@ -7550,6 +7735,7 @@ mod tests {
rename_batch_result_limit: Arc<StdMutex<Option<usize>>>,
serve_rename_data: Arc<AtomicBool>,
rename_data_disks: Arc<StdMutex<Vec<String>>>,
rename_data_reply_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
object_read_all_disks: Arc<StdMutex<Vec<String>>>,
format_data: Bytes,
read_all_data: Bytes,
@@ -7584,6 +7770,7 @@ mod tests {
rename_batch_result_limit: Arc::default(),
serve_rename_data: Arc::default(),
rename_data_disks: Arc::default(),
rename_data_reply_gate: Arc::default(),
object_read_all_disks: Arc::default(),
format_data,
read_all_data,
@@ -7711,6 +7898,11 @@ mod tests {
.lock()
.expect("rename data disks lock poisoned")
.push(request.disk);
let gate = peer.rename_data_reply_gate.lock().expect("rename reply gate lock").take();
if let Some(gate) = gate {
gate.entered.notify_one();
gate.release.cancelled().await;
}
let payload = serde_json::to_string(&RenameDataResp {
sign: Some(vec![1]),
..Default::default()
+69 -73
View File
@@ -44,7 +44,7 @@ use crate::{
};
use futures::{
future::join_all,
stream::{FuturesUnordered, StreamExt},
stream::{self, StreamExt},
};
use http::HeaderMap;
use rustfs_filemeta::FileInfo;
@@ -540,39 +540,39 @@ impl Sets {
// pub default_parity_count: usize,
// }
struct DelObj {
// set_idx: usize,
orig_idx: usize,
obj: ObjectToDelete,
#[derive(Default)]
struct SetDeleteBatch {
indices: Vec<usize>,
objects: Vec<ObjectToDelete>,
}
fn apply_delete_objects_results(
del_objects: &mut [DeletedObject],
del_errs: &mut [Option<Error>],
set_objects: &[DelObj],
dobjects: &[DeletedObject],
indices: &[usize],
deleted: Vec<DeletedObject>,
errs: Vec<Option<Error>>,
) {
let mut deleted = deleted.into_iter();
for (i, err) in errs.into_iter().enumerate() {
let obj = set_objects
let index = *indices
.get(i)
.expect("delete_objects should return errors aligned with input objects");
del_errs[obj.orig_idx] = err;
del_objects[obj.orig_idx] = dobjects
.get(i)
.expect("delete_objects should return objects aligned with input objects")
.clone();
del_errs[index] = err;
del_objects[index] = deleted
.next()
.expect("delete_objects should return objects aligned with input objects");
}
}
fn apply_delete_accounting_results(
accounting: &mut [Option<DeleteAccounting>],
set_objects: &[DelObj],
set_accounting: &[Option<DeleteAccounting>],
indices: &[usize],
set_accounting: Vec<Option<DeleteAccounting>>,
) {
for (obj, value) in set_objects.iter().zip(set_accounting.iter()) {
accounting[obj.orig_idx] = value.clone();
for (&index, value) in indices.iter().zip(set_accounting) {
accounting[index] = value;
}
}
@@ -583,43 +583,60 @@ impl Sets {
objects: Vec<ObjectToDelete>,
opts: ObjectOptions,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let [first, rest @ ..] = objects.as_slice() else {
return (Vec::new(), Vec::new(), Vec::new());
};
if let [set] = self.disk_set.as_slice() {
return set.delete_objects_with_accounting(bucket, objects, opts).await;
}
let first_set = self.get_hashed_set_index(&first.object_name);
let Some(prefix_len) = rest
.iter()
.position(|object| self.get_hashed_set_index(&object.object_name) != first_set)
.map(|offset| offset + 1)
else {
return self.disk_set[first_set]
.delete_objects_with_accounting(bucket, objects, opts)
.await;
};
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
let mut set_obj_map = HashMap::new();
for (i, obj) in objects.iter().enumerate() {
let idx = self.get_hashed_set_index(obj.object_name.as_str());
set_obj_map.entry(idx).or_insert_with(Vec::new).push(DelObj {
orig_idx: i,
obj: obj.clone(),
});
let mut objects = objects.into_iter().enumerate();
let (indices, first_objects) = objects.by_ref().take(prefix_len).unzip();
let mut batches = HashMap::new();
batches.insert(
first_set,
SetDeleteBatch {
indices,
objects: first_objects,
},
);
for (index, object) in objects {
let set_index = self.get_hashed_set_index(&object.object_name);
let batch = batches.entry(set_index).or_default();
batch.indices.push(index);
batch.objects.push(object);
}
let max_concurrent = set_obj_map.len().min(num_cpus::get()).max(1);
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
let mut futures = FuturesUnordered::new();
let bucket = bucket.to_owned();
let mut pending = stream::iter(batches)
.map(|(set_index, batch)| {
let disks = self.get_disks(set_index);
let opts = opts.clone();
async move {
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(bucket, batch.objects, opts).await;
(batch.indices, deleted, errors, accounting)
}
})
.buffer_unordered(self.ctx.worker_parallelism().get());
for (set_index, set_objects) in set_obj_map {
let disks = self.get_disks(set_index);
let objects = set_objects.iter().map(|entry| entry.obj.clone()).collect::<Vec<_>>();
let bucket = bucket.clone();
let opts = opts.clone();
let semaphore = semaphore.clone();
futures.push(async move {
let _permit = semaphore
.acquire_owned()
.await
.expect("delete_objects semaphore should remain open");
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(&bucket, objects, opts).await;
(set_objects, deleted, errors, accounting)
});
}
while let Some((set_objects, deleted, errors, set_accounting)) = futures.next().await {
apply_delete_objects_results(&mut del_objects, &mut del_errs, &set_objects, &deleted, errors);
apply_delete_accounting_results(&mut accounting, &set_objects, &set_accounting);
while let Some((indices, deleted, errors, set_accounting)) = pending.next().await {
apply_delete_objects_results(&mut del_objects, &mut del_errs, &indices, deleted, errors);
apply_delete_accounting_results(&mut accounting, &indices, set_accounting);
}
(del_objects, del_errs, accounting)
@@ -1569,35 +1586,14 @@ mod tests {
let mut del_objects = vec![DeletedObject::default(); 3];
let mut del_errs = vec![None, None, None];
let early_batch = vec![DelObj {
orig_idx: 1,
obj: ObjectToDelete {
object_name: "second".to_string(),
..Default::default()
},
}];
let early_indices = [1];
let early_objects = vec![DeletedObject {
object_name: "second".to_string(),
found: true,
..Default::default()
}];
let late_batch = vec![
DelObj {
orig_idx: 2,
obj: ObjectToDelete {
object_name: "third".to_string(),
..Default::default()
},
},
DelObj {
orig_idx: 0,
obj: ObjectToDelete {
object_name: "first".to_string(),
..Default::default()
},
},
];
let late_indices = [2, 0];
let late_objects = vec![
DeletedObject {
object_name: "third".to_string(),
@@ -1611,12 +1607,12 @@ mod tests {
},
];
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_batch, &early_objects, vec![None]);
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_indices, early_objects, vec![None]);
apply_delete_objects_results(
&mut del_objects,
&mut del_errs,
&late_batch,
&late_objects,
&late_indices,
late_objects,
vec![Some(Error::other("third failed")), None],
);
+74
View File
@@ -58,6 +58,7 @@ type SharedDataMovementStream = Arc<Mutex<Box<dyn AsyncRead + Unpin + Send + Syn
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DATA_MOVEMENT: &str = "data_movement";
const EVENT_DATA_MOVEMENT_MULTIPART_ABORT_FAILED: &str = "data_movement_multipart_abort_failed";
const EVENT_DATA_MOVEMENT_EQUIVALENT_TARGET: &str = "data_movement_equivalent_target";
const DATA_MOVEMENT_MULTIPART_ABORT_RETRY_ATTEMPTS: usize = 3;
const DATA_MOVEMENT_MULTIPART_ABORT_RETRY_DELAY_SECS: u64 = 60;
@@ -1636,6 +1637,57 @@ async fn find_data_movement_target_info(
}
}
/// The pool that already holds this exact source version, for a caller that
/// carries no decommission capacity owner: rebalance, and a decommission
/// without a capacity reservation. A run that stops after the target commit
/// and before the source cleanup leaves the version in both pools; without
/// this lookup the next run uploads every part again and learns of the copy
/// only when the create-only completion is refused. Only the strict identity
/// match settles here; the looser matches stay with the completion path. A
/// lookup that fails or finds no equivalent copy leaves the decision to the
/// normal path, which repeats the lookup and reports its own stage.
///
/// The caller removes the source on this answer, so the copy must also be on
/// a write quorum of the target set's drives. The object read behind the
/// identity match answers from read quorum; a copy held only there leaves the
/// decision to the normal path too, which needs a write quorum to start.
async fn find_equivalent_multipart_target(
store: &ECStore,
src_pool_idx: usize,
bucket: &str,
object_info: &ObjectInfo,
new_multipart_opts: &ObjectOptions,
compare_part_checksums: bool,
) -> Option<usize> {
let target_pool_idx = store
.select_data_movement_pool_idx(bucket, &object_info.name, -1, new_multipart_opts, false)
.await
.ok()?;
if !should_check_data_movement_resume_target(src_pool_idx, target_pool_idx) {
return None;
}
let target = find_data_movement_target_info(store, target_pool_idx, bucket, object_info)
.await
.ok()??;
if !is_equivalent_data_movement_object_identity(object_info, &target, true, compare_part_checksums) {
return None;
}
let object = encode_dir_object(object_info.name.as_str());
store
.pools
.get(target_pool_idx)?
.get_disks_by_key(object.as_str())
.holds_version_on_write_quorum(
bucket,
object.as_str(),
object_info.version_id.unwrap_or_else(uuid::Uuid::nil),
target.data_dir,
)
.await
.ok()?
.then_some(target_pool_idx)
}
/// How a data-movement copy settled on its target pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DataMovementCopy {
@@ -2012,6 +2064,28 @@ async fn migrate_object_inner(
)
})?;
}
} else if let Some(target_pool_idx) = find_equivalent_multipart_target(
store.as_ref(),
pool_idx,
&bucket,
&object_info,
&new_multipart_opts,
preserve_part_checksums,
)
.await
{
info!(
event = EVENT_DATA_MOVEMENT_EQUIVALENT_TARGET,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DATA_MOVEMENT,
result = "skipped",
operation = op_label,
bucket = bucket.as_str(),
object = object_info.name.as_str(),
target_pool = target_pool_idx,
"data movement multipart copy skipped for an equivalent target"
);
return Ok(DataMovementCopy::Committed);
}
let (res, target_pool_idx, expected_bucket_incarnation_id) = match store
.handle_new_multipart_upload_with_pool_idx(
+165 -55
View File
@@ -230,50 +230,126 @@ pub async fn lookup_degraded_bucket_usage_baseline(store: Arc<ECStore>, bucket:
.and_then(|cached| cached.degraded_baseline.get(bucket).copied())
}
/// Whether a cached usage snapshot can certify the current bucket's byte count.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsageStatus {
Certified(u64),
Pending(BucketUsagePendingReason),
Unavailable(BucketUsageUnavailableReason),
}
/// Why otherwise readable usage cannot yet certify this bucket.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsagePendingReason {
SnapshotNotReady,
BucketPending,
MissingBucketProof,
PreviousIncarnation,
}
/// Which part of a purported certification was invalid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsageUnavailableReason {
InvalidSnapshotProof,
InvalidBucketIncarnation,
}
#[derive(Debug, Clone, Copy)]
enum SnapshotCertification {
Ready,
Pending,
Invalid,
}
/// An immutable sample with its bucket certification metadata checked once.
#[derive(Debug, Clone)]
struct UsageSnapshot {
info: DataUsageInfo,
can_certify_buckets: bool,
certification: SnapshotCertification,
}
impl UsageSnapshot {
fn new(info: DataUsageInfo) -> Self {
let pending = &info.usage_snapshot_pending_buckets;
let can_certify_buckets = info.is_complete_bucket_usage_snapshot()
&& !info.usage_snapshot_observational
&& info.scanner_cycle.is_some()
&& info.scanner_epoch.is_some()
&& u64::try_from(pending.len()).ok() == Some(info.usage_snapshot_pending_bucket_count)
&& match info.usage_snapshot_converged {
Some(true) => pending.is_empty(),
Some(false) => !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]),
None => false,
};
Self {
info,
can_certify_buckets,
}
fn new(info: DataUsageInfo, invalid_certification_claim: bool) -> Self {
let certification = if invalid_certification_claim
|| info.usage_snapshot_admin_projection
|| (info.usage_snapshot_complete && (info.usage_snapshot_partial || info.usage_snapshot_bootstrap_pending))
{
SnapshotCertification::Invalid
} else if info.usage_snapshot_bootstrap_pending || info.usage_snapshot_observational || !info.usage_snapshot_complete {
SnapshotCertification::Pending
} else if !info.is_complete_bucket_usage_snapshot() {
SnapshotCertification::Invalid
} else {
let pending = &info.usage_snapshot_pending_buckets;
if u64::try_from(pending.len()).ok() != Some(info.usage_snapshot_pending_bucket_count) {
SnapshotCertification::Invalid
} else {
match info.usage_snapshot_converged {
Some(true) if pending.is_empty() => SnapshotCertification::Ready,
Some(false) if !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]) => {
SnapshotCertification::Ready
}
None if pending.is_empty() => SnapshotCertification::Pending,
_ => SnapshotCertification::Invalid,
}
}
};
let certification = match certification {
SnapshotCertification::Ready if info.scanner_cycle.is_none() || info.scanner_epoch.is_none() => {
SnapshotCertification::Pending
}
other => other,
};
Self { info, certification }
}
fn clone_info(&self) -> DataUsageInfo {
self.info.clone()
}
fn certified_bucket_usage(&self, bucket: &str, incarnation: uuid::Uuid) -> Option<u64> {
if !self.can_certify_buckets
|| incarnation.is_nil()
|| self
.info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_ok()
{
return None;
fn bucket_usage_certification(&self, bucket: &str, incarnation: uuid::Uuid) -> BucketUsageStatus {
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
use BucketUsageStatus::{Certified, Pending, Unavailable};
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
if incarnation.is_nil() {
return Unavailable(InvalidBucketIncarnation);
}
match self.certification {
SnapshotCertification::Invalid => return Unavailable(InvalidSnapshotProof),
SnapshotCertification::Pending => return Pending(SnapshotNotReady),
SnapshotCertification::Ready => {}
}
if self
.info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_ok()
{
return Pending(BucketPending);
}
let Some((usage, proof)) = self
.info
.buckets_usage
.get(bucket)
.and_then(|usage| usage.bucket_incarnation.as_deref().map(|proof| (usage, proof)))
else {
return Pending(MissingBucketProof);
};
match uuid::Uuid::parse_str(proof) {
Ok(id) if id == incarnation => Certified(usage.size),
Ok(id) if !id.is_nil() => Pending(PreviousIncarnation),
_ => Unavailable(InvalidBucketIncarnation),
}
}
}
impl BucketUsageStatus {
fn certified_bytes(self) -> Option<u64> {
match self {
Self::Certified(bytes) => Some(bytes),
Self::Pending(_) | Self::Unavailable(_) => None,
}
let usage = self.info.buckets_usage.get(bucket)?;
let certified = uuid::Uuid::parse_str(usage.bucket_incarnation.as_deref()?).ok()?;
(certified == incarnation).then_some(usage.size)
}
}
@@ -330,6 +406,7 @@ fn cache_data_usage_snapshot_result<T>(
Some(match result {
Ok(LoadedUsageBaseline {
info,
invalid_certification_claim,
mut degraded_baseline,
observed_unavailable,
}) => {
@@ -352,7 +429,7 @@ fn cache_data_usage_snapshot_result<T>(
degraded_baseline.entry(bucket.clone()).or_insert(*size);
}
}
let snapshot = UsageSnapshot::new(info);
let snapshot = UsageSnapshot::new(info, invalid_certification_claim);
let projected = project(&snapshot);
*cache = Some(CachedDataUsageSnapshot {
snapshot: Some(snapshot),
@@ -1349,6 +1426,8 @@ pub async fn load_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataUsa
/// baseline derived from it.
struct LoadedUsageBaseline {
info: DataUsageInfo,
/// Certification failures detected before normalization can demote the sample.
invalid_certification_claim: bool,
degraded_baseline: HashMap<String, u64>,
/// True when the observed snapshot could not be read (a transport error,
/// not absence): the cached loader then carries the previous refresh's
@@ -1365,7 +1444,8 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
// The observed-newness gate below compares against the snapshot as
// persisted, before normalization demotes or discards anything.
let authoritative_as_persisted = loaded_snapshot.snapshot_identity();
let (info, mut degraded_baseline) = normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
let (info, mut degraded_baseline, invalid_certification_claim) =
normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
// A bucket without a converged scanner cycle behind it — a freshly joined
// replica whose every cycle is superseded by the sustained replication
@@ -1391,6 +1471,7 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
Ok(LoadedUsageBaseline {
info,
invalid_certification_claim,
degraded_baseline,
observed_unavailable,
})
@@ -1570,10 +1651,12 @@ fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
}
}
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) {
if data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot() {
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) -> bool {
let invalid_complete_claim = data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot();
if invalid_complete_claim {
data_usage_info.usage_snapshot_complete = false;
}
invalid_complete_claim
}
fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo) {
@@ -1608,14 +1691,16 @@ fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo)
async fn normalize_loaded_data_usage(
mut data_usage_info: DataUsageInfo,
authoritative_format: bool,
) -> (DataUsageInfo, HashMap<String, u64>) {
) -> (DataUsageInfo, HashMap<String, u64>, bool) {
info!("Loaded data usage info from backend with {} buckets", data_usage_info.buckets_count);
if !authoritative_format {
data_usage_info.usage_snapshot_complete = false;
}
populate_backward_compatible_usage_maps(&mut data_usage_info);
validate_complete_usage_snapshot(&mut data_usage_info);
let invalid_complete_claim = validate_complete_usage_snapshot(&mut data_usage_info);
let invalid_certification_claim =
invalid_complete_claim || (authoritative_format && data_usage_info.usage_snapshot_observational);
let degraded_baseline = data_usage_info.bucket_sizes.clone();
discard_incomplete_bucket_usage(&mut data_usage_info);
@@ -1642,7 +1727,7 @@ async fn normalize_loaded_data_usage(
}
}
(data_usage_info, degraded_baseline)
(data_usage_info, degraded_baseline, invalid_certification_claim)
}
/// Load the persisted data usage snapshot through a small in-process cache.
@@ -1663,7 +1748,21 @@ pub async fn load_bucket_usage_from_backend_cached(
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, Error> {
project_data_usage_from_backend_cached(store, |snapshot| snapshot.certified_bucket_usage(bucket, incarnation)).await
Ok(load_bucket_usage_certification_from_backend_cached(store, bucket, incarnation)
.await?
.certified_bytes())
}
/// Inspect the certification for one bucket in the cached authoritative usage snapshot.
///
/// # Errors
/// Returns an error when the snapshot cannot be read or decoded.
pub async fn load_bucket_usage_certification_from_backend_cached(
store: Arc<ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<BucketUsageStatus, Error> {
project_data_usage_from_backend_cached(store, |snapshot| snapshot.bucket_usage_certification(bucket, incarnation)).await
}
// Project under the cache guard so scalar readers never copy the snapshot's
@@ -1745,6 +1844,7 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<Da
.map(|info| LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
});
let loaded_at = tokio::time::Instant::now();
@@ -3970,7 +4070,7 @@ mod tests {
legacy.bucket_sizes.insert("large".to_string(), 0);
legacy.buckets_count = 2;
let (normalized, degraded_baseline) = normalize_loaded_data_usage(legacy, false).await;
let (normalized, degraded_baseline, _) = normalize_loaded_data_usage(legacy, false).await;
assert_eq!(normalized.buckets_count, 0);
assert!(normalized.buckets_usage.is_empty());
@@ -4017,7 +4117,7 @@ mod tests {
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
info.buckets_count = 2;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 2);
assert!(normalized.usage_snapshot_complete);
@@ -4052,7 +4152,7 @@ mod tests {
info.bucket_sizes.insert("partial".to_string(), 196_870_144);
info.buckets_count = 1;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 0);
assert!(!normalized.buckets_usage.contains_key("control"));
@@ -4067,7 +4167,7 @@ mod tests {
info.buckets_count = 2;
assert!(!data_usage_contains_bucket(&info, "missing"));
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert!(!normalized.usage_snapshot_complete);
assert!(normalized.buckets_usage.is_empty());
@@ -4076,7 +4176,7 @@ mod tests {
#[tokio::test]
async fn complete_empty_snapshot_remains_authoritative() {
let (normalized, _) = normalize_loaded_data_usage(
let (normalized, _, _) = normalize_loaded_data_usage(
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
usage_snapshot_complete: true,
@@ -4341,7 +4441,7 @@ mod tests {
async fn partial_admin_observation_does_not_promote_a_legacy_baseline() {
let (legacy, observed) = usage_snapshots_with_missing_observed_set();
let (selected, current_format) = select_admin_data_usage_snapshot(legacy, false, Some(observed));
let (normalized, _) = normalize_loaded_data_usage(selected, current_format).await;
let (normalized, _, _) = normalize_loaded_data_usage(selected, current_format).await;
assert!(normalized.is_valid_partial_snapshot());
assert!(!normalized.is_complete_bucket_usage_snapshot());
@@ -4463,7 +4563,7 @@ mod tests {
async fn install_data_usage_snapshot_cache_for_test(info: DataUsageInfo, age: Duration) {
let degraded_baseline = info.bucket_sizes.clone();
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now()
.checked_sub(age)
@@ -4499,6 +4599,7 @@ mod tests {
LoadedUsageBaseline {
degraded_baseline: info.bucket_sizes.clone(),
info,
invalid_certification_claim: false,
observed_unavailable: false,
}
}
@@ -4919,6 +5020,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: expected,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -5118,7 +5220,7 @@ mod tests {
observed.usage_snapshot_converged = Some(false);
observed.usage_snapshot_authoritative_baseline = Some(baseline.snapshot_identity());
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(observed)),
snapshot: Some(UsageSnapshot::new(observed, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5157,7 +5259,7 @@ mod tests {
(loaded.scanner_epoch, loaded.scanner_cycle) = loaded_position;
let expected = if accept { &loaded } else { &previous };
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(previous.clone())),
snapshot: Some(UsageSnapshot::new(previous.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5184,7 +5286,7 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let expected = data_usage_info_for_test("bucket", 3, 42, SystemTime::UNIX_EPOCH + Duration::from_secs(2));
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(expected.clone())),
snapshot: Some(UsageSnapshot::new(expected.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("bucket".to_string(), 42)]),
@@ -5230,7 +5332,7 @@ mod tests {
let now = SystemTime::now();
let future = now + rustfs_data_usage::USAGE_LAST_UPDATE_FUTURE_TOLERANCE + Duration::from_secs(60);
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future))),
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5329,7 +5431,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("observed-only".to_string(), 7_u64), ("covered".to_string(), 1)]),
@@ -5340,6 +5445,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::from([("covered".to_string(), 2_u64)]),
invalid_certification_claim: false,
observed_unavailable: true,
}),
loaded_at,
@@ -5363,7 +5469,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5375,6 +5484,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -6552,7 +6662,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6624,7 +6734,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6677,7 +6787,7 @@ mod tests {
};
let stale = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(stale)),
snapshot: Some(UsageSnapshot::new(stale, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -8127,7 +8237,7 @@ mod tests {
// memory. Selecting that newer view must not erase local mutations.
let (selected, current_format) = select_admin_data_usage_snapshot(baseline, true, Some(observed));
assert_eq!(selected.scanner_cycle, Some(11));
let (selected, _) = normalize_loaded_data_usage(selected, current_format).await;
let (selected, _, _) = normalize_loaded_data_usage(selected, current_format).await;
let mut distributed = selected.clone();
apply_bucket_usage_memory_overlay_if_authoritative(&mut distributed, false).await;
assert_eq!((distributed.objects_total_count, distributed.objects_total_size), (2, 20));
@@ -82,10 +82,9 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
assert!(reject_admin_usage_projection(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert!(
UsageSnapshot::new(snapshot)
.certified_bucket_usage("bucket", incarnation)
.is_none()
assert_eq!(
UsageSnapshot::new(snapshot, false).bucket_usage_certification("bucket", incarnation),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
}
@@ -381,10 +380,9 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert!(
UsageSnapshot::new(second)
.certified_bucket_usage(bucket, new_identity)
.is_none()
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let quota = load_data_usage_from_backend_cached(store.clone())
.await
@@ -20,7 +20,7 @@ fn scalar_projection_borrows_snapshot_and_preserves_unknown_and_zero() {
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
let cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -66,7 +66,10 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
);
cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -78,6 +81,7 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -99,6 +103,7 @@ fn projected_publication_moves_bucket_maps_into_cache() {
Ok(LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
tokio::time::Instant::now(),
@@ -167,41 +172,106 @@ fn projected_publication_moves_bucket_maps_into_cache() {
}
#[test]
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
fn bucket_usage_certification_distinguishes_pending_and_unavailable_proof() {
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
use BucketUsageStatus::{Certified, Pending, Unavailable};
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
let id = uuid::Uuid::from_u128(7);
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone());
assert_eq!(certified.certified_bucket_usage("known", id), Some(42));
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::from_u128(8)), None);
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::nil()), None);
let mut legacy = info.clone();
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
assert_eq!(UsageSnapshot::new(legacy.clone()).certified_bucket_usage("known", id), None);
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
assert_eq!(UsageSnapshot::new(legacy).certified_bucket_usage("known", id), None);
let mut pending = info.clone();
pending.usage_snapshot_converged = Some(false);
pending.usage_snapshot_pending_buckets = vec!["other".into()];
pending.usage_snapshot_pending_bucket_count = 1;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), Some(42));
pending.usage_snapshot_pending_buckets = vec!["known".into()];
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_bucket_count = 0;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
pending.usage_snapshot_pending_bucket_count = 2;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["other".into(), "other".into()];
assert_eq!(UsageSnapshot::new(pending).certified_bucket_usage("known", id), None);
let mut observational = info.clone();
observational.usage_snapshot_observational = true;
assert_eq!(UsageSnapshot::new(observational).certified_bucket_usage("known", id), None);
info.usage_snapshot_converged = None;
assert_eq!(UsageSnapshot::new(info).certified_bucket_usage("known", id), None);
info.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone(), false);
assert_eq!(certified.bucket_usage_certification("known", id), Certified(42));
assert_eq!(certified.bucket_usage_certification("missing", id), Pending(MissingBucketProof));
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::from_u128(8)),
Pending(PreviousIncarnation)
);
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::nil()),
Unavailable(InvalidBucketIncarnation)
);
for (proof, expected) in [
(None, Pending(MissingBucketProof)),
(Some("corrupt".into()), Unavailable(InvalidBucketIncarnation)),
(Some(uuid::Uuid::nil().to_string()), Unavailable(InvalidBucketIncarnation)),
] {
let mut sample = info.clone();
sample
.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = proof;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for (names, count, expected) in [
(vec!["other"], 1, Certified(42)),
(vec!["known"], 1, Pending(BucketPending)),
(vec!["known"], 0, Unavailable(InvalidSnapshotProof)),
(vec!["z", "a"], 2, Unavailable(InvalidSnapshotProof)),
(vec!["other", "other"], 2, Unavailable(InvalidSnapshotProof)),
(vec![], 0, Unavailable(InvalidSnapshotProof)),
] {
let mut sample = info.clone();
sample.usage_snapshot_converged = Some(false);
sample.usage_snapshot_pending_buckets = names.into_iter().map(str::to_owned).collect();
sample.usage_snapshot_pending_bucket_count = count;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for sample in [
DataUsageInfo {
usage_snapshot_partial: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
usage_snapshot_converged: Some(false),
usage_snapshot_pending_buckets: vec!["known".into()],
..info.clone()
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Unavailable(InvalidSnapshotProof)
);
}
let bootstrap = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
..Default::default()
};
for sample in [
DataUsageInfo::default(),
bootstrap,
DataUsageInfo {
usage_snapshot_observational: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
..info.clone()
},
DataUsageInfo {
usage_snapshot_converged: None,
..info
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Pending(SnapshotNotReady)
);
}
}
#[tokio::test]
@@ -296,12 +366,55 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
.expect("persist malformed certification evidence");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", incarnation)
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("read snapshot without accepting malformed certification"),
None
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
assert_eq!(persisted_bucket_usage(store.clone(), "known").await, Some(84));
info.scanner_cycle = Some(3);
info.usage_snapshot_converged = Some(true);
info.usage_snapshot_pending_bucket_count = 0;
info.usage_snapshot_pending_buckets.clear();
info.buckets_count += 1;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode invalid bucket count"),
)
.await
.expect("persist malformed completeness claim");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify demoted completeness claim"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let raw = load_data_usage_from_backend_cached(store.clone())
.await
.expect("read normalized usage");
assert!(!raw.usage_snapshot_complete);
assert!(raw.buckets_usage.is_empty());
info.scanner_cycle = Some(4);
info.buckets_count -= 1;
info.usage_snapshot_observational = true;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode observational sample in primary slot"),
)
.await
.expect("persist wrong snapshot kind");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify wrong snapshot kind"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
invalidate_data_usage_snapshot_cache().await;
if let Some(cancel) = store.ctx.background_cancel_token() {
cancel.cancel();
+3 -3
View File
@@ -645,7 +645,7 @@ impl LocalDiskWrapper {
get_max_timeout_duration()
};
let observed = run_owned_mutation(external_guard, move || async move {
let mut preflight_rejection = None;
let mut rejected_before_publication = false;
let result = operation
.track_disk_health_mutation(
"rename_data",
@@ -661,7 +661,7 @@ impl LocalDiskWrapper {
namespace_owner,
))
.await;
preflight_rejection = observed.preflight_rejection;
rejected_before_publication = observed.rejected_before_publication();
observed.result
},
timeout_duration,
@@ -670,7 +670,7 @@ impl LocalDiskWrapper {
// Health tracking must observe the real disk error, not an Ok tuple.
Ok(super::RenameDataObservation {
result,
preflight_rejection,
rejected_before_publication,
})
})
.await;
+410 -94
View File
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub(in crate::disk) use self::commit::LocalRenamePreflightRejection;
#[cfg(test)]
#[path = "local/read_path_tests.rs"]
mod read_path_tests;
@@ -817,31 +816,46 @@ fn rename_in_same_dir_fd(
}
#[cfg(unix)]
fn part_txn_files_ready_with_stamp(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_st = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.ok()
.filter(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG)?;
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return new_ok.then(|| multipart_source_state::FileStamp::from_stat(&pub_st));
}
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(not(unix))]
fn part_txn_files_ready_with_stamp(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(test)]
fn part_txn_files_ready(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_ok = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG);
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return pub_ok && new_ok;
}
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
}
#[cfg(not(unix))]
fn part_txn_files_ready(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
part_txn_files_ready_with_stamp(txn_dir_fd, publish_meta_path, transaction_meta_path, expected_len).is_some()
}
#[cfg(unix)]
@@ -914,9 +928,12 @@ struct PreparedPartTxnReceipt {
dst_meta_path: PathBuf,
transaction_path: PathBuf,
meta: Bytes,
part_info: ObjectPartInfo,
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
src_parent_fd: Option<Arc<std::fs::File>>,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
@@ -929,6 +946,8 @@ struct PublishedPartTxnReceipt {
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
}
@@ -978,7 +997,7 @@ fn restore_part_transaction_file(current: &Path, backup: &Path, absent: &Path, r
}
}
#[cfg(test)]
#[cfg(all(test, not(windows)))]
async fn write_metadata_rollback_backup(object_dir: &Path, rollback_dir: Uuid, data: &[u8]) -> Result<()> {
write_delete_rollback_file(
object_dir.parent().unwrap_or(object_dir),
@@ -5026,7 +5045,7 @@ impl LazyLocalFileWriter {
let sync_on_close = self.sync_on_close;
let mark_dir_presynced = self.mark_dir_presynced;
let parent_exists = self.parent_exists;
let volume_dir_for_presync = self.volume_dir.clone();
let volume_dir_for_presync = (close_after && sync_on_close).then(|| self.volume_dir.clone());
self.last_integrity_digest = None;
let write_and_finish = move |mut file: std::fs::File, file_path: PathBuf| {
let digest = match integrity_spec {
@@ -5054,8 +5073,8 @@ impl LazyLocalFileWriter {
}
reclaim_std_file_cache(&file, reclaim_len, reclaim_on_shutdown);
drop(file);
if sync_on_close {
mark_presynced_after_lazy_write(&file_path, &volume_dir_for_presync, mark_dir_presynced);
if let Some(ref volume_dir) = volume_dir_for_presync {
mark_presynced_after_lazy_write(&file_path, volume_dir, mark_dir_presynced);
}
Ok((None, wire_len, digest))
} else {
@@ -9324,10 +9343,29 @@ impl LocalDisk {
}
let path = trash.join(name);
let result = async {
if entry.file_type().await?.is_dir() {
fs::remove_dir_all(&path).await
} else {
fs::remove_file(&path).await
let is_dir = entry.file_type().await?.is_dir();
#[cfg(windows)]
{
// Competing recursive deletions can deny each other's directory
// handles. Keep ownership until the blocking operation returns.
let lease = os::acquire_namespace_mutation_lease_with_owner(&path, None).await;
let path = path.clone();
os::run_blocking_namespace_operation(lease, move || {
if is_dir {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
}
})
.await
}
#[cfg(not(windows))]
{
if is_dir {
fs::remove_dir_all(&path).await
} else {
fs::remove_file(&path).await
}
}
}
.await;
@@ -14900,12 +14938,36 @@ const LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES: usize = 512 * 1024;
/// multi-disk topologies. When every window reaches
/// `LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES`, each shard gets its own dispatch so
/// copies and device reads proceed concurrently.
#[cfg(unix)]
///
/// Enforces the process-wide in-flight read memory budget before allocating
/// shard buffers and binds each permit to the returned [`Bytes`] lifetime.
#[cfg(all(unix, test))]
pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
let lengths: Vec<usize> = requests.iter().map(|(_, _, length)| *length).collect();
let Some(permits) = crate::set_disk::read_budget::global_in_flight_read_budget().try_reserve_batch(&lengths) else {
return (0..requests.len())
.map(|_| Err(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error()))
.collect();
};
let permitted = requests
.into_iter()
.zip(permits)
.map(|((path, offset, length), permit)| (path, offset, length, permit))
.collect();
batch_shard_pread_with_permits(permitted).await
}
#[cfg(unix)]
pub(crate) type PermittedShardPreadRequest = (std::path::PathBuf, usize, usize, crate::set_disk::read_budget::ReadMemoryPermit);
/// Positioned reads for local EC shard files with pre-reserved in-flight byte
/// permits, returned in request order.
#[cfg(unix)]
pub(crate) async fn batch_shard_pread_with_permits(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
if requests.len() < 2
|| requests
.iter()
.any(|(_, _, length)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
.any(|(_, _, length, _)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
{
return batch_shard_pread_blocking(requests).await;
}
@@ -14918,7 +14980,7 @@ pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize,
/// Read every request in turn inside one `spawn_blocking`.
#[cfg(unix)]
async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
let n = requests.len();
let metrics = rustfs_io_metrics::LocalBatchReadMetrics::capture();
let submitted = metrics.as_ref().map(|_| std::time::Instant::now());
@@ -14961,7 +15023,7 @@ async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, us
metrics.record_batch(n);
}
let mut results = Vec::with_capacity(n);
for (file_path, offset, length) in requests {
for (file_path, offset, length, permit) in requests {
#[cfg(feature = "diagnostic-local-batch")]
let _index = results.len();
let mut total = 0usize;
@@ -15042,7 +15104,7 @@ async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, us
}
))?;
}
Ok(Bytes::from(buf))
Ok(permit.wrap_vec(buf))
})();
#[cfg(feature = "diagnostic-local-batch")]
if let Some(sample) = &diagnostic {
@@ -15088,6 +15150,18 @@ fn measure_local_batch_stage<T>(
result
}
impl LocalDisk {
async fn check_deferred_org_volume(&self, org_volume: &str) -> Result<()> {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
Ok(())
}
}
#[async_trait::async_trait]
impl DiskAPI for LocalDisk {
async fn list_multipart_index_roots(
@@ -15871,9 +15945,9 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?;
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let (src_volume_dir, src_file_path) = self.io_get_bucket_and_object_path(src_volume, src_path)?;
let (dst_volume_dir, dst_file_path) = self.io_get_bucket_and_object_path(dst_volume, dst_path)?;
let admission = self.multipart_source_admission_after_validated_part_path(dst_volume, dst_path)?;
@@ -15892,7 +15966,7 @@ impl DiskAPI for LocalDisk {
let durability = effective_durability(dst_volume);
let part = ObjectPartInfo::unmarshal(&meta)?;
let integrity_prep = if let Some(integrity) = part.integrity {
let integrity_prep = if let Some(integrity) = part.integrity.clone() {
integrity.validate()?;
if usize::try_from(integrity.number).map_err(|_| DiskError::FileCorrupt)? != part.number
|| usize::try_from(integrity.size).map_err(|_| DiskError::FileCorrupt)? != part.size
@@ -15917,7 +15991,13 @@ impl DiskAPI for LocalDisk {
multipart_source_state::begin_active_multipart_part_transaction(source, part.number);
}
os::record_native_publication(&transaction_path);
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
let txn_namespace_lock = os::lookup_namespace_mutation_lock(&transaction_path);
let lease = os::acquire_namespace_mutation_lease_with_lock_and_queue(
&txn_namespace_lock,
Arc::clone(&self.blocking_queue),
source_owner,
)
.await;
let res = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
@@ -16243,9 +16323,12 @@ impl DiskAPI for LocalDisk {
dst_meta_path,
transaction_path,
meta,
part_info: part,
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16271,10 +16354,21 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn settle_part_transaction(&self, volume: &str, path: &str, action: PartTransactionAction) -> Result<()> {
multipart_staging::reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
let usage_owner = self.usage_watch_binding.owner(volume, None);
let source_owner = self.multipart_source_owner(volume, path, true, false, usage_owner).await?;
let txn_rel_path = crate::disk::part_transaction_path(path);
let txn_open_path = self.io_get_object_open_path(volume, &txn_rel_path).ok();
let cached_upload_lock = txn_open_path.as_deref().and_then(|txn_open| {
PUBLISHED_PART_TXN_RECEIPTS
.with_get(txn_open, |entry| entry.upload_lock.clone())
.or_else(|| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()))
});
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(volume, path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let cached_published = txn_open_path.as_deref().and_then(take_published_part_txn_receipt);
if cached_published.is_none()
&& let Some(ref txn_open) = txn_open_path
@@ -16288,6 +16382,7 @@ impl DiskAPI for LocalDisk {
skip_obsolete_read_on_commit,
cached_old_flags,
admission,
cached_txn_namespace_lock,
mut txn_dir_fd,
mut txn_parent_fd,
) = match cached_published {
@@ -16298,6 +16393,7 @@ impl DiskAPI for LocalDisk {
!entry.had_old_meta,
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.txn_namespace_lock),
entry.txn_dir_fd,
entry.txn_parent_fd,
),
@@ -16309,7 +16405,17 @@ impl DiskAPI for LocalDisk {
for candidate in [&current_data_path, &current_meta_path, &transaction_path] {
check_path_length(candidate.to_string_lossy().as_ref())?;
}
(current_data_path, current_meta_path, transaction_path, false, None, admission, None, None)
(
current_data_path,
current_meta_path,
transaction_path,
false,
None,
admission,
None,
None,
None,
)
}
};
let admission_source = admission.as_ref().map(|a| a.source().to_path_buf());
@@ -16320,7 +16426,16 @@ impl DiskAPI for LocalDisk {
.and_then(|name| name.to_str())
.and_then(|name| name.strip_prefix("part."))
.and_then(|num| num.parse::<usize>().ok());
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
let lease = match cached_txn_namespace_lock {
Some(ref lock) => {
os::acquire_namespace_mutation_lease_with_lock_and_queue(lock, Arc::clone(&self.blocking_queue), source_owner)
.await
}
None => {
os::acquire_namespace_mutation_lease_with_queue(&transaction_path, Arc::clone(&self.blocking_queue), source_owner)
.await
}
};
os::record_native_publication(&current_data_path);
let res = os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<Result<bool>> {
@@ -16484,14 +16599,26 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
let txn_open_path = (!src_is_dir)
.then(|| {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel).ok()
})
.flatten();
let cached_upload_lock = txn_open_path
.as_deref()
.and_then(|txn_open| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()));
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
multipart_staging::reject_reserved_anchor(dst_path)?;
pool_meta_native::reject_raw_path(&self.root, src_volume, src_path)?;
pool_meta_native::reject_raw_path(&self.root, dst_volume, dst_path)?;
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
if !src_is_dir && dst_is_dir || src_is_dir && !dst_is_dir {
warn!(
@@ -16506,20 +16633,15 @@ impl DiskAPI for LocalDisk {
return Err(DiskError::FileAccessDenied);
}
let cached_prepared = if !src_is_dir {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel)
.ok()
.and_then(|txn_open| take_prepared_part_txn_receipt(&txn_open))
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
})
} else {
None
};
let cached_prepared = txn_open_path
.as_deref()
.and_then(take_prepared_part_txn_receipt)
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
});
let (
src_volume_dir,
@@ -16530,6 +16652,8 @@ impl DiskAPI for LocalDisk {
transaction_path,
preverified_meta_and_old_flags,
admission,
cached_part_info,
cached_txn_namespace_lock,
mut src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16543,6 +16667,8 @@ impl DiskAPI for LocalDisk {
Some(entry.transaction_path),
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.part_info),
Some(entry.txn_namespace_lock),
entry.src_parent_fd,
entry.txn_dir_fd,
entry.txn_parent_fd,
@@ -16585,6 +16711,8 @@ impl DiskAPI for LocalDisk {
None,
None,
None,
None,
None,
)
}
};
@@ -16601,12 +16729,20 @@ impl DiskAPI for LocalDisk {
let src_file_for_cleanup = src_file_path.clone();
let src_volume_for_cleanup = src_volume_dir.clone();
let meta_for_legacy = meta.clone();
let lease = os::acquire_namespace_mutation_lease_with_owner(&dst_file_path, source_owner.clone()).await;
let lease = os::acquire_namespace_mutation_lease_with_queue(
&dst_file_path,
Arc::clone(&self.blocking_queue),
source_owner.clone(),
)
.await;
let published_transaction_meta = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
move || -> std::io::Result<(bool, Option<(PathBuf, PublishedPartTxnReceipt)>)> {
type RenamePartOutcome = (
bool,
Option<multipart_source_state::FileStamp>,
Option<(PathBuf, PublishedPartTxnReceipt)>,
);
let published_transaction_meta =
os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<RenamePartOutcome> {
if let Some(check) = &admission {
check.validate().map_err(to_file_error)?;
}
@@ -16658,18 +16794,20 @@ impl DiskAPI for LocalDisk {
}
}
let mut precomputed_publish_stamp = None;
let transaction_publish_meta = if let Some(transaction_path) = transaction_path.as_ref() {
let transaction_meta_path = transaction_path.join(PART_TRANSACTION_NEW_META);
let publish_meta_path = transaction_path.join(PART_TRANSACTION_PUBLISH_META);
if !cfg!(test)
&& preverified_meta_and_old_flags.is_some()
&& part_txn_files_ready(
&& let Some(stamp) = part_txn_files_ready_with_stamp(
txn_dir_fd.as_deref(),
&publish_meta_path,
&transaction_meta_path,
meta.len() as u64,
)
{
precomputed_publish_stamp = stamp;
Some(publish_meta_path)
} else {
match std::fs::File::open(&transaction_meta_path) {
@@ -16827,6 +16965,7 @@ impl DiskAPI for LocalDisk {
let fast_meta_renamed = false;
if !fast_meta_renamed {
precomputed_publish_stamp = None;
os::rename_all_with_precondition_and_parent_sync_std(
&transaction_publish_meta,
dst_meta_path,
@@ -16858,6 +16997,8 @@ impl DiskAPI for LocalDisk {
let published_entry = if let (Some((had_old_data, had_old_meta)), Some(txn_path), Some(meta_path)) =
(preverified_meta_and_old_flags, transaction_path, dst_meta_path.as_path().into())
{
let txn_namespace_lock =
cached_txn_namespace_lock.unwrap_or_else(|| os::lookup_namespace_mutation_lock(&txn_path));
Some((
txn_path.clone(),
PublishedPartTxnReceipt {
@@ -16867,6 +17008,8 @@ impl DiskAPI for LocalDisk {
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
txn_dir_fd,
txn_parent_fd,
},
@@ -16874,20 +17017,19 @@ impl DiskAPI for LocalDisk {
} else {
None
};
Ok((true, published_entry))
Ok((true, precomputed_publish_stamp, published_entry))
} else {
Ok((false, None))
Ok((false, None, None))
}
},
)
.await
.map_err(DiskError::from);
let published_transaction_meta = match published_transaction_meta {
Ok((published, maybe_entry)) => {
})
.await
.map_err(DiskError::from);
let (published_transaction_meta, precomputed_publish_stamp) = match published_transaction_meta {
Ok((published, stamp, maybe_entry)) => {
if let Some((txn_path, entry)) = maybe_entry {
put_published_part_txn_receipt(&txn_path, entry);
}
published
(published, stamp)
}
Err(err) => {
if let Some(ref source) = admission_source {
@@ -16915,9 +17057,13 @@ impl DiskAPI for LocalDisk {
}
if !src_is_dir
&& let Some(ref source) = admission_source
&& let Ok(part_info) = ObjectPartInfo::unmarshal(&meta_for_legacy)
&& let Some(part_info) = cached_part_info.or_else(|| ObjectPartInfo::unmarshal(&meta_for_legacy).ok())
{
multipart_source_state::record_active_multipart_part_committed(source, part_info);
multipart_source_state::record_active_multipart_part_committed(
source,
part_info,
published_transaction_meta.then_some(precomputed_publish_stamp).flatten(),
);
}
if src_is_dir {
@@ -17193,7 +17339,14 @@ impl DiskAPI for LocalDisk {
length: usize,
metrics: Option<MmapCopyStageMetrics>,
) -> Result<Bytes> {
self.io_backend.pread_bytes(volume, path, offset, length, metrics).await
if offset.checked_add(length).is_none() {
return self.io_backend.pread_bytes(volume, path, offset, length, metrics).await;
}
let in_flight_permit = crate::set_disk::read_budget::global_in_flight_read_budget()
.try_reserve(length)
.ok_or_else(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error)?;
let bytes = self.io_backend.pread_bytes(volume, path, offset, length, metrics).await?;
Ok(in_flight_permit.wrap_bytes(bytes))
}
/// List a single directory. `count < 0` enumerates the *whole* directory in
@@ -17835,22 +17988,40 @@ impl DiskAPI for LocalDisk {
} else {
GET_OBJECT_PATH_LEGACY_DUPLEX
};
if !org_volume.is_empty() {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
#[cfg(target_os = "linux")]
let defer_org_volume_check = !org_volume.is_empty()
&& org_volume == volume
&& volume != RUSTFS_META_MULTIPART_BUCKET
&& is_clean_relative_segment(volume);
#[cfg(not(target_os = "linux"))]
let defer_org_volume_check = false;
if !org_volume.is_empty() && !defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
let path_resolve_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let (volume_dir, file_path) = self.io_get_bucket_and_object_open_path(volume, path)?;
let resolved_paths = self.io_get_bucket_and_object_open_path(volume, path);
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_RESOLVE, path_resolve_start);
let (volume_dir, file_path) = match resolved_paths {
Ok(paths) => paths,
Err(err) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
};
let path_check_start = get_stage_timer_if_enabled(stage_metrics_enabled);
check_path_length(file_path.to_string_lossy().as_ref())?;
let len_check = check_path_length(file_path.to_string_lossy().as_ref());
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_CHECK, path_check_start);
if let Err(err) = len_check {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
if volume == RUSTFS_META_MULTIPART_BUCKET
&& !opts.read_data
@@ -17866,13 +18037,19 @@ impl DiskAPI for LocalDisk {
let xlmeta_read_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let raw_read_result = self.read_raw(volume, &volume_dir, &file_path, read_data).await;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_XLMETA_READ, xlmeta_read_start);
let (data, _) = raw_read_result.map_err(|e| {
if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
let (data, _) = match raw_read_result {
Ok(res) => res,
Err(e) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
});
}
})?;
};
let decode_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let file_info_result: Result<FileInfo> = (|| {
@@ -22915,6 +23092,22 @@ mod test {
.expect("new tmp data should be written");
let dst_meta_parent = dir.path().join(bucket).join(object);
os::fsync_dir_recorder::set_grouped_failure(&dst_meta_parent, io::ErrorKind::PermissionDenied);
let disk_permits = Arc::clone(&disk.file_sync_permits);
let initial_permits = disk_permits.available_permits();
let (permit_probe_tx, mut permit_probe_rx) = tokio::sync::oneshot::channel();
let canonical_parent = dir
.path()
.canonicalize()
.expect("canonical fixture directory")
.join(bucket)
.join(object);
let _probe = os::prepared_publication_test_hooks::install_at(
os::prepared_publication_test_hooks::Stage::DirFsync,
&canonical_parent,
move || {
let _ = permit_probe_tx.send(disk_permits.available_permits());
},
);
let new_fi = test_file_info(object, version_id, Some(new_data_dir), None);
let err = disk
@@ -22923,6 +23116,8 @@ mod test {
.expect_err("grouped dst dir fsync failure must fail the fresh PUT");
assert_eq!(err, DiskError::FileAccessDenied);
assert_eq!(permit_probe_rx.try_recv().expect("observe the grouped syscall"), initial_permits - 1);
assert_eq!(disk.file_sync_permits.available_permits(), initial_permits);
assert!(
!dst_meta_parent.join(STORAGE_FORMAT_FILE).exists(),
"fresh PUT rollback must remove the committed xl.meta after grouped dst dir fsync failure"
@@ -42339,7 +42534,7 @@ mod test {
let source_root = multipart_staging::upload_scope_root(mp_dst_path, true);
let mut upload = FileInfo::new(source_root, 2, 2);
upload.erasure.index = 1;
upload.data_dir = Some(Uuid::new_v4());
upload.data_dir = Some(Uuid::parse_str("58ba822c-06e4-4332-81cc-be2c9d921900").expect("valid part data_dir uuid"));
upload.mod_time = Some(time::OffsetDateTime::now_utc());
upload.fresh = true;
disk.write_metadata("", RUSTFS_META_MULTIPART_BUCKET, source_root, upload)
@@ -42361,6 +42556,14 @@ mod test {
.expect("stage multipart part");
let mp_dir = disk.io_root().join(RUSTFS_META_MULTIPART_BUCKET);
let mp_txn_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, &crate::disk::part_transaction_path(mp_dst_path))
.expect("multipart txn open path");
let expected_upload_lock = disk
.lookup_multipart_upload_lock(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, true)
.expect("lookup upload lock")
.expect("multipart upload lock present");
let expected_txn_ns_lock = os::lookup_namespace_mutation_lock(&mp_txn_open_path);
let jobs_before_mp = disk.blocking_queue.submitted_jobs_for_test();
let fsync_jobs_before_mp = disk.blocking_queue.submitted_fsync_jobs_for_test();
let mp_syncs_before = os::fsync_dir_recorder::count_under(&mp_dir);
@@ -42373,6 +42576,19 @@ mod test {
)
.await
.expect("prepare_part_transaction");
assert!(
PREPARED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry.part_info.number == 1
&& entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PreparedPartTxnReceipt must retain parsed part_info, UploadLockHandle, and NamespaceMutationLockHandle"
);
disk.rename_part(
RUSTFS_META_TMP_BUCKET,
"mp-stage/part.1",
@@ -42382,6 +42598,38 @@ mod test {
)
.await
.expect("rename_part");
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PublishedPartTxnReceipt must carry UploadLockHandle and NamespaceMutationLockHandle into settle_part_transaction"
);
let alias_meta_path = format!("multipart/{mp_dst_path}");
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_BUCKET, &alias_meta_path, PartTransactionAction::Commit)
.await
.expect_err("volume/path alias must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
let dot_segment_mp_path = mp_dst_path.replacen('/', "/./", 1);
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, &dot_segment_mp_path, PartTransactionAction::Commit)
.await
.expect_err("dot-segment path must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |_| true)
.unwrap_or(false),
"rejected settle_part_transaction calls must not consume warm PublishedPartTxnReceipt"
);
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, PartTransactionAction::Commit)
.await
.expect("settle_part_transaction");
@@ -42407,10 +42655,78 @@ mod test {
.expect("read settled part"),
part_payload
);
let source_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, source_root)
.expect("source open path");
assert_eq!(
multipart_source_state::get_active_multipart_source_part_with_head(&source_open_path, 1, false)
.map(|part| (part.number, part.size)),
Some((1, part_payload.len())),
"ACTIVE_MULTIPART_SOURCE_HEADS must serve committed part metadata after rename_part + settle_part_transaction"
);
// 4. Deferred org_volume check in read_version must preserve VolumeNotFound precedence
// when org_volume == volume does not exist on disk, and FileVersionNotFound when
// org_volume == volume exists and version_id is non-empty.
let missing_bucket = "nonexistent-read-version-bucket";
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "missing-obj", "", &ReadOptions::default())
.await
.expect_err("missing org_volume == volume must fail"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound when org_volume == volume does not exist"
);
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "../escape", "", &ReadOptions::default())
.await
.expect_err("missing org_volume with invalid path must still report VolumeNotFound first"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound precedence over path-resolve errors when org_volume == volume is missing"
);
assert_eq!(
disk.read_version(
bucket,
bucket,
"missing-versioned-obj",
"00000000-0000-0000-0000-000000000001",
&ReadOptions::default(),
)
.await
.expect_err("existing bucket with missing object and non-empty version_id must return FileVersionNotFound"),
DiskError::FileVersionNotFound,
"read_version must preserve FileNotFound -> FileVersionNotFound mapping when org_volume == volume exists"
);
println!("HOTPATH_BUDGET_OK");
}
#[cfg(unix)]
#[test]
fn part_txn_files_ready_with_stamp_matches_post_rename_file_stamp() {
let dir = tempfile::tempdir().expect("tempdir");
let txn_dir = dir.path().join("part.1.part-txn");
std::fs::create_dir_all(&txn_dir).expect("create txn dir");
let publish_meta = txn_dir.join(PART_TRANSACTION_PUBLISH_META);
let new_meta = txn_dir.join(PART_TRANSACTION_NEW_META);
let payload = b"serialized-part-meta";
std::fs::write(&publish_meta, payload).expect("write publish.meta");
std::fs::write(&new_meta, payload).expect("write new.meta");
let txn_fd = std::fs::File::open(&txn_dir).expect("open txn_dir_fd");
let pre_rename_stamp = part_txn_files_ready_with_stamp(Some(&txn_fd), &publish_meta, &new_meta, payload.len() as u64)
.expect("part_txn_files_ready_with_stamp must report ready")
.expect("unix statat path must return precomputed FileStamp");
let committed_meta = dir.path().join("part.1.meta");
std::fs::rename(&publish_meta, &committed_meta).expect("rename publish.meta to part.1.meta");
let post_rename_stamp =
multipart_source_state::FileStamp::from_path(&committed_meta).expect("post-rename FileStamp::from_path");
assert_eq!(
pre_rename_stamp, post_rename_stamp,
"FileStamp::from_stat before rename must match FileStamp::from_path after rename"
);
}
#[test]
fn read_metadata_only_from_reader_handles_short_reads_large_envelopes_and_errors() {
struct ScriptedShortReader<'a> {
+15 -6
View File
@@ -540,7 +540,7 @@ async fn prepare_rename_commit_and_destination_metadata(
/// Proof produced only when the local rename returns at an existing access
/// preflight, before metadata, backups, or object data can be published.
#[derive(Debug)]
pub(in crate::disk) struct LocalRenamePreflightRejection(());
struct LocalRenamePreflightRejection(());
#[derive(Default)]
pub(super) struct RenameDataState {
@@ -1248,13 +1248,14 @@ impl LocalDisk {
}
#[cfg(test)]
run_owned_file_before_open(&backup_path);
if let Err(err) = os::stage_inline_rollback_backup_with_commit_guard_std(
if let Err(err) = os::stage_inline_rollback_backup_in_dir_with_commit_guard_std(
&dst_file_path_owned,
&backup_parent,
&backup_path,
old_file,
sync_recovery_protocol,
!should_fail_local_inline_rollback_hardlink(&dst_file_path_owned),
has_old_data_dir.is_some(),
&guard,
) {
drop(prepared_metadata_source);
@@ -2152,9 +2153,17 @@ impl LocalDisk {
&& let Some(parent) = dst_file_path.parent()
{
let fsync_started = rustfs_io_metrics::put_stage_timer();
if let Err(err) =
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), None).await
{
let fsync_result = async {
let admission = if dst_dir_group_commit {
Some(os::acquire_file_sync_admission(self.file_sync_permits.clone()).await?)
} else {
None
};
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), admission.as_ref())
.await
}
.await;
if let Err(err) = fsync_result {
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_DST_DIR_FSYNC,
fsync_started,
@@ -2939,7 +2948,7 @@ impl LocalDisk {
.await;
super::super::RenameDataObservation {
result,
preflight_rejection: state.preflight_rejection,
rejected_before_publication: state.preflight_rejection.is_some(),
}
}
}
@@ -2599,6 +2599,7 @@ mod tests {
assert!(!disk.root.join(RUSTFS_META_TMP_BUCKET).join(raw_path).exists());
}
#[cfg(unix)]
async fn assert_cold_recovery_after_present_head_failure(
fixture: &mut Fixture,
publication: &PublicationIdentity,
@@ -261,8 +261,8 @@ pub(super) fn read_optional_in_pinned(
Err(error) => Err(error.into()),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct FileStamp {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct FileStamp {
len: u64,
modified: Option<std::time::SystemTime>,
#[cfg(unix)]
@@ -270,7 +270,7 @@ struct FileStamp {
}
impl FileStamp {
fn from_path(path: &Path) -> Option<Self> {
pub(super) fn from_path(path: &Path) -> Option<Self> {
let meta = std::fs::symlink_metadata(path).ok()?;
Some(Self {
len: meta.len(),
@@ -282,6 +282,22 @@ impl FileStamp {
},
})
}
#[cfg(unix)]
pub(super) fn from_stat(st: &rustix::fs::Stat) -> Option<Self> {
fn try_u64<T: TryInto<u64>>(v: T) -> Option<u64> {
v.try_into().ok()
}
fn try_u32<T: TryInto<u32>>(v: T) -> Option<u32> {
v.try_into().ok()
}
let len = try_u64(st.st_size)?;
let sec = try_u64(st.st_mtime)?;
let nsec = try_u32(st.st_mtime_nsec).filter(|&n| n < 1_000_000_000)?;
let ino = try_u64(st.st_ino)?;
let modified = Some(std::time::UNIX_EPOCH.checked_add(std::time::Duration::new(sec, nsec))?);
Some(Self { len, modified, ino })
}
}
#[derive(Clone)]
@@ -371,7 +387,19 @@ pub(super) fn begin_active_multipart_part_transaction(source: &Path, part_number
});
}
pub(super) fn record_active_multipart_part_committed(source: &Path, part: rustfs_filemeta::ObjectPartInfo) {
pub(super) fn record_active_multipart_part_committed(
source: &Path,
part: rustfs_filemeta::ObjectPartInfo,
precomputed_stamp: Option<FileStamp>,
) {
if let Some(part_stamp) = precomputed_stamp {
ACTIVE_MULTIPART_SOURCE_HEADS.with_get_mut(source, |entry| {
if entry.fi.data_dir.is_some_and(|dir| !dir.is_nil()) {
entry.parts.insert(part.number, (part_stamp, part));
}
});
return;
}
let Some(data_dir) = ACTIVE_MULTIPART_SOURCE_HEADS
.with_get(source, |entry| entry.fi.data_dir)
.flatten()
@@ -755,7 +783,7 @@ impl SourceStore {
.await?;
Ok(state)
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub async fn write_owned_backup(&self, owner: Uuid, target: bool, bytes: &[u8]) -> Result<()> {
if owner.is_nil() {
return Err(DiskError::FileCorrupt);
@@ -317,6 +317,16 @@ impl Drop for MultipartCommitStaging {
}
}
#[derive(Clone)]
pub(super) struct UploadLockHandle(Arc<UploadEntry>);
impl UploadLockHandle {
#[cfg(test)]
pub(super) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl LocalDisk {
pub(crate) fn has_clean_active_multipart_source(&self, upload_or_part_path: &str, part_path: bool) -> bool {
let root = upload_scope_root(upload_or_part_path, part_path);
@@ -379,27 +389,37 @@ impl LocalDisk {
}))
}
pub(super) async fn multipart_source_owner(
pub(super) fn lookup_multipart_upload_lock(
&self,
volume: &str,
path: &str,
part_path: bool,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
) -> Result<Option<UploadLockHandle>> {
reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
if volume != RUSTFS_META_MULTIPART_BUCKET {
return Ok(owner);
return Ok(None);
}
let root = upload_scope_root(path, part_path);
// Only the internal relative scope is folded: the configured disk root
// keeps its physical spelling. Case-sensitive filesystems may serialize
// two case-only upload IDs; insensitive filesystems must share one lock.
let key = self.root.join(RUSTFS_META_MULTIPART_BUCKET).join(root.to_ascii_lowercase());
let entry = UPLOAD_LOCKS.entry(key);
Ok(Some(UploadLockHandle(UPLOAD_LOCKS.entry(key))))
}
pub(super) async fn acquire_multipart_source_owner_with_handle(
handle: Option<&UploadLockHandle>,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Option<Arc<dyn Send + Sync>> {
let Some(handle) = handle else {
return owner;
};
let entry = Arc::clone(&handle.0);
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
// Upload scope precedes the private attempt, object metadata and
// publication leases. Independent parts retain shared ownership.
Ok(Some(if exclusive {
Some(if exclusive {
Arc::new(UploadOwner {
_guard: Arc::clone(&entry.lock).write_owned().await,
_entry: entry,
@@ -411,7 +431,19 @@ impl LocalDisk {
_entry: entry,
_owner: owner,
})
}))
})
}
pub(super) async fn multipart_source_owner(
&self,
volume: &str,
path: &str,
part_path: bool,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
let handle = self.lookup_multipart_upload_lock(volume, path, part_path)?;
Ok(Self::acquire_multipart_source_owner_with_handle(handle.as_ref(), exclusive, owner).await)
}
pub(super) async fn prepare_multipart_commit_staging(
+13 -16
View File
@@ -130,24 +130,28 @@ pub(crate) struct RenameDataGuards {
pub(crate) scanner_publication_lease_token: Option<Uuid>,
pub(crate) external_guard: Option<Arc<dyn Send + Sync>>,
pub(crate) namespace_owner: Option<Arc<dyn Send + Sync>>,
pub(crate) dispatch_deadline: Option<RenameDispatchDeadline>,
}
/// Local preflight evidence stays outside DiskAPI and the RPC response format.
/// The fanout publishes this deadline once enough disks have committed.
pub(crate) type RenameDispatchDeadline = tokio::sync::watch::Receiver<Option<tokio::time::Instant>>;
/// Pre-dispatch evidence stays outside DiskAPI and the RPC response format.
pub(crate) struct RenameDataObservation {
pub(crate) result: Result<RenameDataResp>,
preflight_rejection: Option<local::LocalRenamePreflightRejection>,
pub(crate) rejected_before_publication: bool,
}
impl RenameDataObservation {
fn unknown(result: Result<RenameDataResp>) -> Self {
pub(crate) fn unknown(result: Result<RenameDataResp>) -> Self {
Self {
result,
preflight_rejection: None,
rejected_before_publication: false,
}
}
pub(crate) fn rejected_before_publication(&self) -> bool {
self.result.is_err() && self.preflight_rejection.is_some()
self.result.is_err() && self.rejected_before_publication
}
}
@@ -1388,18 +1392,11 @@ impl Disk {
.rename_data_observed_with_guards(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
Disk::Remote(remote_disk) => RenameDataObservation::unknown(
Disk::Remote(remote_disk) => {
remote_disk
.rename_data_borrowed_with_fence(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
guards.scanner_publication_lease_token,
)
.await,
),
.rename_data_observed(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
}
}
+132 -48
View File
@@ -1007,14 +1007,15 @@ impl OpenedDstDirFsyncGroup {
}
struct DstDirFsyncWaiter {
namespace_owner: Option<Arc<dyn Send + Sync>>,
resource_unit: Option<super::io_admission::ResourceIoUnit>,
owner: DstDirFsyncOwner,
result_tx: oneshot::Sender<SharedDstDirFsyncResult>,
}
#[derive(Default)]
struct DstDirFsyncOwner {
_namespace: Option<Arc<dyn Send + Sync>>,
_resource: Option<super::io_admission::ResourceIoUnit>,
disk_permit: Option<Arc<OwnedSemaphorePermit>>,
}
#[derive(Clone)]
@@ -1073,6 +1074,7 @@ impl DstDirFsyncGroupCommit {
&self,
opened: OpenedDstDirFsyncGroup,
namespace_owner: Option<Arc<dyn Send + Sync>>,
admission: Option<&FileSyncAdmission>,
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
let (result_tx, result_rx) = oneshot::channel();
let mut registry = self.inner.lock();
@@ -1105,8 +1107,11 @@ impl DstDirFsyncGroupCommit {
let mut group_state = group.inner.lock();
group_state.pending.push_back(DstDirFsyncWaiter {
result_tx,
namespace_owner,
resource_unit: super::io_admission::current_resource_unit(),
owner: DstDirFsyncOwner {
_namespace: namespace_owner,
_resource: super::io_admission::current_resource_unit(),
disk_permit: admission.map(|admission| Arc::clone(&admission.disk_permit)),
},
});
let start_worker = !group_state.worker_running;
if start_worker {
@@ -1158,7 +1163,7 @@ impl DstDirFsyncGroupCommit {
&self,
dir: &Path,
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None)
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None, None)
}
}
@@ -1224,7 +1229,10 @@ impl Drop for DstDirFsyncWorkerGuard {
}
}
fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::future::Future<Output = ()> {
fn run_dst_dir_fsync_group_worker(
group: Arc<DstDirFsyncGroup>,
global_permits: &Semaphore,
) -> impl std::future::Future<Output = ()> + '_ {
// Capture before spawning: shutdown may drop the future without polling it.
let worker_guard = DstDirFsyncWorkerGuard {
group: group.clone(),
@@ -1253,20 +1261,25 @@ fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::fut
#[cfg(test)]
fsync_dir_recorder::record_grouped(&group.dir, batch.len());
let namespace_owners = batch
let owners: Vec<_> = batch
.iter_mut()
.filter_map(|waiter| {
let namespace = waiter.namespace_owner.take();
let resource = waiter.resource_unit.take();
(namespace.is_some() || resource.is_some()).then_some(DstDirFsyncOwner {
_namespace: namespace,
_resource: resource,
})
let owner = std::mem::take(&mut waiter.owner);
(owner._namespace.is_some() || owner._resource.is_some() || owner.disk_permit.is_some()).then_some(owner)
})
.collect();
let result = fsync_open_dst_dir_group(&group, namespace_owners)
.await
.map_err(SharedDstDirFsyncError::from_error);
let result = async {
// The waiters already hold their disk admission. Reserve one global slot
// per physical sync, keeping it with the worker so shutdown can release it.
let _global_permit = if owners.iter().any(|owner| owner.disk_permit.is_some()) {
Some(acquire_global_file_sync_permit(global_permits).await?)
} else {
None
};
fsync_open_dst_dir_group(&group, owners).await
}
.await
.map_err(SharedDstDirFsyncError::from_error);
let batch_len = batch.len();
DST_DIR_FSYNC_GROUP_COMMIT.complete_batch(batch_len);
worker_guard.in_flight = 0;
@@ -1300,7 +1313,7 @@ async fn fsync_dst_dir_group_commit_with_enabled(
enabled: bool,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> io::Result<()> {
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None).await
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None, None).await
}
async fn fsync_dst_dir_group_commit_opened(
@@ -1308,6 +1321,7 @@ async fn fsync_dst_dir_group_commit_opened(
enabled: bool,
namespace_owner: Option<Arc<dyn Send + Sync>>,
opened: Option<Arc<std::fs::File>>,
admission: Option<&FileSyncAdmission>,
) -> io::Result<()> {
if !enabled {
if let Some(file) = opened {
@@ -1333,9 +1347,9 @@ async fn fsync_dst_dir_group_commit_opened(
})
.await
.map_err(|err| io::Error::other(format!("blocking dst dir group open failed: {err}")))??;
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner)?;
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner, admission)?;
if let Some(group) = worker {
tokio::spawn(run_dst_dir_fsync_group_worker(group));
tokio::spawn(run_dst_dir_fsync_group_worker(group, &FILE_SYNC_PERMITS));
}
match result_rx.await {
@@ -1415,9 +1429,8 @@ pub(crate) async fn fsync_commit_directory(
.ok_or_else(|| io::Error::other("commit directory was not published"))?
.file
.clone();
if !dst_dir_fsync_group_commit_enabled()
&& let Some(admission) = admission
{
let grouped = dst_dir_fsync_group_commit_enabled();
if !grouped && let Some(admission) = admission {
let dir = dir.to_path_buf();
return run_blocking_namespace_file_sync_operation(lease, admission, move || {
#[cfg(test)]
@@ -1426,7 +1439,7 @@ pub(crate) async fn fsync_commit_directory(
})
.await;
}
fsync_dst_dir_group_commit_opened(dir, dst_dir_fsync_group_commit_enabled(), Some(lease), Some(file)).await
fsync_dst_dir_group_commit_opened(dir, grouped, Some(lease), Some(file), admission).await
}
#[cfg(not(target_os = "linux"))]
{
@@ -1453,7 +1466,7 @@ pub(crate) async fn fsync_dst_dir_group_commit_or_namespace_file_sync_limit(
admission: &FileSyncAdmission,
) -> io::Result<()> {
if dst_dir_fsync_group_commit_enabled() {
fsync_dst_dir_group_commit_with_enabled(dir, true, Some(lease)).await
fsync_dst_dir_group_commit_opened(dir.as_ref(), true, Some(lease), None, Some(admission)).await
} else {
fsync_dir_with_namespace_file_sync_limit(dir, lease, admission).await
}
@@ -2328,9 +2341,10 @@ static FSYNC_RUNTIME: LazyLock<Option<tokio::runtime::Runtime>> = LazyLock::new(
if threads <= 1 {
return None;
}
let workers = crate::runtime::detect_worker_parallelism().get().min(8);
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder
.worker_threads(num_cpus::get().min(8))
.worker_threads(workers)
.max_blocking_threads(threads)
.thread_name("rustfs-fsync")
.thread_stack_size(512 * 1024)
@@ -2666,7 +2680,7 @@ fn default_global_file_sync_limit(cpu_count: usize, max_blocking_threads: usize)
fn global_file_sync_limit() -> usize {
let max_blocking_threads =
rustfs_utils::get_env_usize(rustfs_config::ENV_MAX_BLOCKING_THREADS, rustfs_config::DEFAULT_MAX_BLOCKING_THREADS);
default_global_file_sync_limit(num_cpus::get(), max_blocking_threads)
default_global_file_sync_limit(crate::runtime::detect_worker_parallelism().get(), max_blocking_threads)
}
#[cfg(test)]
@@ -2737,7 +2751,7 @@ impl DiskBlockingLane {
#[derive(Default)]
struct DiskBlockingQueueState {
jobs: VecDeque<Box<dyn FnOnce() + Send>>,
#[cfg(test)]
#[cfg(all(test, unix))]
submitted_jobs: usize,
active_workers: usize,
idle_workers: usize,
@@ -2865,7 +2879,7 @@ impl DiskBlockingQueue {
let should_spawn = {
let mut state = self.lane(lane).state.lock();
state.jobs.push_back(job);
#[cfg(test)]
#[cfg(all(test, unix))]
{
state.submitted_jobs += 1;
}
@@ -2883,7 +2897,7 @@ impl DiskBlockingQueue {
}
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) fn submitted_jobs_for_test(&self) -> usize {
self.lanes.iter().map(|lane| lane.state.lock().submitted_jobs).sum()
}
@@ -3312,8 +3326,8 @@ static DISK_METADATA_MUTATION_LOCKS: LazyLock<ShardedPathLockRegistry<NamespaceM
#[derive(Clone)]
pub(crate) struct MetadataMutationLockHandle(Arc<NamespaceMutationLock>);
#[cfg(all(test, unix))]
impl MetadataMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
@@ -3323,8 +3337,8 @@ impl MetadataMutationLockHandle {
#[derive(Clone)]
pub(in crate::disk) struct NamespaceMutationLockHandle(Arc<NamespaceMutationLock>);
#[cfg(all(test, unix))]
impl NamespaceMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
@@ -5161,7 +5175,7 @@ pub(crate) fn read_destination_file_with_commit_guard(
}
}
#[cfg(target_os = "linux")]
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn stage_inline_rollback_backup_with_commit_guard_std(
dst_file_path: &Path,
backup_parent: &Path,
@@ -5845,15 +5859,7 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
global_permits: &Semaphore,
operation: impl FnOnce(&dyn Fn() -> bool) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
let wait_started = rustfs_io_metrics::put_stage_timer();
let global_permit = global_permits
.acquire()
.await
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
wait_started,
);
let global_permit = acquire_global_file_sync_permit(global_permits).await?;
let disk_permit = admission.disk_permit.clone();
let queue = Arc::clone(&lease.blocking_queue);
let result = queue
@@ -5867,6 +5873,19 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
result
}
async fn acquire_global_file_sync_permit(global_permits: &Semaphore) -> io::Result<SemaphorePermit<'_>> {
let wait_started = rustfs_io_metrics::put_stage_timer();
let permit = global_permits
.acquire()
.await
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
wait_started,
);
Ok(permit)
}
pub(crate) async fn fsync_dir_with_namespace_file_sync_limit(
dir: impl AsRef<Path>,
lease: Arc<NamespaceMutationLease>,
@@ -12306,11 +12325,20 @@ mod tests {
let second_owner = second_ctx.begin_namespace_commit();
let first_probe = Arc::downgrade(&first_owner);
let second_probe = Arc::downgrade(&second_owner);
let disk_permits = Arc::new(Semaphore::new(2));
let first_admission = acquire_file_sync_admission(disk_permits.clone())
.await
.expect("first disk slot");
let second_admission = acquire_file_sync_admission(disk_permits.clone())
.await
.expect("second disk slot");
let global_permits = Arc::new(Semaphore::new(1));
let (first_rx, group) = with_background_resource_unit(resources[0].acquire().await, async {
DST_DIR_FSYNC_GROUP_COMMIT
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open first waiter directory"),
Some(first_owner),
Some(&first_admission),
)
.expect("queue first real waiter")
})
@@ -12321,6 +12349,7 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open second waiter directory"),
Some(second_owner),
Some(&second_admission),
)
.expect("queue second real waiter")
})
@@ -12334,12 +12363,18 @@ mod tests {
let _ = entered_tx.send(());
let _ = release_rx.recv();
});
let worker = tokio::spawn(run_dst_dir_fsync_group_worker(group.clone()));
drop((first_admission, second_admission));
let worker = tokio::spawn({
let group = group.clone();
let global_permits = global_permits.clone();
async move { run_dst_dir_fsync_group_worker(group, &global_permits).await }
});
tokio::time::timeout(Duration::from_secs(5), entered_rx)
.await
.expect("batch must reach its physical fsync")
.expect("physical fsync entry");
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(&dir), vec![2]);
assert_eq!(global_permits.available_permits(), 0, "one physical sync must reserve the global slot");
assert!(
group.inner.lock().pending.is_empty(),
"both waiters were transferred into the physical batch"
@@ -12353,6 +12388,7 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open queued waiter directory"),
Some(queued_owner),
None,
)
.expect("queue a waiter after the physical batch was frozen")
})
@@ -12372,6 +12408,8 @@ mod tests {
let first_pending = first_ctx.namespace_commits_pending() && first_probe.upgrade().is_some();
let second_pending = second_ctx.namespace_commits_pending() && second_probe.upgrade().is_some();
let retained_resources = resources.each_ref().map(|gate| gate.snapshot().active);
let retained_disk_permits = disk_permits.available_permits();
let released_global_permits = global_permits.available_permits();
let generations = (first_ctx.namespace_commit_generation(), second_ctx.namespace_commit_generation());
drop(release_tx);
tokio::time::timeout(Duration::from_secs(5), async {
@@ -12401,6 +12439,38 @@ mod tests {
assert!(!second_ctx.namespace_commits_pending());
assert!(first_ctx.namespace_commit_generation() > generations.0);
assert!(second_ctx.namespace_commit_generation() > generations.1);
assert_eq!(retained_disk_permits, 0, "both disk slots must survive abort while the syscall runs");
assert_eq!(released_global_permits, 1, "abort must restore capacity for other disks");
assert_eq!(disk_permits.available_permits(), 2, "both disk slots return after fsync");
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(dst_dir_fsync_group_commit)]
async fn grouped_fsync_propagates_closed_global_limit_without_syncing() {
let directory = tempdir().expect("fixture directory");
let disk_permits = Arc::new(Semaphore::new(1));
let admission = acquire_file_sync_admission(disk_permits.clone()).await.expect("disk slot");
let (result, worker) = DST_DIR_FSYNC_GROUP_COMMIT
.enqueue_opened(
OpenedDstDirFsyncGroup::open(directory.path()).expect("open fixture"),
None,
Some(&admission),
)
.expect("enqueue waiter");
drop(admission);
let global_permits = Semaphore::new(0);
global_permits.close();
run_dst_dir_fsync_group_worker(worker.expect("first waiter starts worker"), &global_permits).await;
let error = result
.await
.expect("worker reports completion")
.expect_err("closed limiter must reject fsync");
assert_eq!(&*error.message, "global file sync concurrency limiter closed");
assert!(!fsync_dir_recorder::was_fsynced(directory.path()));
assert_eq!(disk_permits.available_permits(), 1);
assert_eq!(DST_DIR_FSYNC_GROUP_COMMIT.counts_for_test(), (0, 0));
}
#[cfg(unix)]
@@ -12416,10 +12486,11 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open queued waiter directory"),
Some(owner),
None,
)
.expect("queue a real waiter");
let group = group.expect("first waiter starts the group");
let worker = run_dst_dir_fsync_group_worker(group.clone());
let worker = run_dst_dir_fsync_group_worker(group.clone(), &FILE_SYNC_PERMITS);
assert!(ctx.namespace_commits_pending());
drop(worker);
assert!(rx.await.is_err(), "shutdown before first poll must release the waiter");
@@ -12496,9 +12567,12 @@ mod tests {
.enqueue_for_test(temp_dir.path())
.expect("enqueue old group");
let old_group = old_worker.expect("old group starts a worker");
tokio::time::timeout(Duration::from_secs(5), run_dst_dir_fsync_group_worker(old_group.clone()))
.await
.expect("old worker must finish its actual fsync");
tokio::time::timeout(
Duration::from_secs(5),
run_dst_dir_fsync_group_worker(old_group.clone(), &FILE_SYNC_PERMITS),
)
.await
.expect("old worker must finish its actual fsync");
assert!(old_rx.await.expect("old worker reports completion").is_ok());
assert!(fsync_dir_recorder::was_fsynced(temp_dir.path()));
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(temp_dir.path()), vec![1]);
@@ -12512,11 +12586,12 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open successor directory"),
Some(owner),
None,
)
.expect("enqueue successor owner");
let successor = successor_worker.expect("successor starts a new group");
assert!(!Arc::ptr_eq(&old_group, &successor));
let worker = run_dst_dir_fsync_group_worker(successor.clone());
let worker = run_dst_dir_fsync_group_worker(successor.clone(), &FILE_SYNC_PERMITS);
// The stale Arc represents W1 resuming after another worker removed G.
DST_DIR_FSYNC_GROUP_COMMIT.remove_idle_group(&old_group);
assert!(ctx.namespace_commits_pending());
@@ -14665,8 +14740,17 @@ mod tests {
q_fsync
.run_fsync_cancellable(|is_cancelled| {
assert!(!is_cancelled());
if FSYNC_RUNTIME.is_some() {
let blocking_threads = rustfs_utils::get_env_usize(
rustfs_config::ENV_FSYNC_BLOCKING_THREADS,
rustfs_config::DEFAULT_FSYNC_BLOCKING_THREADS,
);
if blocking_threads > 1 {
let runtime = FSYNC_RUNTIME.as_ref().expect("configured dedicated fsync runtime");
assert_eq!(std::thread::current().name(), Some("rustfs-fsync"));
let expected = std::thread::available_parallelism().map_or(1, usize::from).min(8);
assert_eq!(runtime.metrics().num_workers(), expected);
} else {
assert!(FSYNC_RUNTIME.is_none());
}
Ok(())
})
+17
View File
@@ -269,6 +269,12 @@ pub enum StorageError {
/// retained for operator inspection.
#[error("delete recovery found an ambiguous legacy residue; operator inspection is required")]
DeleteRecoveryLegacyAmbiguous,
#[error("delete recovery blocked for {bucket}/{object}: transaction {transaction} conflicts with the live object generation")]
DeleteRecoveryGenerationConflict {
bucket: String,
object: String,
transaction: uuid::Uuid,
},
/// Delete recovery exhausted the per-request work budget before it could
/// classify every residue. Retrying later makes progress, so callers treat
/// it like `SlowDown`; it stays distinct so the disk error round-trips.
@@ -717,6 +723,15 @@ impl Clone for StorageError {
StorageError::StorageFull => StorageError::StorageFull,
StorageError::SlowDown => StorageError::SlowDown,
StorageError::DeleteRecoveryLegacyAmbiguous => StorageError::DeleteRecoveryLegacyAmbiguous,
StorageError::DeleteRecoveryGenerationConflict {
bucket,
object,
transaction,
} => StorageError::DeleteRecoveryGenerationConflict {
bucket: bucket.clone(),
object: object.clone(),
transaction: *transaction,
},
StorageError::DeleteRecoveryWorkLimit => StorageError::DeleteRecoveryWorkLimit,
StorageError::PrefixAccessDenied(a, b) => StorageError::PrefixAccessDenied(a.clone(), b.clone()),
StorageError::InvalidUploadIDKeyCombination(a, b) => {
@@ -860,6 +875,8 @@ impl StorageError {
StorageError::StorageFull => StorageErrorCode::StorageFull,
StorageError::SlowDown => StorageErrorCode::SlowDown,
StorageError::DeleteRecoveryLegacyAmbiguous => StorageErrorCode::DeleteRecoveryLegacyAmbiguous,
// Only the inspecting coordinator has the evidence to park a specific responsibility.
StorageError::DeleteRecoveryGenerationConflict { .. } => StorageErrorCode::OutdatedXLMeta,
StorageError::DeleteRecoveryWorkLimit => StorageErrorCode::DeleteRecoveryWorkLimit,
StorageError::PrefixAccessDenied(_, _) => StorageErrorCode::PrefixAccessDenied,
StorageError::InvalidUploadIDKeyCombination(_, _) => StorageErrorCode::InvalidUploadIDKeyCombination,
+107 -11
View File
@@ -432,18 +432,24 @@ async fn open_disk_reader(
// request the entire part span in one call. Over-cap reads (e.g. a huge
// single-part object, rustfs#5123) take the bounded streaming path below.
let use_mmap_copy = if use_mmap_read && disk.is_local() {
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
let inflight_budget = crate::set_disk::read_budget::object_mmap_read_max_inflight_bytes();
if inflight_budget == 0 || length > inflight_budget {
rustfs_io_metrics::record_zero_copy_fallback("in_flight_read_budget_exceeded");
false
} else {
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
}
within_cap
}
within_cap
} else {
false
};
@@ -524,6 +530,7 @@ async fn open_disk_reader(
let reader = instrument_raw_shard_reader(reader, disk.is_local());
Ok(wrap_first_read_metrics(reader, metrics_path))
}
Err(stream_err) if crate::set_disk::read_budget::is_in_flight_read_budget_exhausted(&err) => Err(stream_err),
Err(_) => Err(err),
};
}
@@ -1848,6 +1855,95 @@ mod tests {
.await;
}
#[tokio::test]
async fn open_disk_reader_preserves_disk_errors_and_streams_under_inflight_budget() {
use crate::set_disk::read_budget::global_in_flight_read_budget;
use rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES;
use tokio::io::AsyncReadExt;
let (disk, _dir) = local_test_disk().await;
let payload = vec![0x5Au8; 2048];
disk.make_volume("test-bucket").await.expect("volume should be created");
disk.write_all("test-bucket", "obj/part.1", Bytes::from(payload.clone()))
.await
.expect("shard file should be written");
// 1. Exhausted non-zero budget: existing shard falls back to streaming,
// missing shard preserves DiskError::FileNotFound instead of WouldBlock.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("2048"))], async {
let held_permit = global_in_flight_read_budget()
.try_reserve(2048)
.expect("initial permit should reserve full test budget");
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard must fall back to streaming when budget is exhausted");
assert!(
matches!(existing, ShardReader::Stream(_)),
"budget exhaustion must route open_disk_reader to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed fallback read should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"budget exhaustion must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
// Releasing the held permit restores the in-memory fast path and reclaims on drop.
drop(held_permit);
let fast = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("read under reclaimed budget should succeed");
assert!(
matches!(fast, ShardReader::InMemory(_)),
"read after permit reclamation must resume InMemory fast path"
);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), payload.len());
drop(fast);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), 0);
})
.await;
// 2. Zero budget disables mmap-copy upfront: existing shard streams and
// missing shard preserves DiskError::FileNotFound.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0"))], async {
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard with zero budget must stream");
assert!(
matches!(existing, ShardReader::Stream(_)),
"zero budget must route existing shard to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed read with zero budget should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard with zero budget must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"zero budget must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
})
.await;
}
#[tokio::test]
async fn disk_bitrot_reader_and_writer_preserve_full_shard_body() {
let (disk, _dir) = local_test_disk().await;
+9 -38
View File
@@ -110,29 +110,24 @@ pub fn compression_index_storage_bytes(index: &Index) -> Bytes {
}
}
/// Decodes one complete stored compression index for Range GET planning.
pub fn decode_compression_index_bytes(bytes: &Bytes) -> Option<Index> {
#[cfg(feature = "rio-v2")]
{
if let Some(decoded) = decode_minio_index_bytes(bytes) {
return Some(decoded);
}
}
// Check the legacy frame before attempting to restore a headerless S2
// index. Metadata contains exactly one index, so reject partial parses.
let mut decoded = Index::new();
if decoded.load(bytes.as_ref()).is_ok() {
if decoded.load(bytes.as_ref()).is_ok_and(|remaining| remaining.is_empty()) {
return Some(decoded);
}
#[cfg(feature = "rio-v2")]
{
let restored = restore_legacy_index_headers(bytes.as_ref());
let mut decoded = Index::new();
if decoded.load(&restored).is_ok() {
return Some(decoded);
}
decode_minio_index_bytes(bytes)
}
None
#[cfg(not(feature = "rio-v2"))]
{
None
}
}
pub fn compression_reader<R>(reader: R, algorithm: CompressionAlgorithm, encrypted: bool) -> CompressReader<R>
@@ -298,30 +293,6 @@ where
}
}
#[cfg(feature = "rio-v2")]
fn restore_legacy_index_headers(bytes: &[u8]) -> Vec<u8> {
if bytes.is_empty() {
return Vec::new();
}
const S2_INDEX_HEADER: &[u8] = b"s2idx\x00";
const S2_INDEX_TRAILER: &[u8] = b"\x00xdi2s";
let mut restored = Vec::with_capacity(4 + S2_INDEX_HEADER.len() + bytes.len() + 4 + S2_INDEX_TRAILER.len());
restored.extend_from_slice(&[0x99, 0x2A, 0x4D, 0x18]);
restored.extend_from_slice(S2_INDEX_HEADER);
restored.extend_from_slice(bytes);
let total_size = (restored.len() + 4 + S2_INDEX_TRAILER.len()) as u32;
restored.extend_from_slice(&total_size.to_le_bytes());
restored.extend_from_slice(S2_INDEX_TRAILER);
let chunk_len = restored.len() - 4;
restored[1] = chunk_len as u8;
restored[2] = (chunk_len >> 8) as u8;
restored[3] = (chunk_len >> 16) as u8;
restored
}
#[derive(Debug, Clone, Copy)]
pub struct WriteEncryption {
key_bytes: [u8; 32],
+10 -3
View File
@@ -73,6 +73,8 @@ impl TryFrom<&str> for Endpoint {
/// Performs the conversion.
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
const INVALID_URL_PORT: &str = "invalid URL endpoint format: port number must be between 1 to 65535";
// check whether given path is not empty.
if ["", "/", "\\"].iter().any(|&v| v.eq(value)) {
return Err(Error::other("empty or root endpoint is not supported"));
@@ -80,6 +82,7 @@ impl TryFrom<&str> for Endpoint {
let mut is_local = false;
let url = match Url::parse(value) {
Ok(url) if url.port() == Some(0) => return Err(Error::other(INVALID_URL_PORT)),
#[allow(unused_mut)]
Ok(mut url) if url.has_host() => {
// URL style of endpoint.
@@ -139,9 +142,7 @@ impl TryFrom<&str> for Endpoint {
url_parse_from_file_path(value)?
}
Err(e) => match e {
ParseError::InvalidPort => {
return Err(Error::other("invalid URL endpoint format: port number must be between 1 to 65535"));
}
ParseError::InvalidPort => return Err(Error::other(INVALID_URL_PORT)),
ParseError::EmptyHost => return Err(Error::other("invalid URL endpoint format: empty host name")),
ParseError::RelativeUrlWithoutBase => {
// like /foo
@@ -450,6 +451,12 @@ mod test {
expected_type: Some(EndpointType::Url),
expected_err: None,
},
TestCase {
arg: "http://127.0.0.1:0/path",
expected_endpoint: None,
expected_type: None,
expected_err: Some(Error::other("invalid URL endpoint format: port number must be between 1 to 65535")),
},
TestCase {
arg: "https://93.184.216.34:808080/path",
expected_endpoint: None,
+262 -246
View File
@@ -21,20 +21,25 @@ use rustfs_config::{
ENV_KUBERNETES_SERVICE_HOST, ENV_LOCAL_ENDPOINT_HOST, ENV_MINIO_CI, ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY,
ENV_STARTUP_TOPOLOGY_WAIT_MODE, ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT, ENV_UNSAFE_BYPASS_DISK_CHECK,
};
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, get_host_ip, is_local_host};
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, is_local_ip};
#[cfg(test)]
use std::sync::{LazyLock, Mutex};
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap, HashSet, hash_map::Entry},
future::Future,
io::{Error, ErrorKind, Result},
net::IpAddr,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::time::sleep as async_sleep;
use tokio::time::{Instant as TokioInstant, sleep as async_sleep, sleep_until};
use tracing::{error, info, instrument, warn};
use url::Host;
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY: &str = "endpoint_topology";
const EVENT_STARTUP_ENDPOINT_DNS_FAILED: &str = "startup_endpoint_dns_failed";
/// enum for setup type.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum SetupType {
@@ -196,18 +201,17 @@ struct PoolEndpointList {
setup_type: SetupType,
}
struct ResolvedStartupHost {
addresses: HashSet<IpAddr>,
is_local: bool,
}
impl AsRef<Vec<Endpoints>> for PoolEndpointList {
fn as_ref(&self) -> &Vec<Endpoints> {
&self.inner
}
}
impl AsMut<Vec<Endpoints>> for PoolEndpointList {
fn as_mut(&mut self) -> &mut Vec<Endpoints> {
&mut self.inner
}
}
impl PoolEndpointList {
/// Creates a list of endpoints per pool, resolves their relevant hostnames
/// and discovers whether those are local or remote.
@@ -322,76 +326,41 @@ impl PoolEndpointList {
let convergence_started = Instant::now();
let dns_retry_deadline = DnsRetryDeadline::new(policy.wait_timeout, policy.retry_max_delay);
if let Some(local_endpoint_host) = local_endpoint_host {
let resolved_hosts = if let Some(local_endpoint_host) = local_endpoint_host {
pool_endpoint_list.update_is_local_from_explicit_host(disks_layout, server_addr.port(), local_endpoint_host)?;
HashMap::new()
} else {
pool_endpoint_list
.update_is_local(server_addr.port(), &dns_retry_deadline)
.await?;
// Collapse divergent local/remote verdicts for the same host:port that
// orchestrated DNS churn can produce during startup, before any check
// relies on the local flag.
normalize_same_host_local_state(pool_endpoint_list.as_mut());
}
.resolve_startup_hosts(server_addr.port(), &dns_retry_deadline, lookup_startup_host_ips)
.await?
};
let mut total_endpoints = 0;
let mut local_endpoints = 0;
for endpoints in pool_endpoint_list.inner.iter_mut() {
// Check whether same path is not used in endpoints of a host on different port.
// This relies on resolving every host to its IP set, which can flap while a
// Kubernetes headless service is still publishing records; defer it in
// orchestrated mode and re-run the DNS-independent checks below.
if !policy.is_orchestrated() {
let mut path_ip_map: HashMap<String, HashSet<IpAddr>> = HashMap::new();
let mut host_ip_cache: HashMap<Host<&str>, HashSet<IpAddr>> = HashMap::new();
let mut path_ip_map: HashMap<String, Cow<'_, HashSet<IpAddr>>> = HashMap::new();
for ep in endpoints.as_ref() {
let Some(host) = ep.url.host() else {
let Some(host) = ep.url.host_str().and_then(|host| resolved_hosts.get(host)) else {
continue;
};
let host_ip_set = if let Some(set) = host_ip_cache.get(&host) {
info!(
target: "rustfs::ecstore::endpoints",
host = %host,
endpoint = %ep.to_string(),
from = "cache",
"Create pool endpoints host '{}' found in cache for endpoint '{}'", host, ep.to_string()
);
set.clone()
} else {
let ips = match resolve_host_ips_with_retry(host.clone(), &ep.to_string(), &dns_retry_deadline).await {
Ok(ips) => ips,
Err(e) => {
error!("Create pool endpoints host {} not found, error:{}", host, e);
return Err(e);
}
};
info!(
target: "rustfs::ecstore::endpoints",
host = %host,
endpoint = %ep.to_string(),
from = "get_host_ip",
"Create pool endpoints host '{}' resolved to ips {:?} for endpoint '{}'",
host,
ips,
ep.to_string()
);
host_ip_cache.insert(host.clone(), ips.clone());
ips
};
let path = ep.get_file_path();
match path_ip_map.entry(path) {
Entry::Occupied(mut e) => {
if e.get().intersection(&host_ip_set).count() > 0 {
let path_key = e.key().clone();
if !e.get().is_disjoint(&host.addresses) {
return Err(Error::other(format!(
"same path '{path_key}' can not be served by different port on same address"
"same path '{}' can not be served by different port on same address",
e.key()
)));
}
e.get_mut().extend(host_ip_set.iter());
e.get_mut().to_mut().extend(&host.addresses);
}
Entry::Vacant(e) => {
e.insert(host_ip_set);
e.insert(Cow::Borrowed(&host.addresses));
}
}
}
@@ -414,13 +383,11 @@ impl PoolEndpointList {
}
// Here all endpoints are URL style.
let mut ep_path_set = HashSet::new();
let mut local_server_host_set = HashSet::new();
let mut local_port_set = HashSet::new();
let mut local_endpoint_count = 0;
for ep in endpoints.as_ref() {
ep_path_set.insert(ep.get_file_path());
if ep.is_local && ep.url.has_host() {
local_server_host_set.insert(ep.url.host());
local_port_set.insert(ep.url.port());
@@ -438,30 +405,20 @@ impl PoolEndpointList {
}
// Add missing port in all endpoints.
total_endpoints += endpoints.as_ref().len();
for ep in endpoints.as_mut() {
local_endpoints += usize::from(ep.is_local);
if !ep.url.has_host() {
unique_args.insert(format!("localhost:{}", server_addr.port()));
continue;
}
match ep.url.port() {
None => {
if local_endpoint_host.is_none() {
let _ = ep.url.set_port(Some(server_addr.port()));
}
}
Some(port) => {
// If endpoint is local, but port is different than serverAddrPort, then make it as remote.
if ep.is_local && server_addr.port() != port {
ep.is_local = false;
}
}
if ep.url.port().is_none() && local_endpoint_host.is_none() {
let _ = ep.url.set_port(Some(server_addr.port()));
}
unique_args.insert(ep.host_port());
}
}
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
let setup_type = match pool_endpoint_list.as_ref()[0].as_ref()[0].get_type() {
EndpointType::Path => SetupType::Erasure,
EndpointType::Url => match unique_args.len() {
@@ -470,15 +427,25 @@ impl PoolEndpointList {
},
};
pool_endpoint_list.setup_type = setup_type;
// A storage member can belong to just one pool, but it must own a slot somewhere in the topology.
if local_endpoints == 0 {
let local_port = server_addr.port();
if local_endpoint_host.is_some() {
return Err(Error::other(format!(
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
)));
}
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"no local storage endpoints on the local server port {local_port}; \
check that a host in RUSTFS_VOLUMES resolves to a local interface and uses the RUSTFS_ADDRESS port"
),
));
}
let total_endpoints: usize = pool_endpoint_list.inner.iter().map(|eps| eps.as_ref().len()).sum();
let local_endpoints = pool_endpoint_list
.inner
.iter()
.flat_map(|eps| eps.as_ref())
.filter(|ep| ep.is_local)
.count();
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
pool_endpoint_list.setup_type = setup_type;
info!(
target: "rustfs::ecstore::endpoints",
mode = ?policy.mode,
@@ -492,34 +459,33 @@ impl PoolEndpointList {
Ok(pool_endpoint_list)
}
/// resolves all hosts and discovers which are local
async fn update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
self._update_is_local(local_port, dns_retry_deadline).await
}
/// resolves all hosts and discovers which are local
async fn _update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
// Keep each successful answer for the whole startup so all drives and path checks agree.
async fn resolve_startup_hosts(
&mut self,
local_port: u16,
dns_retry_deadline: &DnsRetryDeadline,
resolve: impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
) -> Result<HashMap<String, ResolvedStartupHost>> {
let mut resolved_hosts: HashMap<String, ResolvedStartupHost> = HashMap::new();
for endpoints in self.inner.iter_mut() {
for ep in endpoints.as_mut() {
match ep.url.host() {
None => {
ep.is_local = true;
}
Some(host) => {
ep.is_local = resolve_local_host_with_retry(
host,
ep.url.port().unwrap_or_default(),
local_port,
&ep.to_string(),
dns_retry_deadline,
)
.await?;
}
}
let (Some(host_name), Some(host)) = (ep.url.host_str(), ep.url.host()) else {
ep.is_local = true;
continue;
};
let is_local = if let Some(resolved) = resolved_hosts.get(host_name) {
resolved.is_local
} else {
let addresses = resolve_startup_host_with_retry(host, &ep.to_string(), dns_retry_deadline, &resolve).await?;
let is_local = addresses.iter().any(is_local_ip);
resolved_hosts.insert(host_name.to_owned(), ResolvedStartupHost { addresses, is_local });
is_local
};
ep.is_local = is_local && ep.url.port().is_none_or(|port| port == local_port);
}
}
Ok(())
Ok(resolved_hosts)
}
fn update_is_local_from_explicit_host(
@@ -529,7 +495,6 @@ impl PoolEndpointList {
raw_local_host: &str,
) -> Result<()> {
let local_host = parse_explicit_local_endpoint_host(raw_local_host)?;
let mut local_endpoint_found = false;
let mut host_path_ports = HashMap::new();
debug_assert_eq!(self.inner.len(), disks_layout.pools.len());
@@ -575,17 +540,9 @@ impl PoolEndpointList {
entry.insert(endpoint_port);
}
}
local_endpoint_found |= endpoint.is_local;
}
}
if !local_endpoint_found {
return Err(Error::other(format!(
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
)));
}
Ok(())
}
}
@@ -686,17 +643,21 @@ fn kernel_hostname_for_endpoint_identity() -> Result<String> {
.map_err(|_| Error::new(ErrorKind::InvalidData, "kernel hostname is not valid UTF-8"))
}
fn endpoint_is_local_host(host: Host<&str>, port: u16, local_port: u16) -> Result<bool> {
async fn lookup_startup_host_ips(host: Host<&str>) -> Result<HashSet<IpAddr>> {
#[cfg(test)]
if local_host_resolution_timeout_forced(&host) {
return Err(Error::new(ErrorKind::TimedOut, "resolver timeout"));
}
is_local_host(host, port, local_port)
match host {
Host::Domain(domain) => Ok(tokio::net::lookup_host((domain, 0)).await?.map(|addr| addr.ip()).collect()),
Host::Ipv4(ip) => Ok(HashSet::from([IpAddr::V4(ip)])),
Host::Ipv6(ip) => Ok(HashSet::from([IpAddr::V6(ip)])),
}
}
struct DnsRetryDeadline {
started: Instant,
started: TokioInstant,
timeout: Duration,
max_delay: Duration,
}
@@ -704,7 +665,7 @@ struct DnsRetryDeadline {
impl DnsRetryDeadline {
fn new(timeout: Duration, max_delay: Duration) -> Self {
Self {
started: Instant::now(),
started: TokioInstant::now(),
timeout,
max_delay,
}
@@ -718,6 +679,14 @@ impl DnsRetryDeadline {
self.started.elapsed()
}
fn expires_at(&self) -> Option<TokioInstant> {
// Zero means one lookup with no retries. MAX is the unbounded orchestrated policy.
if matches!(self.timeout, Duration::ZERO | Duration::MAX) {
return None;
}
self.started.checked_add(self.timeout)
}
fn bounded_delay(&self, delay: Duration) -> Option<Duration> {
let remaining = self.timeout.saturating_sub(self.started.elapsed());
if remaining.is_zero() {
@@ -746,17 +715,16 @@ where
RetryLog: FnMut(u32, Duration, Duration, &Error),
{
let mut attempts: u32 = 0;
let mut last_warn: Option<Instant> = None;
loop {
match resolve().await {
Ok(value) => return Ok(value),
Err(err) => {
if !is_retryable_dns_error(&err) {
return Err(permanent_error(err));
}
let result = {
let retry = async {
let mut last_warn: Option<Instant> = None;
loop {
attempts += 1;
let err = match resolve().await {
Ok(value) => return Ok(value),
Err(err) if is_retryable_dns_error(&err) => err,
Err(err) => return Err(permanent_error(err)),
};
let Some(delay) = dns_retry_deadline.bounded_delay(dns_retry_delay(attempts, dns_retry_deadline.max_delay))
else {
return Err(timeout_error(attempts, dns_retry_deadline.timeout(), err));
@@ -770,8 +738,25 @@ where
}
sleep(delay).await;
}
};
match dns_retry_deadline.expires_at() {
Some(expires_at) if expires_at <= TokioInstant::now() => None,
Some(expires_at) => tokio::select! {
biased;
() = sleep_until(expires_at) => None,
result = retry => Some(result),
},
None => Some(retry.await),
}
}
};
result.unwrap_or_else(|| {
Err(timeout_error(
attempts,
dns_retry_deadline.timeout(),
Error::new(ErrorKind::TimedOut, "startup DNS deadline elapsed"),
))
})
}
/// Action-oriented tail shared by topology convergence timeout errors so a
@@ -781,26 +766,30 @@ const TOPOLOGY_TIMEOUT_HINT: &str = "check DNS and /etc/hosts resolution, the ht
and that all peer nodes have started; on Kubernetes/orchestrated deployments set \
RUSTFS_STARTUP_TOPOLOGY_WAIT_MODE=orchestrated to keep waiting instead of exiting";
async fn resolve_local_host_with_retry(
async fn resolve_startup_host_with_retry(
host: Host<&str>,
port: u16,
local_port: u16,
context: &str,
dns_retry_deadline: &DnsRetryDeadline,
) -> Result<bool> {
resolve: &impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
) -> Result<HashSet<IpAddr>> {
retry_dns_operation(
|| {
let host = host.clone();
async move { endpoint_is_local_host(host, port, local_port) }
},
|| resolve(host.clone()),
async_sleep,
dns_retry_deadline,
|err| Error::other(format!("endpoint '{context}' local-host detection failed for host '{host}': {err}")),
|attempts, timeout, err| {
Error::other(format!(
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
let kind = if timeout.is_zero() {
ErrorKind::Other
} else {
ErrorKind::TimedOut
};
Error::new(
kind,
format!(
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
))
),
)
},
|attempts, delay, elapsed, err| {
warn!(
@@ -817,42 +806,18 @@ over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
},
)
.await
}
async fn resolve_host_ips_with_retry(
host: Host<&str>,
context: &str,
dns_retry_deadline: &DnsRetryDeadline,
) -> Result<HashSet<IpAddr>> {
retry_dns_operation(
|| {
let host = host.clone();
async move { get_host_ip(host).await }
},
async_sleep,
dns_retry_deadline,
|err| Error::other(format!("endpoint '{context}' host '{host}' cannot resolve: {err}")),
|attempts, timeout, err| {
Error::other(format!(
"endpoint '{context}' host '{host}' DNS resolution did not converge after {attempts} attempts over \
{timeout:?} (stage=host_ip_resolution): {err}. {TOPOLOGY_TIMEOUT_HINT}"
))
},
|attempts, delay, elapsed, err| {
warn!(
target = "rustfs::ecstore::endpoints",
stage = "host_ip_resolution",
context = %context,
host = %host,
attempt = attempts,
delay_ms = delay.as_millis(),
elapsed_ms = elapsed.as_millis(),
error = %err,
"retrying endpoint DNS resolution after temporary error"
);
},
)
.await
.inspect_err(|err| {
error!(
target: "rustfs::ecstore::endpoints",
event = EVENT_STARTUP_ENDPOINT_DNS_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY,
state = "failed",
host = %host,
error_kind = ?err.kind(),
"Startup endpoint DNS resolution failed"
);
})
}
fn is_retryable_dns_error(err: &Error) -> bool {
@@ -936,6 +901,26 @@ fn explicit_url_port(raw: &str) -> Result<Option<u16>> {
port.parse().map(Some).map_err(|_| invalid())
}
fn is_url_topology_with_non_literal_hosts(disks_layout: &DisksLayout) -> Result<bool> {
let mut endpoints = disks_layout
.pools
.iter()
.flat_map(|pool| pool.iter().flatten())
.map(|endpoint| Endpoint::try_from(endpoint.as_str()));
let Some(first) = endpoints.next().transpose()? else {
return Ok(false);
};
if first.get_type() != EndpointType::Url {
return Ok(false);
}
for endpoint in std::iter::once(Ok(first)).chain(endpoints) {
if !matches!(endpoint?.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
return Ok(true);
}
}
Ok(false)
}
fn infer_kubernetes_local_endpoint_host(
disks_layout: &DisksLayout,
local_port: u16,
@@ -1189,34 +1174,6 @@ fn parse_wait_duration(raw: &str) -> Option<Duration> {
}
}
/// Collapses divergent local/remote verdicts for endpoints that share the same
/// `host:port`. A `host:port` is a single network identity, so if any endpoint
/// of the group resolved as local, all of them are local. This absorbs the
/// transient inconsistency that orchestrated DNS churn can produce across the
/// several drives exported by one host.
fn normalize_same_host_local_state(pools: &mut [Endpoints]) {
let mut local_hosts: HashSet<String> = HashSet::new();
for endpoints in pools.iter() {
for ep in endpoints.as_ref() {
if ep.is_local && ep.url.has_host() {
local_hosts.insert(ep.host_port());
}
}
}
if local_hosts.is_empty() {
return;
}
for endpoints in pools.iter_mut() {
for ep in endpoints.as_mut() {
if !ep.is_local && ep.url.has_host() && local_hosts.contains(&ep.host_port()) {
ep.is_local = true;
}
}
}
}
/// represent endpoints in a given pool
/// along with its setCount and setDriveCount.
#[derive(Debug, Clone)]
@@ -1280,32 +1237,11 @@ impl EndpointServerPools {
) -> Result<(EndpointServerPools, SetupType)> {
let mut local_endpoint_host = get_env_opt_str(ENV_LOCAL_ENDPOINT_HOST);
let mut policy_override = None;
let first_endpoint = disks_layout
.pools
.iter()
.flat_map(|pool| pool.iter().flatten())
.next()
.map(|endpoint| Endpoint::try_from(endpoint.as_str()))
.transpose()?;
let distributed = first_endpoint
.as_ref()
.is_some_and(|endpoint| endpoint.get_type() == EndpointType::Url);
let mut all_distributed_hosts_are_ip_literals = distributed;
if distributed {
for raw_endpoint in disks_layout.pools.iter().flat_map(|pool| pool.iter().flatten()) {
let endpoint = Endpoint::try_from(raw_endpoint.as_str())?;
if !matches!(endpoint.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
all_distributed_hosts_are_ip_literals = false;
break;
}
}
}
let wait_mode = get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_MODE).map(|value| value.trim().to_ascii_lowercase());
let infer_kubernetes_host = local_endpoint_host.is_none()
&& distributed
&& !all_distributed_hosts_are_ip_literals
&& std::env::var_os(ENV_KUBERNETES_SERVICE_HOST).is_some()
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"));
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"))
&& is_url_topology_with_non_literal_hosts(disks_layout)?;
if infer_kubernetes_host {
let kernel_hostname = kernel_hostname_for_endpoint_identity()?;
let local_port = check_local_server_addr(server_addr)?.port();
@@ -1317,7 +1253,7 @@ impl EndpointServerPools {
policy_override = Some(StartupTopologyPolicy::resolve_from(
Some("bounded"),
true,
distributed,
true,
get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT).as_deref(),
get_env_opt_str(ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY).as_deref(),
false,
@@ -1788,7 +1724,7 @@ mod test {
#[tokio::test]
async fn system_resolver_negative_result_reaches_the_dns_allowlist() {
let Err(err) = get_host_ip(Host::Domain("rustfs-startup-negative.invalid")).await else {
let Err(err) = lookup_startup_host_ips(Host::Domain("rustfs-startup-negative.invalid")).await else {
// Some corporate and ISP resolvers synthesize an address for
// unknown names, including the reserved .invalid suffix.
return;
@@ -1959,22 +1895,48 @@ mod test {
);
}
#[test]
fn normalize_same_host_local_state_unifies_divergent_verdicts() {
let mut d1 = Endpoint::try_from("http://node1:9000/d1").unwrap();
let mut d2 = Endpoint::try_from("http://node1:9000/d2").unwrap();
d1.is_local = true;
d2.is_local = false; // divergent verdict for the same host:port
let mut remote = Endpoint::try_from("http://node2:9000/d1").unwrap();
remote.is_local = false;
#[tokio::test]
async fn startup_reuses_one_dns_answer_per_host_across_ports_and_pools() {
let mut pools = PoolEndpointList {
inner: vec![
Endpoints::try_from(["http://node1:9000/d1", "http://node1:9000/d2", "http://node2:9000/d1"].as_slice())
.expect("first pool endpoints should parse"),
Endpoints::try_from(["http://node1:9000/d3", "http://node1:9001/d4"].as_slice())
.expect("second pool endpoints should parse"),
],
setup_type: SetupType::Unknown,
};
let deadline = DnsRetryDeadline::new(Duration::ZERO, DNS_RETRY_MAX_DELAY);
let node1_lookups = std::cell::Cell::new(0);
let local_ip = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
let stale_ip = IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 10));
let resolve = async |host: Host<&str>| match host {
Host::Domain("node1") => {
let lookups = node1_lookups.get();
node1_lookups.set(lookups + 1);
Ok(HashSet::from([if lookups == 0 { stale_ip } else { local_ip }]))
}
Host::Domain("node2") => Ok(HashSet::from([stale_ip])),
_ => panic!("unexpected hostname in test: {host}"),
};
let mut pools = vec![Endpoints::from(vec![d1, d2, remote])];
normalize_same_host_local_state(&mut pools);
let first_start = pools
.resolve_startup_hosts(9000, &deadline, resolve)
.await
.expect("first lookup");
assert_eq!(node1_lookups.get(), 1);
assert_eq!(first_start["node1"].addresses, HashSet::from([stale_ip]));
assert_eq!(local_flags(&pools.inner[0]), [false, false, false]);
assert_eq!(local_flags(&pools.inner[1]), [false, false]);
let eps = pools[0].as_ref();
assert!(eps[0].is_local);
assert!(eps[1].is_local, "same host:port must inherit the local verdict");
assert!(!eps[2].is_local, "a genuinely remote host must stay remote");
let restart = pools
.resolve_startup_hosts(9000, &deadline, resolve)
.await
.expect("fresh lookup");
assert_eq!(node1_lookups.get(), 2);
assert_eq!(restart["node1"].addresses, HashSet::from([local_ip]));
assert_eq!(local_flags(&pools.inner[0]), [true, true, false]);
assert_eq!(local_flags(&pools.inner[1]), [true, false]);
}
#[test]
@@ -2020,11 +1982,11 @@ mod test {
// trip the DNS-IP cross-port check in bounded mode but must be deferred
// (allowed) in orchestrated mode, where headless-service records can
// still be flapping.
let args = vec![
let args = [
"http://192.0.2.10:9000/export",
"http://192.0.2.10:9001/export",
"http://192.0.2.11:9000/export",
"http://192.0.2.12:9000/export",
"http://127.0.0.1:9000/export",
];
let layout = DisksLayout::from_volumes(args.as_slice()).unwrap();
@@ -2046,6 +2008,24 @@ mod test {
assert_eq!(resolved.setup_type, SetupType::DistErasure);
}
#[tokio::test]
async fn rejects_startup_when_no_endpoint_is_local() {
for volumes in [
["http://192.0.2.10:9000/data", "http://192.0.2.11:9000/data"],
["http://192.0.2.10:9000/data", "http://127.0.0.1:9001/data"],
["http://192.0.2.10:9000/data1", "http://192.0.2.10:9000/data2"],
] {
let layout = DisksLayout::from_volumes(&volumes).expect("URL topology should parse");
for policy in [bounded_test_policy(), orchestrated_test_policy()] {
let err = EndpointServerPools::create_server_endpoints_with("0.0.0.0:9000", &layout, Some(policy), None)
.await
.expect_err("startup must reject a topology with no local endpoints");
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert!(err.to_string().contains("no local storage endpoints"), "{err}");
}
}
}
#[test]
fn explicit_local_endpoint_host_accepts_only_a_canonical_host() {
assert_eq!(
@@ -2274,7 +2254,7 @@ mod test {
#[serial]
#[tokio::test]
async fn create_server_endpoints_infers_kubernetes_pod_host_without_peer_dns() {
async fn create_server_endpoints_infers_kubernetes_host_after_literal_peer_without_dns() {
let _kernel_hostname = force_kernel_hostname_for_test("rustfs-0");
let local_host = "rustfs-0.rustfs-headless.ns.svc.cluster.local";
@@ -2288,14 +2268,16 @@ mod test {
let (pools, setup_type) = EndpointServerPools::from_volumes(
"0.0.0.0:9000",
vec![
"http://192.0.2.10:9000/data2".to_string(),
format!("http://{local_host}:9000/data0"),
"http://permanently-missing.invalid:9000/data1".to_string(),
"http://192.0.2.11:9000/data3".to_string(),
],
)
.await
.expect("kernel hostname inference should avoid resolving the missing peer");
assert_eq!(local_flags(&pools.0[0].endpoints), vec![true, false]);
assert_eq!(local_flags(&pools.0[0].endpoints), vec![false, true, false, false]);
assert_eq!(setup_type, SetupType::DistErasure);
},
)
@@ -2815,6 +2797,40 @@ mod test {
assert!(err.to_string().contains("timed out after 1 attempts"));
}
#[tokio::test(start_paused = true)]
async fn startup_dns_deadline_stops_pending_and_later_lookups() {
let timeout = Duration::from_secs(3);
let deadline = DnsRetryDeadline::new(timeout, DNS_RETRY_MAX_DELAY);
let lookups = std::cell::Cell::new(0);
let resolve = async |_host: Host<&str>| {
lookups.set(lookups.get() + 1);
std::future::pending::<Result<HashSet<IpAddr>>>().await
};
let err = tokio::time::timeout(
timeout * 2,
resolve_startup_host_with_retry(Host::Domain("node1"), "first endpoint", &deadline, &resolve),
)
.await
.expect("a pending lookup must complete before the test deadline")
.expect_err("a pending lookup must stop at the startup deadline");
assert_eq!(err.kind(), ErrorKind::TimedOut);
assert!(err.to_string().contains("first endpoint"));
assert!(err.to_string().contains("startup DNS deadline elapsed"));
assert_eq!(deadline.elapsed(), timeout);
assert_eq!(lookups.get(), 1);
let err = tokio::time::timeout(
timeout * 2,
resolve_startup_host_with_retry(Host::Domain("node2"), "second endpoint", &deadline, &resolve),
)
.await
.expect("a later lookup must complete before the test deadline")
.expect_err("an exhausted startup budget must prevent a new lookup");
assert!(err.to_string().contains("second endpoint"));
assert_eq!(lookups.get(), 1);
}
#[test]
fn test_new_endpoints() {
let test_cases = [
+338 -300
View File
@@ -14,8 +14,9 @@
use super::*;
#[cfg(test)]
use crate::io_support::rio::Index;
use std::mem::MaybeUninit;
use std::{mem::MaybeUninit, task::ready};
#[cfg(feature = "rio-v2")]
const DARE_PAYLOAD_SIZE: i64 = 64 * 1024;
@@ -41,11 +42,8 @@ pub(crate) fn restore_request_active(opts: &ObjectOptions) -> bool {
restore.type_.is_some() || restore.days.is_some() || restore.output_location.is_some() || restore.select_parameters.is_some()
}
fn decode_compression_index(index: Option<&Bytes>) -> Option<Index> {
crate::io_support::rio::decode_compression_index_bytes(index?)
}
fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
#[cfg(feature = "rio-v2")]
fn get_encrypted_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
let mut skip_length = 0_i64;
let mut cumulative_actual_size = 0_i64;
let mut first_part_idx = 0_usize;
@@ -63,30 +61,20 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
}
let mut part_skip = offset - skip_length;
#[cfg(feature = "rio-v2")]
let (mut decrypt_skip, mut seq_num) = (0_i64, 0_u64);
#[cfg(not(feature = "rio-v2"))]
let (decrypt_skip, seq_num) = (0_i64, 0_u64);
if part_skip > 0
&& let Some(part) = oi.parts.get(first_part_idx)
&& let Some(index) = decode_compression_index(part.index.as_ref())
&& let Some(index) = part
.index
.as_ref()
.and_then(crate::io_support::rio::decode_compression_index_bytes)
&& let Ok((comp_off, uncomp_off)) = index.find(part_skip)
&& comp_off > 0
{
#[cfg(feature = "rio-v2")]
if oi.is_encrypted() {
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
} else {
compressed_offset += comp_off;
}
#[cfg(not(feature = "rio-v2"))]
{
compressed_offset += comp_off;
}
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
part_skip -= uncomp_off;
}
@@ -94,6 +82,68 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
(compressed_offset, part_skip, first_part_idx, decrypt_skip, seq_num)
}
// Plan a window of complete compression blocks in stored coordinates. The
// index can omit the final block or record a stale total. Part metadata owns
// the actual bounds, and missing checkpoints widen only the covering parts.
fn compressed_storage_window(oi: &ObjectInfo, offset: usize, length: i64) -> Option<(usize, i64, usize)> {
let start = i64::try_from(offset).ok()?;
let end = start.checked_add(length)?;
if start >= end {
return None;
}
let (mut plaintext_offset, mut stored_offset) = (0_i64, 0_i64);
let mut window_start = None;
for part in oi.parts.iter() {
let stored_size = i64::try_from(part.size).ok()?;
let stored_end = stored_offset.checked_add(stored_size)?;
if stored_end > oi.size || part.actual_size < 0 || (part.actual_size == 0) != (stored_size == 0) {
return None;
}
let plaintext_end = plaintext_offset.checked_add(part.actual_size)?;
let starts_here = window_start.is_none() && start < plaintext_end;
let ends_here = end <= plaintext_end;
if starts_here || ends_here {
let index = part
.index
.as_ref()
.filter(|_| (starts_here && start > plaintext_offset) || (ends_here && end < plaintext_end))
.and_then(crate::io_support::rio::decode_compression_index_bytes);
if starts_here {
let relative_start = start - plaintext_offset;
let (stored, plaintext) = index
.as_ref()
.filter(|_| relative_start > 0)
.and_then(|index| index.checkpoint_at_or_before(relative_start))
.filter(|&(stored, plaintext)| {
(1..stored_size).contains(&stored) && (0..=relative_start).contains(&plaintext)
})
.unwrap_or((0, 0));
window_start = Some((stored_offset + stored, relative_start - plaintext));
}
if ends_here {
let (window_start, skip) = window_start?;
let relative_end = end - plaintext_offset;
let window_end = index
.filter(|_| relative_end < part.actual_size)
.as_ref()
.and_then(|index| index.checkpoint_at_or_after(relative_end))
.filter(|&(stored, plaintext)| {
(1..=stored_size).contains(&stored) && (relative_end..=part.actual_size).contains(&plaintext)
})
.map_or(stored_end, |(stored, _)| stored_offset + stored);
return (window_end > window_start).then_some((
usize::try_from(window_start).ok()?,
window_end - window_start,
usize::try_from(skip).ok()?,
));
}
}
plaintext_offset = plaintext_end;
stored_offset = stored_end;
}
None
}
#[cfg(feature = "rio-v2")]
fn get_encrypted_offsets(oi: &ObjectInfo, offset: i64) -> Result<(i64, usize, usize, u32, i64)> {
if oi.parts.is_empty() {
@@ -713,10 +763,12 @@ impl ReadPlan {
let actual_size = oi.get_actual_size()?;
let (storage_offset, storage_length, decompressed_offset, decompressed_length) = if let Some(rs) = rs {
let (req_off, req_length) = rs.get_offset_length(actual_size)?;
let (physical_off, decompressed_skip, _, _, _) = get_compressed_offsets(oi, req_off as i64);
let storage_offset = usize::try_from(physical_off)
.map_err(|_| Error::other(format!("invalid compressed offset {physical_off}")))?;
(storage_offset, oi.size - physical_off, decompressed_skip as usize, req_length)
let (storage_offset, storage_length, skip) = if req_length < actual_size {
compressed_storage_window(oi, req_off, req_length).unwrap_or((0, oi.size, req_off))
} else {
(0, oi.size, req_off)
};
(storage_offset, storage_length, skip, req_length)
} else {
(0, oi.size, 0, actual_size)
};
@@ -794,7 +846,7 @@ impl ReadPlan {
)?
} else if is_compressed {
let (physical_off, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
get_compressed_offsets(oi, requested_offset as i64);
get_encrypted_compressed_offsets(oi, requested_offset as i64);
(
usize::try_from(physical_off)
.map_err(|_| Error::other(format!("invalid encrypted compressed offset {physical_off}")))?,
@@ -910,40 +962,14 @@ impl ReadPlan {
decompressed_length,
total_plaintext_size,
} => {
let dec_reader = crate::io_support::rio::decompression_reader(reader, algorithm, backend);
#[cfg(feature = "rio-v2")]
let dec_reader = StreamConsumer::new(dec_reader);
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decompressed_offset > 0
|| decompressed_length != total_plaintext_size as i64
{
#[cfg(feature = "rio-v2")]
let ranged_result = RangedDecompressReader::new_draining(
dec_reader,
decompressed_offset,
decompressed_length,
total_plaintext_size,
);
#[cfg(not(feature = "rio-v2"))]
let ranged_result =
RangedDecompressReader::new(dec_reader, decompressed_offset, decompressed_length, total_plaintext_size);
match ranged_result {
Ok(ranged_reader) => {
tracing::debug!(
"Successfully created RangedDecompressReader for offset={}, length={}",
decompressed_offset,
decompressed_length
);
Box::new(ranged_reader)
}
Err(e) => {
tracing::error!("RangedDecompressReader failed with invalid range parameters: {}", e);
return Err(e);
}
}
} else {
Box::new(HardLimitReader::new(dec_reader, decompressed_length))
};
let final_reader = compressed_object_reader(
reader,
algorithm,
backend,
decompressed_offset,
decompressed_length,
total_plaintext_size,
)?;
let mut object_info = oi.clone();
object_info.size = self.object_size;
@@ -1019,29 +1045,14 @@ impl ReadPlan {
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> =
if let Some((algo, compression_backend)) = compression {
let decompressed_reader =
crate::io_support::rio::decompression_reader(decrypted_reader, algo, compression_backend);
#[cfg(feature = "rio-v2")]
let decompressed_reader = StreamConsumer::new(decompressed_reader);
if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
#[cfg(feature = "rio-v2")]
let ranged_reader = RangedDecompressReader::new_draining(
decompressed_reader,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?;
#[cfg(not(feature = "rio-v2"))]
let ranged_reader = RangedDecompressReader::new(
decompressed_reader,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?;
Box::new(ranged_reader)
} else {
Box::new(HardLimitReader::new(decompressed_reader, total_plaintext_size_i64))
}
compressed_object_reader(
decrypted_reader,
algo,
compression_backend,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?
} else if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
Box::new(RangedDecompressReader::new(
decrypted_reader,
@@ -1118,294 +1129,201 @@ impl AsyncRead for GetObjectReader {
}
}
fn compressed_object_reader(
source: Box<dyn AsyncRead + Unpin + Send + Sync>,
algorithm: CompressionAlgorithm,
backend: crate::io_support::rio::ReadCompressionBackend,
offset: usize,
length: i64,
total_size: usize,
) -> Result<Box<dyn AsyncRead + Unpin + Send + Sync>> {
let decoded = crate::io_support::rio::decompression_reader(source, algorithm, backend);
if offset != 0 || usize::try_from(length).ok() != Some(total_size) {
// A partial response needs the blocks covering its bytes. Dropping the
// source closes the producer instead of draining unrelated blocks.
return Ok(Box::new(RangedDecompressReader::new(decoded, offset, length, total_size)?));
}
#[cfg(feature = "rio-v2")]
let decoded = StreamConsumer::new(decoded);
Ok(Box::new(HardLimitReader::new(decoded, length)))
}
#[derive(Debug)]
struct SkipReader<R> {
inner: R,
bytes_to_skip: usize,
bytes_skipped: usize,
scratch: Box<[MaybeUninit<u8>]>,
remaining_skip: usize,
scratch: Option<Box<[MaybeUninit<u8>]>>,
}
impl<R: AsyncRead + Unpin + Send + Sync> SkipReader<R> {
impl<R: AsyncRead + Unpin> SkipReader<R> {
fn new(inner: R, bytes_to_skip: usize) -> Self {
Self {
inner,
bytes_to_skip,
bytes_skipped: 0,
scratch: Box::<[u8]>::new_uninit_slice(8192),
remaining_skip: bytes_to_skip,
scratch: None,
}
}
}
impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SkipReader<R> {
impl<R: AsyncRead + Unpin> AsyncRead for SkipReader<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
let this = self.as_mut().get_mut();
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
while this.bytes_skipped < this.bytes_to_skip {
let remaining = this.bytes_to_skip - this.bytes_skipped;
let scratch_len = remaining.min(this.scratch.len());
let mut scratch_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
match Pin::new(&mut this.inner).poll_read(cx, &mut scratch_buf) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Ready(Ok(())) => {
let n = scratch_buf.filled().len();
if n == 0 {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!("unexpected EOF while skipping {} bytes from decrypted stream", this.bytes_to_skip),
)));
}
this.bytes_skipped += n;
if this.remaining_skip != 0 {
let scratch_len = this.remaining_skip.min(8192);
let scratch = this.scratch.get_or_insert_with(|| Box::<[u8]>::new_uninit_slice(scratch_len));
while this.remaining_skip > 0 {
// An unindexed range can skip many decoded blocks without the source yielding.
let budget = ready!(tokio::task::coop::poll_proceed(cx));
let len = this.remaining_skip.min(scratch.len());
let mut discard = ReadBuf::uninit(&mut scratch[..len]);
ready!(Pin::new(&mut this.inner).poll_read(cx, &mut discard))?;
let n = discard.filled().len();
if n == 0 {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"object stream ended before reaching the range start",
)));
}
this.remaining_skip -= n;
budget.made_progress();
}
this.scratch = None;
}
Pin::new(&mut this.inner).poll_read(cx, buf)
}
}
/// A streaming decompression reader that supports range requests by skipping data in the decompressed stream.
/// This implementation acknowledges that compressed streams (like LZ4) must be decompressed sequentially
/// from the beginning, so it streams and discards data until reaching the target offset.
/// Reads a bounded plaintext range from a stream positioned at or before its start.
/// The source is released when the range completes. An early source EOF is an error.
#[derive(Debug)]
pub struct RangedDecompressReader<R: AsyncRead + Unpin + Send + Sync + 'static> {
inner: Option<R>,
target_offset: usize,
target_length: usize,
current_offset: usize,
bytes_returned: usize,
scratch: Box<[MaybeUninit<u8>]>,
inner: Option<tokio::io::Take<SkipReader<R>>>,
drain_on_done: bool,
drain_task: Option<tokio::task::JoinHandle<()>>,
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> RangedDecompressReader<R> {
/// Skips `offset` bytes and yields up to `length` bytes, capped by `total_size`.
///
/// # Errors
/// Returns an invalid range error if the offset is outside the stream or the length is negative.
pub fn new(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
Self::new_with_drain(inner, offset, length, total_size, false)
}
/// Reads like [Self::new] and drains any remainder in the background once the range completes.
///
/// # Errors
/// Returns the same range validation errors as [Self::new].
pub fn new_draining(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
Self::new_with_drain(inner, offset, length, total_size, true)
}
fn new_with_drain(inner: R, offset: usize, length: i64, total_size: usize, drain_on_done: bool) -> Result<Self> {
// Validate the range request
if offset >= total_size {
tracing::debug!("Range offset {} exceeds total size {}", offset, total_size);
return Err(Error::InvalidRangeSpec("Range offset exceeds file size".to_string()));
}
// Adjust length if it extends beyond file end
let actual_length = std::cmp::min(length as usize, total_size - offset);
tracing::debug!(
"Creating RangedDecompressReader: offset={}, length={}, total_size={}, actual_length={}",
offset,
length,
total_size,
actual_length
);
let length =
u64::try_from(length).map_err(|_| Error::InvalidRangeSpec("Range length must be nonnegative".to_string()))?;
let length = length.min((total_size - offset) as u64);
Ok(Self {
inner: Some(inner),
target_offset: offset,
target_length: actual_length,
current_offset: 0,
bytes_returned: 0,
scratch: Box::<[u8]>::new_uninit_slice(8192),
inner: Some(SkipReader::new(inner, offset).take(length)),
drain_on_done,
drain_task: None,
})
}
fn start_drain(&mut self) {
if !self.drain_on_done || self.drain_task.is_some() {
return;
fn finish(&mut self) {
if let Some(inner) = self.inner.take()
&& self.drain_on_done
{
drain_stream(inner.into_inner().inner);
}
let Some(mut inner) = self.inner.take() else {
return;
};
self.drain_task = Some(tokio::spawn(async move {
let mut buf = [0u8; 8192];
loop {
match inner.read(&mut buf).await {
Ok(0) => break,
Ok(_) => continue,
Err(_) => break,
}
}
}));
}
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> AsyncRead for RangedDecompressReader<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
use std::pin::Pin;
use std::task::Poll;
use tokio::io::ReadBuf;
let this = self.as_mut().get_mut();
loop {
// If we've returned all the bytes we need, return EOF
if this.bytes_returned >= this.target_length {
this.start_drain();
return Poll::Ready(Ok(()));
}
// Read from the inner stream
let buf_capacity = buf.remaining();
if buf_capacity == 0 {
return Poll::Ready(Ok(()));
}
let scratch_len = std::cmp::min(this.scratch.len(), std::cmp::max(buf_capacity, 1));
let mut temp_read_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
let Some(inner) = this.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
match Pin::new(inner).poll_read(cx, &mut temp_read_buf) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Ready(Ok(())) => {
let n = temp_read_buf.filled().len();
if n == 0 {
// EOF from inner stream
if this.current_offset < this.target_offset {
// We haven't reached the target offset yet - this is an error
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"Unexpected EOF: only read {} bytes, target offset is {}",
this.current_offset, this.target_offset
),
)));
}
// Normal EOF after reaching target
return Poll::Ready(Ok(()));
}
// Update current position
let old_offset = this.current_offset;
this.current_offset += n;
// Check if we're still in the skip phase
if old_offset < this.target_offset {
// We're still skipping data
let skip_end = std::cmp::min(this.current_offset, this.target_offset);
let bytes_to_skip_in_this_read = skip_end - old_offset;
if this.current_offset <= this.target_offset {
// All data in this read should be skipped
tracing::trace!("Skipping {} bytes at offset {}", n, old_offset);
// Continue reading in the loop instead of recursive call
continue;
} else {
// Partial skip: some data should be returned
let data_start_in_buffer = bytes_to_skip_in_this_read;
let available_data = n - data_start_in_buffer;
let bytes_to_return = std::cmp::min(
available_data,
std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned),
);
if bytes_to_return > 0 {
let data_slice =
&temp_read_buf.filled()[data_start_in_buffer..data_start_in_buffer + bytes_to_return];
buf.put_slice(data_slice);
this.bytes_returned += bytes_to_return;
tracing::trace!(
"Skipped {} bytes, returned {} bytes at offset {}",
bytes_to_skip_in_this_read,
bytes_to_return,
old_offset
);
}
return Poll::Ready(Ok(()));
}
} else {
// We're in the data return phase
let bytes_to_return =
std::cmp::min(n, std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned));
if bytes_to_return > 0 {
buf.put_slice(&temp_read_buf.filled()[..bytes_to_return]);
this.bytes_returned += bytes_to_return;
tracing::trace!("Returned {} bytes at offset {}", bytes_to_return, old_offset);
}
return Poll::Ready(Ok(()));
}
}
}
let Some(inner) = this.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
if inner.limit() == 0 {
this.finish();
return Poll::Ready(Ok(()));
}
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
ready!(Pin::new(&mut *inner).poll_read(cx, buf))?;
if before == buf.filled().len() {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"decompressed stream ended before the requested range was complete",
)));
}
if inner.limit() == 0 {
this.finish();
}
Poll::Ready(Ok(()))
}
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> Drop for RangedDecompressReader<R> {
fn drop(&mut self) {
if self.bytes_returned >= self.target_length {
self.start_drain();
if self.inner.as_ref().is_some_and(|inner| inner.limit() == 0) {
self.finish();
}
}
}
/// A wrapper that ensures the inner stream is fully consumed even if the outer reader stops early.
/// This prevents broken pipe errors in erasure coding scenarios where the writer expects
/// the full stream to be consumed.
fn drain_stream<R: AsyncRead + Unpin + Send + 'static>(mut stream: R) {
drop(tokio::spawn(async move {
let mut buf = [0u8; 8192];
while matches!(stream.read(&mut buf).await, Ok(n) if n > 0) {}
}));
}
/// Drains the source in the background if dropped before observing its EOF.
pub struct StreamConsumer<R: AsyncRead + Unpin + Send + 'static> {
inner: Option<R>,
consumer_task: Option<tokio::task::JoinHandle<()>>,
}
impl<R: AsyncRead + Unpin + Send + 'static> StreamConsumer<R> {
pub fn new(inner: R) -> Self {
Self {
inner: Some(inner),
consumer_task: None,
}
}
fn ensure_consumer_started(&mut self) {
if self.consumer_task.is_none() && self.inner.is_some() {
let mut inner = self.inner.take().unwrap();
let task = tokio::spawn(async move {
let mut buf = [0u8; 8192];
loop {
match inner.read(&mut buf).await {
Ok(0) => break, // EOF
Ok(_) => continue, // Keep consuming
Err(_) => break, // Error, stop consuming
}
}
});
self.consumer_task = Some(task);
}
Self { inner: Some(inner) }
}
}
impl<R: AsyncRead + Unpin + Send + 'static> AsyncRead for StreamConsumer<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
use std::pin::Pin;
use std::task::Poll;
if let Some(ref mut inner) = self.inner {
Pin::new(inner).poll_read(cx, buf)
} else {
Poll::Ready(Ok(())) // EOF
let Some(inner) = self.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
ready!(Pin::new(inner).poll_read(cx, buf))?;
if before == buf.filled().len() {
self.inner = None;
}
Poll::Ready(Ok(()))
}
}
impl<R: AsyncRead + Unpin + Send + 'static> Drop for StreamConsumer<R> {
fn drop(&mut self) {
self.ensure_consumer_started();
if let Some(inner) = self.inner.take() {
drain_stream(inner);
}
}
}
@@ -1666,6 +1584,129 @@ mod tests {
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
}
#[tokio::test]
async fn ranged_reader_fills_large_buffers_without_overreading() {
let data = vec![0x32; 128 * 1024];
let length = 64 * 1024;
let mut reader = RangedDecompressReader::new(Cursor::new(data.clone()), 0, length as i64, data.len()).unwrap();
let mut output = vec![0xa5; data.len()];
assert_eq!(reader.read(&mut output).await.unwrap(), length);
assert_eq!(&output[..length], &data[..length]);
assert!(output[length..].iter().all(|&byte| byte == 0xa5));
assert_eq!(reader.read(&mut output).await.unwrap(), 0);
}
#[tokio::test]
async fn ranged_reader_skips_in_bulk_with_a_small_response_buffer() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountReads {
cursor: Cursor<Vec<u8>>,
calls: Arc<AtomicUsize>,
}
impl AsyncRead for CountReads {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
self.calls.fetch_add(1, Ordering::Relaxed);
Pin::new(&mut self.cursor).poll_read(cx, buf)
}
}
let skip = 512 * 1024;
let mut data = vec![0xa5; skip];
data.extend_from_slice(b"wanted bytes here");
let total = data.len();
let calls = Arc::new(AtomicUsize::new(0));
let inner = CountReads {
cursor: Cursor::new(data),
calls: Arc::clone(&calls),
};
let mut reader = RangedDecompressReader::new(inner, skip, 16, total).unwrap();
let mut output = [0; 16];
reader.read_exact(&mut output).await.unwrap();
assert_eq!(&output, b"wanted bytes her");
assert_eq!(calls.load(Ordering::Relaxed), 65, "64 discards and one response read");
}
#[tokio::test]
async fn ranged_reader_yields_while_skipping_an_unindexed_prefix() {
let skip = 2 * 1024 * 1024;
let data = vec![0x36; skip + 1];
let total = data.len();
let mut reader = RangedDecompressReader::new(Cursor::new(data), skip, 1, total).unwrap();
let mut output = [0; 1];
let mut buf = ReadBuf::new(&mut output);
let mut yielded = false;
std::future::poll_fn(|cx| {
let poll = Pin::new(&mut reader).poll_read(cx, &mut buf);
yielded |= poll.is_pending();
poll
})
.await
.unwrap();
assert!(yielded, "a long discard must yield even when the source stays ready");
assert_eq!(buf.filled(), &[0x36]);
}
#[tokio::test]
async fn ranged_reader_releases_the_source_when_the_range_completes() {
use tokio::io::AsyncWriteExt;
let (source, mut producer) = tokio::io::duplex(16);
producer.write_all(b"abcxyz").await.unwrap();
let mut reader = RangedDecompressReader::new(source, 0, 3, 6).unwrap();
let mut body = [0; 3];
reader.read_exact(&mut body).await.unwrap();
assert_eq!(&body, b"abc");
let error = producer
.write_all(b"!")
.await
.expect_err("completed range must release the pipe");
assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
assert_eq!(reader.read(&mut body).await.unwrap(), 0);
}
#[tokio::test]
async fn ranged_reader_drains_the_source_when_requested() {
use tokio::io::AsyncWriteExt;
let (source, mut producer) = tokio::io::duplex(8);
producer.write_all(b"abc").await.unwrap();
let mut reader = RangedDecompressReader::new_draining(source, 0, 3, 19).unwrap();
let mut body = [0; 3];
reader.read_exact(&mut body).await.unwrap();
assert_eq!(&body, b"abc");
tokio::time::timeout(std::time::Duration::from_secs(2), producer.write_all(b"0123456789abcdef"))
.await
.expect("completed range must start draining the source")
.expect("draining must keep the pipe open");
}
#[tokio::test]
async fn stream_consumer_observes_eof_only_with_a_nonempty_buffer() {
let mut reader = StreamConsumer::new(Cursor::new(b"body"));
assert_eq!(reader.read(&mut []).await.unwrap(), 0);
let mut output = Vec::new();
reader.read_to_end(&mut output).await.unwrap();
assert_eq!(output, b"body");
assert!(reader.inner.is_none(), "observed EOF needs no background drain");
}
#[tokio::test]
async fn ranged_decompress_reader_rejects_eof_inside_the_requested_range() {
let mut reader = RangedDecompressReader::new(Cursor::new(b"abc"), 1, 3, 4).unwrap();
let mut output = Vec::new();
let error = reader.read_to_end(&mut output).await.expect_err("short range must fail");
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
assert_eq!(output, b"bc");
}
#[tokio::test]
async fn test_ranged_decompress_reader_from_start() {
let original_data = b"Hello, World! This is a test.";
@@ -2688,10 +2729,6 @@ mod tests {
let (compressed_offset, uncompressed_offset) = decoded.find(2_097_152).expect("seek into decoded index");
assert!(compressed_offset > 0);
assert_eq!(uncompressed_offset, 2_097_152);
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, 2_097_152);
assert!(physical_offset > 0);
assert_eq!(decompressed_skip, 0);
let range = HTTPRangeSpec {
is_suffix_length: false,
start: 2_097_152,
@@ -2830,7 +2867,8 @@ mod tests {
assert!(compressed_offset > 0);
assert_eq!(uncompressed_offset, range.start);
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, range.start);
let (physical_offset, _, decompressed_skip) =
compressed_storage_window(&object_info, range.start as usize, 10).expect("indexed range");
assert!(physical_offset > 0);
assert_eq!(decompressed_skip, 0);
@@ -2838,14 +2876,14 @@ mod tests {
.await
.expect("MinIO headerless compression index should be decoded");
assert_eq!(plan.storage_offset as i64, physical_offset);
assert_eq!(plan.storage_offset, physical_offset);
assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
assert_eq!(plan.object_size, 10);
}
#[cfg(feature = "rio-v2")]
#[test]
fn test_get_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
fn test_get_encrypted_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
let mut index = Index::new();
index.add(0, 0).unwrap();
index.add(200_000, 2_097_152).unwrap();
@@ -2879,7 +2917,7 @@ mod tests {
};
let (physical_offset, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
get_compressed_offsets(&object_info, 2_097_152);
get_encrypted_compressed_offsets(&object_info, 2_097_152);
assert_eq!(first_part_idx, 0);
assert_eq!(physical_offset, (expected_comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE);
@@ -12,7 +12,6 @@ const HISTORICAL_INDEX: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/compression-index/pre-zigzag-index.bin"
));
#[cfg(not(feature = "rio-v2"))]
const CURRENT_INDEX: &[u8] =
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/compression-index/zigzag-index.bin"));
const PLAINTEXT_LEN: usize = 3 * 1024 * 1024 + 123;
@@ -161,6 +160,16 @@ async fn truncated_index_falls_back_without_truncating_the_range() {
assert_eq!(actual, fixture_plaintext()[start..start + 97]);
}
#[test]
fn compression_metadata_requires_one_complete_index() {
use crate::io_support::rio::decode_compression_index_bytes;
let index = Bytes::from_static(CURRENT_INDEX);
assert!(decode_compression_index_bytes(&index).is_some());
let trailing = Bytes::from([CURRENT_INDEX, b"trailing bytes"].concat());
assert!(decode_compression_index_bytes(&trailing).is_none());
}
#[tokio::test]
async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
let info = fixture_info(HISTORICAL_INDEX);
@@ -183,3 +192,105 @@ async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
assert!(actual.len() < PLAINTEXT_LEN);
}
#[tokio::test]
async fn compressed_ranges_bound_storage_for_large_index_and_unsampled_tail() {
use crate::io_support::rio::compression_index_storage_bytes;
use rustfs_rio::{CompressReader, TryGetIndex};
const BLOCK: usize = 1024 * 1024;
const BLOCKS: usize = 203;
const TAIL: usize = 32 * 1024;
const LENGTH: usize = 16 * 1024;
let len = BLOCK * BLOCKS + TAIL;
let mut compressor = CompressReader::new(
tokio::io::repeat(b'a')
.take((len - TAIL) as u64)
.chain(tokio::io::repeat(b'z').take(TAIL as u64)),
CompressionAlgorithm::Lz4,
);
let mut stored = Vec::new();
compressor.read_to_end(&mut stored).await.expect("compress fixture");
let index = compressor.try_get_index().expect("legacy writer has an index");
assert!(index.len() > 200);
assert_eq!(index.total_uncompressed, (len - TAIL) as i64, "short final block is not indexed");
let index = compression_index_storage_bytes(index);
let mut info = fixture_info(&index);
info.size = stored.len() as i64;
info.actual_size = len as i64;
let part = &mut Arc::make_mut(&mut info.parts)[0];
part.size = stored.len();
part.actual_size = len as i64;
for start in [1000, 9999, BLOCK - 7, len - LENGTH] {
let range = if start == len - LENGTH {
HTTPRangeSpec {
is_suffix_length: true,
start: -(LENGTH as i64),
end: -1,
}
} else {
HTTPRangeSpec {
is_suffix_length: false,
start: start as i64,
end: (start + LENGTH - 1) as i64,
}
};
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
.await
.expect("plan valid range");
let physical_start = plan.storage_offset;
let physical_end = physical_start + usize::try_from(plan.storage_length).expect("positive storage window");
let mut output = Vec::new();
let (mut reader, _, _) = plan
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
.expect("valid plaintext range has a reader");
reader.read_to_end(&mut output).await.expect("decode from planned window");
let expected_byte = if start == len - LENGTH { b'z' } else { b'a' };
assert_eq!(output, vec![expected_byte; LENGTH], "range starting at {start}");
assert!(
physical_end - physical_start < stored.len() / 20,
"range at {start} reads too much compressed data"
);
if start == len - LENGTH {
assert!(physical_start > stored.len() * 9 / 10, "suffix must seek within the final part");
}
}
}
#[tokio::test]
async fn compressed_multipart_window_stops_at_the_last_covering_part() {
let mut info = fixture_info(CURRENT_INDEX);
let parts = Arc::make_mut(&mut info.parts);
parts.push(ObjectPartInfo {
number: 2,
..parts[0].clone()
});
parts.push(ObjectPartInfo {
number: 3,
..parts[0].clone()
});
info.size *= 3;
info.actual_size = (PLAINTEXT_LEN * 3) as i64;
let range = HTTPRangeSpec {
is_suffix_length: false,
start: PLAINTEXT_LEN as i64 - 16,
end: PLAINTEXT_LEN as i64 + 15,
};
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
.await
.expect("valid range across parts");
let physical_start = plan.storage_offset;
let physical_end = physical_start + plan.storage_length as usize;
assert!(physical_end > STREAM.len(), "range crosses the stored part boundary");
assert!(physical_end < STREAM.len() * 2, "range should stop at the first checkpoint in part two");
let stored = STREAM.repeat(3);
let (mut reader, _, _) = plan
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
.expect("create multipart range reader");
let mut output = Vec::new();
reader.read_to_end(&mut output).await.expect("decode part boundary");
let plaintext = fixture_plaintext();
assert_eq!(output, [&plaintext[PLAINTEXT_LEN - 16..], &plaintext[..16]].concat());
}
+8
View File
@@ -54,6 +54,7 @@ use crate::store::delete_recovery_runtime::DeleteRecoveryHints;
use rustfs_lock::{GlobalLockManager, get_global_lock_manager};
use rustfs_s3_types::Region;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroUsize;
use std::sync::{
Arc, OnceLock,
atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
@@ -234,6 +235,8 @@ pub struct InstanceContext {
/// drift out of sync). Stored as one value so the three predicates can
/// never observe a torn intermediate state.
erasure_kind: RwLock<SetupType>,
/// Snapshot of the creating thread's affinity and CPU quota for instance workers.
worker_parallelism: NonZeroUsize,
list_read_budget: OnceLock<ListReadBudget>,
#[cfg(feature = "internode-transport")]
internode_data_transport: OnceLock<Arc<dyn crate::api::rpc::InternodeDataTransport>>,
@@ -464,6 +467,7 @@ impl InstanceContext {
fn with_lock_manager(lock_manager: Arc<GlobalLockManager>) -> Self {
Self {
erasure_kind: RwLock::new(SetupType::Unknown),
worker_parallelism: super::detect_worker_parallelism(),
list_read_budget: OnceLock::new(),
#[cfg(feature = "internode-transport")]
internode_data_transport: OnceLock::new(),
@@ -515,6 +519,10 @@ impl InstanceContext {
Self::with_lock_manager(lock_manager)
}
pub(crate) fn worker_parallelism(&self) -> NonZeroUsize {
self.worker_parallelism
}
/// This instance's namespace lock manager.
pub fn lock_manager(&self) -> Arc<GlobalLockManager> {
self.lock_manager.clone()
+4
View File
@@ -18,3 +18,7 @@ pub(crate) mod global;
pub(crate) mod instance;
pub(crate) mod sources;
pub(crate) mod usage_watch;
pub(crate) fn detect_worker_parallelism() -> std::num::NonZeroUsize {
std::thread::available_parallelism().unwrap_or(std::num::NonZeroUsize::MIN)
}
@@ -2443,6 +2443,197 @@ mod tests {
});
}
/// A stopped run left a multipart version committed on the target pool
/// and still present on the source. Its metadata reads back from two of
/// the four target drives, but a copy held only there is one drive loss
/// from unreadable: while the target set is below write quorum the retry
/// must keep the source. Once the drives are back it settles on the
/// committed copy without writing it again.
#[test]
#[serial_test::serial]
fn real_rebalance_retry_keeps_the_source_while_the_committed_target_is_below_write_quorum() {
run_large_stack_async_test("rebalance-degraded-equivalent-target", || async {
const REBALANCE_ID: &str = "rebalance-degraded-equivalent-target";
let (_temp_dirs, store, _peer) = super::super::test_pool_stores_with_contexts(None, true, 2, 4).await;
let bucket = "rebalance-degraded-target";
let object = "multipart.bin";
Box::pin(store.make_bucket(
bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
))
.await
.expect("create bucket");
prepare_rebalance_test_volumes(&store).await;
let incarnation = store.bucket_incarnation_id(bucket).await.expect("bucket incarnation");
let rebalance_meta = active_rebalance_meta(REBALANCE_ID);
rebalance_meta
.save(Arc::clone(&store.pools[0]))
.await
.expect("persist the active rebalance run");
*store.rebalance_meta.write().await = Some(rebalance_meta);
let source_set = store.pools[0].get_disks_by_key(object);
let target_set = store.pools[1].get_disks_by_key(object);
// Four drives per set written as 2+2: read quorum 2, write quorum 3.
let storage_class = crate::config::storageclass::lookup_config_for_pools_without_env(
&rustfs_config::server_config::KVS::new(),
&[4, 4],
)
.expect("the automatic storage class resolves for both pools");
source_set.set_test_storage_class_config(storage_class.clone());
target_set.set_test_storage_class_config(storage_class);
let write_opts = ObjectOptions {
versioned: true,
..Default::default()
};
let upload = Box::pin(source_set.new_multipart_upload(bucket, object, &write_opts))
.await
.expect("create the source multipart upload");
let parts = [vec![0x5a; 5 << 20], vec![0xa5; 1024]];
let mut completed = Vec::with_capacity(parts.len());
for (index, bytes) in parts.iter().enumerate() {
let part = Box::pin(source_set.put_object_part(
bucket,
object,
&upload.upload_id,
index + 1,
&mut PutObjReader::from_vec(bytes.clone()),
&write_opts,
))
.await
.expect("write a source part");
completed.push(CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
});
}
let written = Box::pin(Arc::clone(&source_set).complete_multipart_upload(
bucket,
object,
&upload.upload_id,
completed,
&write_opts,
))
.await
.expect("complete the source multipart upload");
assert!(written.is_multipart(), "the migration must use its multipart path");
let version_id = written.version_id.expect("the source version id");
let source_versions = || async {
source_set
.load_file_info_versions_exact(bucket, object)
.await
.expect("read source versions")
};
let version = source_versions().await.expect("the source version").versions.remove(0);
assert_eq!(version.version_id, Some(version_id));
// The stopped run: the copy commits on the target and the source
// cleanup never runs.
let read_opts = super::super::migration::rebalance_object_migration_read_opts(&version);
let reader = Box::pin(source_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("read the source version");
let copied = Box::pin(Arc::clone(&store).rebalance_object(0, bucket.to_owned(), reader, Some(incarnation), None))
.await
.expect("commit the copy on the target pool");
assert_eq!(copied, data_movement::DataMovementCopy::Committed);
let committed = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("the target holds the committed copy");
assert!(committed.data_dir.is_some());
assert_eq!((committed.data_blocks, committed.parity_blocks), (2, 2), "the target copy must be 2+2");
assert!(source_versions().await.is_some(), "the stopped run left the source in place");
let run_entry = || async {
let entry = metacache_entry_from_source(&source_set, bucket, object).await;
tokio::time::timeout(
StdDuration::from_secs(60),
Box::pin(Arc::clone(&store).rebalance_entry(
RebalanceEntryTarget {
bucket: bucket.to_owned(),
pool_index: 0,
},
entry,
Arc::clone(&source_set),
Arc::new(RebalanceBucketConfigs {
bucket_incarnation_id: Some(incarnation),
..Default::default()
}),
Arc::from(REBALANCE_ID),
CancellationToken::new(),
)),
)
.await
.expect("the entry must finish within the test deadline")
};
let offline = {
let mut disks = target_set.disks.write().await;
[disks[0].take(), disks[1].take()]
};
assert!(offline.iter().all(Option::is_some), "the fixture drives must have been online");
let degraded = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("two drives still serve the committed copy's metadata");
assert_eq!(degraded.data_dir, committed.data_dir);
let outcome = run_entry().await;
assert!(
!matches!(outcome, Ok(RebalanceEntryOutcome::Completed)),
"the entry must not complete on a target below write quorum: {outcome:?}"
);
let kept = source_versions()
.await
.expect("the source must survive a target below write quorum");
assert_eq!(kept.versions.len(), 1, "{:?}", kept.versions);
assert_eq!(kept.versions[0].version_id, Some(version_id));
let mut source_reader = Box::pin(source_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("the source version must stay readable");
let mut source_bytes = Vec::new();
source_reader
.stream
.read_to_end(&mut source_bytes)
.await
.expect("drain the source version");
assert_eq!(source_bytes, parts.concat());
{
let mut disks = target_set.disks.write().await;
let [first, second] = offline;
disks[0] = first;
disks[1] = second;
}
let outcome = run_entry().await.expect("rebalance entry on a healthy target");
assert_eq!(outcome, RebalanceEntryOutcome::Completed);
assert!(
source_versions().await.is_none(),
"the source is removed once the target holds the version on write quorum"
);
let settled = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("the target still holds the committed copy");
assert_eq!(settled.data_dir, committed.data_dir, "the retry must not rewrite the committed copy");
let mut target_reader = Box::pin(target_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("the committed copy must be readable");
let mut target_bytes = Vec::new();
target_reader
.stream
.read_to_end(&mut target_bytes)
.await
.expect("drain the committed copy");
assert_eq!(target_bytes, parts.concat());
});
}
const TRANSITIONED_REBALANCE_ID: &str = "rebalance-transitioned-source-cleanup";
/// One transitioned source version on pool 0 of a two-pool store with an
+534 -135
View File
@@ -149,7 +149,7 @@ use std::{
time::{Duration, Instant},
};
use tokio::io::{AsyncRead, ReadBuf};
use tokio::sync::{RwLock, mpsc, oneshot};
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::task::JoinSet;
pub(in crate::set_disk) const EVENT_SET_DISK_READ: &str = "set_disk_read";
@@ -1307,12 +1307,21 @@ pub(in crate::set_disk) fn record_bitrot_reader_setup_strategy(
}
}
#[cfg(unix)]
enum BatchPreadOutcome {
Selected(Box<BitrotReaderSetup>),
BudgetExhausted,
NotEligible,
}
/// When all online shards are local and mmap-read is enabled, materialize
/// shard bytes through `batch_shard_pread` instead of the per-shard
/// `open_disk_reader` path. Demand-bound reads add parity batches only as needed.
/// shard bytes through `batch_shard_pread_with_permits` instead of the
/// per-shard `open_disk_reader` path. Demand-bound reads add parity batches
/// only as needed, and every batch reserves its full in-flight byte budget
/// before allocating buffers.
#[cfg(unix)]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
@@ -1328,15 +1337,16 @@ async fn try_create_bitrot_readers_via_batch_pread(
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
use crate::disk::local::batch_shard_pread;
) -> BatchPreadOutcome {
use crate::disk::local::batch_shard_pread_with_permits;
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
use rustfs_io_metrics::{LocalBatchReadDecision, record_local_batch_read_decision};
use std::io::Cursor;
// Scoped q reads retain the normal source's disk admission and memory
// receipts; the foreground batch worker does not carry resource units.
if frame_size != shard_size && crate::disk::has_resource_io_scope() {
return None;
return BatchPreadOutcome::NotEligible;
}
let prepare_started = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
@@ -1347,14 +1357,14 @@ async fn try_create_bitrot_readers_via_batch_pread(
bitrot_encoded_range_with_frame_size(read_offset, read_length, shard_size, frame_size, checksum_algo.clone());
if adj_len > object_mmap_read_max_length() {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
return None;
return BatchPreadOutcome::NotEligible;
}
let mut batch_items: Vec<(usize, std::path::PathBuf, usize, usize)> = Vec::new();
for (idx, disk_op) in disks.iter().enumerate() {
if files.get(idx).is_some_and(|fi| fi.data.is_some()) {
record_decision(LocalBatchReadDecision::InlineData);
return None;
return BatchPreadOutcome::NotEligible;
}
if let Some(disk) = disk_op.as_ref() {
let data_dir = files[idx].data_dir.unwrap_or_default();
@@ -1363,11 +1373,11 @@ async fn try_create_bitrot_readers_via_batch_pread(
Some(Ok(p)) => batch_items.push((idx, p, adj_off, adj_len)),
Some(Err(_)) => {
record_decision(LocalBatchReadDecision::InvalidPath);
return None;
return BatchPreadOutcome::NotEligible;
}
None => {
record_decision(LocalBatchReadDecision::NonLocalShard);
return None;
return BatchPreadOutcome::NotEligible;
}
}
}
@@ -1375,7 +1385,7 @@ async fn try_create_bitrot_readers_via_batch_pread(
if batch_items.is_empty() {
record_decision(LocalBatchReadDecision::NoLocalShards);
return None;
return BatchPreadOutcome::NotEligible;
}
// Legacy lockstep consumes every shard, so retain its coalesced batch for
@@ -1398,22 +1408,38 @@ async fn try_create_bitrot_readers_via_batch_pread(
batch_items.len()
};
let mut pending = batch_items.into_iter();
record_decision(LocalBatchReadDecision::Selected);
let mut selected_recorded = false;
loop {
let mut indices = Vec::with_capacity(batch_size.min(pending.len()));
let requests: Vec<_> = pending
.by_ref()
.take(batch_size)
.map(|(idx, path, offset, length)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length)
})
.collect();
if !requests.is_empty() {
for (idx, result) in indices.into_iter().zip(batch_shard_pread(requests).await) {
let batch_slice: Vec<_> = pending.by_ref().take(batch_size).collect();
if !batch_slice.is_empty() {
let lengths: Vec<usize> = batch_slice.iter().map(|(_, _, _, length)| *length).collect();
let Some(permits) = global_in_flight_read_budget().try_reserve_batch(&lengths) else {
// Drop any shard readers materialized in earlier loop rounds so
// their permits return to the global budget before falling back
// to the streaming path.
drop(setup);
if !selected_recorded {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
}
return BatchPreadOutcome::BudgetExhausted;
};
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
selected_recorded = true;
}
let mut indices = Vec::with_capacity(batch_slice.len());
let requests: Vec<_> = batch_slice
.into_iter()
.zip(permits)
.map(|((idx, path, offset, length), permit)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length, permit)
})
.collect();
for (idx, result) in indices.into_iter().zip(batch_shard_pread_with_permits(requests).await) {
let result = result.map(|bytes| {
Some(BitrotReader::new_with_frame_size(
ShardReader::InMemory(Cursor::new(bytes)),
@@ -1437,11 +1463,20 @@ async fn try_create_bitrot_readers_via_batch_pread(
.saturating_sub(setup.available_shards());
}
Some(setup)
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
}
BatchPreadOutcome::Selected(Box::new(setup))
}
#[cfg(not(unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread_unsupported() {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
}
#[cfg(all(test, not(unix)))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
_files: &[FileInfo],
_disks: &[Option<DiskStore>],
@@ -1459,10 +1494,53 @@ async fn try_create_bitrot_readers_via_batch_pread(
_mode: BitrotReaderSetupMode,
_strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
try_create_bitrot_readers_via_batch_pread_unsupported().await;
None
}
#[cfg(all(test, unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
part_number: usize,
read_offset: usize,
read_length: usize,
shard_size: usize,
frame_size: usize,
checksum_algo: HashAlgorithm,
skip_verify_bitrot: bool,
data_shards: usize,
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(setup) => Some(*setup),
BatchPreadOutcome::BudgetExhausted | BatchPreadOutcome::NotEligible => None,
}
}
#[allow(dead_code, reason = "compatibility wrapper for the legacy shard geometry")]
#[allow(clippy::too_many_arguments)]
pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_all_shards(
@@ -1726,48 +1804,67 @@ pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_with_prefere
} else {
true
};
if batch_read_enabled
&& let Some(mut setup) = try_create_bitrot_readers_via_batch_pread(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return setup;
}
let use_mmap_read = if batch_read_enabled {
#[cfg(unix)]
{
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(mut setup) => {
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return *setup;
}
BatchPreadOutcome::BudgetExhausted => {
// Fall straight through to the bounded streaming reader path
// instead of re-attempting per-shard in-memory mmap copies.
false
}
BatchPreadOutcome::NotEligible => use_mmap_read,
}
}
#[cfg(not(unix))]
{
try_create_bitrot_readers_via_batch_pread_unsupported().await;
use_mmap_read
}
} else {
use_mmap_read
};
if strategy == BitrotReaderSetupStrategy::AllShards {
return create_bitrot_readers_until_quorum_all_shards_with_frame_size(
@@ -3279,6 +3376,7 @@ fn rename_tail_cleanup_queue() -> &'static RenameTailCleanupQueue {
}
const EVENT_SET_DISK_RENAME_ROLLBACK: &str = "set_disk_rename_rollback";
const PUT_RENAME_POST_QUORUM_DISPATCH_GRACE: Duration = Duration::from_secs(1);
#[derive(Clone, Copy)]
enum RenameDispatchState {
@@ -3305,12 +3403,22 @@ struct RenameBatchGroup {
slots: Vec<usize>,
}
#[derive(Clone)]
struct RenameSlotPaths {
src_bucket: Arc<String>,
src_object: Arc<String>,
dst_bucket: Arc<String>,
dst_object: Arc<String>,
src_bucket: String,
src_object: String,
dst_bucket: String,
dst_object: String,
}
impl RenameSlotPaths {
fn new(src_bucket: &str, src_object: &str, dst_bucket: &str, dst_object: &str) -> Self {
Self {
src_bucket: src_bucket.to_owned(),
src_object: src_object.to_owned(),
dst_bucket: dst_bucket.to_owned(),
dst_object: dst_object.to_owned(),
}
}
}
struct RenameSlotContext {
@@ -3320,20 +3428,22 @@ struct RenameSlotContext {
scanner_token: Option<Uuid>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
successful_completion_rank: Option<Arc<AtomicUsize>>,
write_quorum: usize,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducerArgs {
disks: Arc<Vec<Option<DiskStore>>>,
file_infos: Arc<Vec<FileInfo>>,
fence_tokens: Arc<Vec<Option<Uuid>>>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
write_quorum: usize,
allow_batch: bool,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducers {
@@ -3827,6 +3937,7 @@ pub(in crate::set_disk) struct RenameDataFenceOptions<'a> {
rollback_receipt: Option<RenameRollbackReceipt>,
multipart_proof_authority: Option<crate::disk::multipart_source::ProofVerificationContext>,
multipart_commit_owner: Option<Arc<MultipartLogicalGuards>>,
bound_dispatch_after_quorum: bool,
}
impl<'a> RenameDataFenceOptions<'a> {
@@ -3842,9 +3953,15 @@ impl<'a> RenameDataFenceOptions<'a> {
rollback_receipt: None,
multipart_proof_authority: None,
multipart_commit_owner: None,
bound_dispatch_after_quorum: false,
}
}
pub(in crate::set_disk) fn with_quorum_bounded_dispatch(mut self, enabled: bool) -> Self {
self.bound_dispatch_after_quorum = enabled;
self
}
pub(in crate::set_disk) fn with_multipart_commit_owner(mut self, owner: Arc<MultipartLogicalGuards>) -> Self {
self.multipart_commit_owner = Some(owner);
self
@@ -4426,6 +4543,7 @@ impl SetDisks {
disk::RenameDataGuards {
scanner_publication_lease_token: context.scanner_token,
namespace_owner: context.namespace_owner.clone(),
dispatch_deadline: context.dispatch_deadline.clone(),
..Default::default()
},
)
@@ -4602,6 +4720,7 @@ impl SetDisks {
publication_scope,
write_quorum,
allow_batch,
dispatch_deadline,
} = args;
debug_assert!(!allow_batch || publication_scope.is_none());
let disk_count = disks.len();
@@ -4626,6 +4745,10 @@ impl SetDisks {
continue;
}
let outcome_tx = outcome_tx.clone();
let dispatch_deadline = dispatch_deadline
.as_ref()
.filter(|_| disk.as_ref().is_some_and(|disk| !disk.is_local()))
.cloned();
let context = RenameSlotContext {
slot,
disk,
@@ -4636,6 +4759,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline,
};
let resource_unit = resource_unit.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
@@ -4653,6 +4777,7 @@ impl SetDisks {
let group_disks = disks.clone();
let group_tokens = fence_tokens.clone();
let resource_unit = resource_unit.clone();
let dispatch_deadline = dispatch_deadline.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
let prepared = join_all(group.slots.into_iter().map(|slot| {
let context = RenameSlotContext {
@@ -4665,6 +4790,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline: dispatch_deadline.clone(),
};
async move { (slot, Self::prepare_and_admit_rename_slot(context).await) }
}))
@@ -4736,6 +4862,7 @@ impl SetDisks {
&paths.dst_bucket,
&paths.dst_object,
items,
dispatch_deadline,
)
.await
}
@@ -4844,6 +4971,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority: _,
multipart_commit_owner: _,
bound_dispatch_after_quorum: _,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -4864,19 +4992,13 @@ impl SetDisks {
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(disks, &file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let coordinator_disks = fanout_disks.clone();
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let (commit_tx, commit_rx) = oneshot::channel();
let coordinator_failure_receipt = rollback_receipt.clone();
let early_ack_spawn_to_quorum_wait_started = rustfs_io_metrics::put_stage_timer();
let tail_drain = tokio::spawn(crate::disk::with_detached_disk_io_context({
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
let paths = paths.clone();
async move {
let allow_batch = scanner_publication_commit_scope.is_none();
let RenameOutcomeProducers {
@@ -4886,16 +5008,12 @@ impl SetDisks {
disks: fanout_disks.clone(),
file_infos: file_infos.clone(),
fence_tokens: fanout_fence_tokens.clone(),
paths: RenameSlotPaths {
src_bucket: fanout_src_bucket.clone(),
src_object: fanout_src_object.clone(),
dst_bucket: fanout_dst_bucket.clone(),
dst_object: fanout_dst_object.clone(),
},
paths: paths.clone(),
namespace_owner: namespace_commit_guard.clone().map(|owner| owner as Arc<dyn Send + Sync>),
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline: None,
});
let mut commit_tx = Some(commit_tx);
@@ -4980,7 +5098,7 @@ impl SetDisks {
}
if let Some(commit_tx) = commit_tx.take() {
#[cfg(test)]
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&fanout_dst_object).await;
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&paths.dst_object).await;
let _ = commit_tx.send(snapshot_commit);
}
sent_commit = true;
@@ -4998,7 +5116,7 @@ impl SetDisks {
);
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&paths.dst_object);
if rustfs_io_metrics::put_stage_metrics_enabled() {
let fanout_success = errs.iter().filter(|err| err.is_none()).count();
let fanout_error = errs.len().saturating_sub(fanout_success + fanout_panic);
@@ -5021,7 +5139,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&fanout_dst_bucket, &fanout_dst_object),
(&paths.dst_bucket, &paths.dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5068,11 +5186,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = fanout_dst_bucket.clone();
let dst_object = fanout_dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -5081,16 +5198,16 @@ impl SetDisks {
Ok(Err(DiskError::FileNotFound | DiskError::VolumeNotFound)) => {}
Ok(Err(err)) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %err,
"rollback backup reclamation failed after committed rename"
);
}
Err(join_err) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %join_err,
"rollback backup reclamation task failed after committed rename"
);
@@ -5136,7 +5253,7 @@ impl SetDisks {
let commit = match commit_rx.await {
Ok(commit) => commit,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), coordinator_failure_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), coordinator_failure_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5216,6 +5333,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority,
multipart_commit_owner,
bound_dispatch_after_quorum,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -5239,28 +5357,15 @@ impl SetDisks {
};
let mut errs = vec![Some(DiskError::Unexpected); disks.len()];
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let disk_count = disks.len();
let fanout_disks = Arc::new(disks.to_vec());
let fanout_file_infos = Arc::new(file_infos);
let fanout_fence_tokens =
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(
disks,
&fanout_file_infos,
&fanout_fence_tokens,
src_bucket.as_str(),
dst_bucket.as_str(),
dst_object.as_str(),
);
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
Self::record_rename_batch_candidates(disks, &fanout_file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let fanout_paths = paths.clone();
let fanout_publication_scope = scanner_publication_commit_scope.clone();
let logical_guards = multipart_commit_owner;
let multipart_commit_owner = logical_guards
@@ -5278,13 +5383,16 @@ impl SetDisks {
// fan-out owner, even if the caller future is cancelled.
let _fanout_publication_scope = fanout_publication_scope;
let _namespace_commit_guard = fanout_namespace_commit_guard.clone();
let paths = RenameSlotPaths {
src_bucket: fanout_src_bucket,
src_object: fanout_src_object,
dst_bucket: fanout_dst_bucket,
dst_object: fanout_dst_object.clone(),
};
let allow_batch = !protected_multipart && scanner_publication_commit_scope.is_none();
let (dispatch_deadline_tx, dispatch_deadline) = if bound_dispatch_after_quorum
&& fanout_disks.iter().flatten().count() > write_quorum
&& fanout_disks.iter().flatten().any(|disk| !disk.is_local())
{
let (tx, rx) = watch::channel(None);
(Some(tx), Some(rx))
} else {
(None, None)
};
let RenameOutcomeProducers {
outcomes: mut outcome_rx,
mut tasks,
@@ -5292,19 +5400,29 @@ impl SetDisks {
disks: fanout_disks,
file_infos: fanout_file_infos.clone(),
fence_tokens: fanout_fence_tokens,
paths,
paths: fanout_paths.clone(),
namespace_owner: fanout_namespace_owner,
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline,
});
let mut results = Vec::with_capacity(disk_count);
let mut successful = 0;
while let Some(outcome) = outcome_rx.recv().await {
if let Some(tx) = dispatch_deadline_tx.as_ref()
&& matches!(&outcome.completion, Ok(Ok(_)))
{
successful += 1;
if successful == write_quorum {
tx.send_replace(Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_DISPATCH_GRACE));
}
}
results.push(outcome);
}
while tasks.join_next().await.is_some() {}
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
(results, fanout_file_infos)
};
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
@@ -5338,7 +5456,7 @@ impl SetDisks {
let (results, file_infos) = match fanout_result {
Ok(result) => result,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), rollback_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), rollback_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5471,7 +5589,7 @@ impl SetDisks {
// Destination-only Undo cannot restore a consumed MPU head.
// Only this failed owner can spend the original native caps.
owner
.failed_owned(disks, &file_infos, &src_object, (&dst_bucket, &dst_object), namespace_commit_guard)
.failed_owned(disks, &file_infos, src_object, (dst_bucket, dst_object), namespace_commit_guard)
.await;
} else {
rollback_failed_rename(
@@ -5480,7 +5598,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&dst_bucket, &dst_object),
(dst_bucket, dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5526,11 +5644,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = dst_bucket.clone();
let dst_object = dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -10003,6 +10120,228 @@ mod tests {
assert_eq!(recorder.histogram_sample_count("rustfs_io_get_object_local_batch_prepare_seconds"), 8);
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn in_flight_read_budget_falls_back_to_streaming_and_reclaims_on_drop() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("in-flight read budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("4096")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
assert_eq!(budget.in_flight_bytes(), 0, "budget must start clean");
let bucket = "in-flight-read-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let payload = vec![0x5a_u8; 4096];
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from(payload.clone()))
.await
.expect("write shard fixture");
}
// First read consumes the 4096-byte data shard via batch pread
// (parity shard stays deferred), filling the exact 4096-byte budget.
let first = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
first.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"first read under budget must keep the batch pread InMemory fast path"
);
assert_eq!(
budget.in_flight_bytes(),
4096,
"unread in-memory shard reader must charge the process-wide budget"
);
// Second concurrent unread read exceeds budget -> must fall back to streaming
// without overshooting the budget and still return intact shard bytes.
let mut second = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 4096, "exhausted budget must never overshoot");
assert!(
second
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"concurrent read when budget is exhausted must fall back to streaming readers"
);
let mut streamed = vec![0u8; payload.len()];
let read_n = second.readers[0]
.as_mut()
.expect("streaming reader must be present")
.read(&mut streamed)
.await
.expect("fallback streaming reader must serve exact bytes");
assert_eq!(read_n, payload.len());
assert_eq!(streamed, payload);
drop(second);
// Dropping/cancelling the unread first reader must immediately reclaim all bytes.
drop(first);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping unread readers must immediately release reserved budget"
);
// After reclamation, subsequent reads resume the InMemory batch fast path.
let third = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
third.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"after drop reclamation, batch pread fast path must be re-admitted"
);
assert_eq!(budget.in_flight_bytes(), 4096);
drop(third);
assert_eq!(budget.in_flight_bytes(), 0);
},
));
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn zero_in_flight_read_budget_forces_streaming_fallback() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("zero budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
let bucket = "zero-in-flight-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"abcd"))
.await
.expect("write shard fixture");
}
let setup = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
setup
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"zero in-flight budget must force streaming readers"
);
},
));
}
async fn reopen_local_disk(dir: &TempDir) -> DiskStore {
let endpoint =
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
@@ -12818,6 +13157,66 @@ mod tests {
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_bounds_cold_connect_after_durable_quorum() {
const DISKS: usize = 4;
let bucket = "rename-connect-tail-bucket";
let object = "rename-connect-tail-object";
let (dirs, mut disks) = call_counter_local_disks(bucket, DISKS).await;
prepare_rename_source_dirs(&dirs, &disks, "source").await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind cold peer");
// The TCP socket remains open, but there is no TLS server to finish the dial.
let endpoint = crate::disk::endpoint::Endpoint {
url: url::Url::parse(&format!("https://{}/data/rustfs0", listener.local_addr().expect("cold peer address")))
.expect("cold peer URL"),
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx: 3,
};
disks[DISKS - 1] = Some(
crate::disk::new_disk(
&endpoint,
&crate::disk::DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("construct remote disk"),
);
let file_infos = rename_commit_fileinfos(object, DISKS, "bounded-connect-etag");
let commit = temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CONNECT_TIMEOUT_SECS, Some("15"))], async {
tokio::time::timeout(
Duration::from_secs(5),
SetDisks::rename_data_owned_with_fence(
&disks,
(RUSTFS_META_TMP_BUCKET, "source"),
file_infos,
(bucket, object),
false,
RenameDataFenceOptions::new(3, None).with_quorum_bounded_dispatch(true),
),
)
.await
.expect("durable quorum must finish before the silent peer's dial deadline")
.expect("three durable renames must satisfy write quorum")
})
.await;
assert_eq!(commit.convergence, RenameConvergence::PartialCommit);
assert!(commit.needs_immediate_heal());
assert!(commit.tail_drain.is_none());
for dir in dirs.iter().take(3) {
let reopened = reopen_local_disk(dir).await;
let stored = reopened
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("quorum metadata survives reopening");
assert_eq!(stored.metadata.get("etag").map(String::as_str), Some("bounded-connect-etag"));
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_without_tail_handoff_waits_after_write_quorum() {
+1
View File
@@ -21,3 +21,4 @@ pub(crate) mod io_primitives;
pub(in crate::set_disk) mod metadata_quorum;
pub(in crate::set_disk) mod metadata_read;
pub(in crate::set_disk) mod multipart_source;
pub(crate) mod read_budget;
@@ -0,0 +1,380 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Process-wide RAII byte budget for buffered local shard reads.
//!
//! Local batch positioned reads (`batch_shard_pread`) and mmap-copy shard reads
//! materialize full shard ranges in memory before returning a `ShardReader`.
//! Without a process-wide ceiling, concurrent unread or slow-consumed
//! `GetObject` responses can pin unbounded heap memory across requests.
//!
//! Callers reserve bytes *before* allocating shard buffers and bind the
//! resulting [`ReadMemoryPermit`] to the returned [`Bytes`] via
//! [`Bytes::from_owner`]. Dropping or cancelling the reader (and its last slice)
//! frees the buffer first and immediately returns the reserved bytes to the
//! budget. When the budget cannot admit a request, callers fall back to the
//! streaming reader path.
use bytes::Bytes;
use rustfs_config::{DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
/// Process-wide in-flight byte budget shared by buffered local shard reads.
static GLOBAL_IN_FLIGHT_READ_BUDGET: OnceLock<Arc<InFlightReadBudget>> = OnceLock::new();
const IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG: &str = "in-flight read memory budget exhausted";
/// Sentinel error returned by `LocalDisk::read_file_mmap_copy_with_metrics`
/// when the process-wide in-flight read memory budget cannot admit a read.
pub(crate) fn in_flight_read_budget_exhausted_error() -> crate::disk::error::DiskError {
crate::disk::error::DiskError::Io(std::io::Error::new(std::io::ErrorKind::WouldBlock, IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG))
}
/// Returns `true` when `err` is the in-flight read memory budget exhaustion
/// sentinel produced by [`in_flight_read_budget_exhausted_error`].
pub(crate) fn is_in_flight_read_budget_exhausted(err: &crate::disk::error::DiskError) -> bool {
matches!(
err,
crate::disk::error::DiskError::Io(io_err)
if io_err.kind() == std::io::ErrorKind::WouldBlock
&& io_err.to_string() == IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG
)
}
/// Configured process-wide in-flight read byte limit.
///
/// Cached via `OnceLock` in non-test builds to keep the hot read path free of
/// process-global environment locks; read directly in test builds so `temp_env`
/// overrides take effect immediately.
pub(crate) fn object_mmap_read_max_inflight_bytes() -> usize {
#[cfg(test)]
{
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
}
#[cfg(not(test))]
{
static CACHED: OnceLock<usize> = OnceLock::new();
*CACHED.get_or_init(|| {
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
})
}
}
/// Returns the process-wide in-flight read memory budget.
pub(crate) fn global_in_flight_read_budget() -> &'static Arc<InFlightReadBudget> {
GLOBAL_IN_FLIGHT_READ_BUDGET.get_or_init(|| Arc::new(InFlightReadBudget::new_global()))
}
/// Lock-free byte budget tracking in-flight buffered shard allocations.
#[derive(Debug)]
pub(crate) struct InFlightReadBudget {
in_flight_bytes: AtomicUsize,
limit_override: Option<usize>,
}
impl InFlightReadBudget {
fn new_global() -> Self {
Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: None,
}
}
/// Create an isolated budget with an explicit fixed limit (used by unit tests).
#[cfg(test)]
pub(crate) fn with_limit(limit: usize) -> Arc<Self> {
Arc::new(Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: Some(limit),
})
}
/// Current configured byte ceiling.
pub(crate) fn limit(&self) -> usize {
self.limit_override.unwrap_or_else(object_mmap_read_max_inflight_bytes)
}
/// Currently reserved in-flight bytes.
#[cfg(test)]
pub(crate) fn in_flight_bytes(&self) -> usize {
self.in_flight_bytes.load(Ordering::Acquire)
}
/// Attempt to reserve `bytes` from this budget without blocking.
///
/// Returns `None` when the configured limit is `0` (buffered reads disabled)
/// or when admitting `bytes` would overflow or exceed the current limit.
pub(crate) fn try_reserve(self: &Arc<Self>, bytes: usize) -> Option<ReadMemoryPermit> {
let limit = self.limit();
if limit == 0 || bytes > limit {
return None;
}
if bytes == 0 {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes: 0,
});
}
let mut current = self.in_flight_bytes.load(Ordering::Acquire);
loop {
let next = current.checked_add(bytes)?;
if next > limit {
return None;
}
match self
.in_flight_bytes
.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes,
});
}
Err(observed) => current = observed,
}
}
}
/// Atomically reserve every shard length in `sizes` as an all-or-nothing
/// batch, returning one independently droppable permit per entry.
pub(crate) fn try_reserve_batch(self: &Arc<Self>, sizes: &[usize]) -> Option<Vec<ReadMemoryPermit>> {
let total = sizes.iter().try_fold(0usize, |acc, &size| acc.checked_add(size))?;
let mut batch_permit = self.try_reserve(total)?;
let mut permits = Vec::with_capacity(sizes.len());
for &size in sizes {
permits.push(batch_permit.split(size)?);
}
debug_assert_eq!(batch_permit.bytes, 0, "batch permit must be fully partitioned");
Some(permits)
}
}
/// RAII reservation of in-flight shard read bytes.
///
/// Dropping this permit immediately returns its reserved bytes to the owning
/// [`InFlightReadBudget`].
#[derive(Debug)]
pub(crate) struct ReadMemoryPermit {
budget: Arc<InFlightReadBudget>,
bytes: usize,
}
impl ReadMemoryPermit {
/// Bytes reserved by this permit.
#[cfg(test)]
pub(crate) fn bytes(&self) -> usize {
self.bytes
}
/// Carve `amount` bytes off this permit into a child permit while conserving
/// the total reserved byte count across parent and child.
fn split(&mut self, amount: usize) -> Option<Self> {
let remaining = self.bytes.checked_sub(amount)?;
self.bytes = remaining;
Some(Self {
budget: Arc::clone(&self.budget),
bytes: amount,
})
}
/// Bind this permit to an owned `Vec<u8>` buffer via [`Bytes::from_owner`].
///
/// If the buffer is empty, the permit is released immediately and an empty
/// `Bytes` is returned. Otherwise the permit remains held until the last
/// `Bytes` slice referencing the allocation is dropped, freeing the backing
/// buffer before refunding the budget.
pub(crate) fn wrap_vec(self, data: Vec<u8>) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
/// Bind this permit to an already-constructed [`Bytes`] via
/// [`Bytes::from_owner`].
pub(crate) fn wrap_bytes(self, data: Bytes) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
}
impl Drop for ReadMemoryPermit {
fn drop(&mut self) {
if self.bytes > 0 {
let prev = self.budget.in_flight_bytes.fetch_sub(self.bytes, Ordering::AcqRel);
debug_assert!(prev >= self.bytes, "in-flight read budget underflow");
}
}
}
/// Owner wrapper passed to [`Bytes::from_owner`].
///
/// Field declaration order is significant: `data` is dropped first so heap
/// memory is released before `_permit` refunds the global budget.
struct BudgetedOwner<T> {
data: T,
_permit: ReadMemoryPermit,
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for BudgetedOwner<T> {
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Barrier;
#[test]
fn budget_reserves_enforces_cap_and_reclaims_on_drop() {
let budget = InFlightReadBudget::with_limit(1024);
assert_eq!(budget.in_flight_bytes(), 0);
let p1 = budget.try_reserve(600).expect("first reservation under cap");
assert_eq!(p1.bytes(), 600);
assert_eq!(budget.in_flight_bytes(), 600);
assert!(
budget.try_reserve(500).is_none(),
"reservation exceeding remaining capacity must fail without overshoot"
);
assert_eq!(budget.in_flight_bytes(), 600);
let p2 = budget.try_reserve(424).expect("exact remaining capacity must succeed");
assert_eq!(budget.in_flight_bytes(), 1024);
assert!(budget.try_reserve(1).is_none());
drop(p1);
assert_eq!(budget.in_flight_bytes(), 424);
drop(p2);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn zero_limit_disables_all_reservations_including_empty() {
let budget = InFlightReadBudget::with_limit(0);
assert!(budget.try_reserve(0).is_none());
assert!(budget.try_reserve(1).is_none());
assert!(budget.try_reserve_batch(&[0, 0]).is_none());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn batch_reservation_is_atomic_and_splits_independently() {
let budget = InFlightReadBudget::with_limit(100);
assert!(
budget.try_reserve_batch(&[40, 40, 40]).is_none(),
"all-or-nothing batch over limit must leave budget untouched"
);
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
budget.try_reserve_batch(&[usize::MAX, 1]).is_none(),
"overflowing batch sum must be rejected safely"
);
assert_eq!(budget.in_flight_bytes(), 0);
let mut permits = budget.try_reserve_batch(&[30, 50, 20]).expect("exact batch fits");
assert_eq!(budget.in_flight_bytes(), 100);
assert_eq!(permits.len(), 3);
let last = permits.pop().expect("third permit");
drop(last);
assert_eq!(budget.in_flight_bytes(), 80);
drop(permits);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn bytes_owner_holds_permit_across_slices_and_releases_on_last_drop() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(64).expect("reserve 64 bytes");
let bytes = permit.wrap_vec(vec![0xAB; 64]);
assert_eq!(budget.in_flight_bytes(), 64);
let slice = bytes.slice(8..16);
drop(bytes);
assert_eq!(
budget.in_flight_bytes(),
64,
"permit must stay held while a non-empty slice pins the backing allocation"
);
assert_eq!(slice.as_ref(), &[0xAB; 8]);
drop(slice);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping the final slice must release the full reservation immediately"
);
}
#[test]
fn empty_buffer_releases_permit_immediately() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(16).expect("reserve");
let bytes = permit.wrap_vec(Vec::new());
assert!(bytes.is_empty());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn concurrent_reservations_never_exceed_limit_or_leak() {
const LIMIT: usize = 4096;
const THREADS: usize = 8;
const CHUNK: usize = 256;
let budget = InFlightReadBudget::with_limit(LIMIT);
let barrier = Arc::new(Barrier::new(THREADS));
let mut handles = Vec::with_capacity(THREADS);
for _ in 0..THREADS {
let budget = Arc::clone(&budget);
let barrier = Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
barrier.wait();
let mut held = Vec::new();
for _ in 0..200 {
if let Some(permit) = budget.try_reserve(CHUNK) {
assert!(
budget.in_flight_bytes() <= LIMIT,
"in-flight bytes must never overshoot the configured limit"
);
held.push(permit.wrap_vec(vec![1u8; CHUNK]));
} else {
held.pop();
}
}
drop(held);
}));
}
for handle in handles {
handle.join().expect("worker thread must not panic");
}
assert_eq!(budget.in_flight_bytes(), 0, "all reservations must be reclaimed");
}
}
+36
View File
@@ -917,6 +917,7 @@ mod core;
pub(crate) use core::io_primitives::disk_call_counters;
#[cfg(test)]
pub(crate) use core::io_primitives::{ENV_RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE, rename_fanout_barrier};
pub(crate) use core::read_budget;
mod ctx;
mod metadata;
mod ops;
@@ -7207,6 +7208,41 @@ impl SetDisks {
.any(|copy| FileMeta::load(&copy.buf).is_ok_and(|meta| meta.find_version(Some(version_id)).is_ok()))
}
/// Whether a write quorum of this set's drives hold `version_id` of the
/// key as the committed copy in `data_dir`. An object read answers from
/// read quorum, which on a data = parity set is one drive loss away from
/// unreadable; a data-movement caller that removes the source on this
/// answer needs the drives a new copy would have been written to. Every
/// drive is asked in one fanout, and a drive counts only for the shard
/// its own slot is assigned.
pub(crate) async fn holds_version_on_write_quorum(
&self,
bucket: &str,
object: &str,
version_id: Uuid,
data_dir: Option<Uuid>,
) -> Result<bool> {
let disks = self.disk_inventory().await;
let (copies, _) =
Self::read_all_fileinfo(&disks, "", bucket, object, &version_id.to_string(), false, false, false).await?;
let mut holders: HashMap<[u8; 32], (usize, usize)> = HashMap::new();
for (slot, copy) in copies.iter().enumerate() {
if !file_info_is_valid_for_metadata(copy)
|| copy.deleted
|| copy.version_id.unwrap_or_else(Uuid::nil) != version_id
|| copy.data_dir != data_dir
|| !copy.has_valid_erasure_geometry()
|| copy.erasure.distribution.len() != copies.len()
|| copy.erasure.distribution.get(slot) != Some(&copy.erasure.index)
{
continue;
}
let required = copy.write_quorum(self.default_write_quorum());
holders.entry(Self::file_info_quorum_hash(copy)).or_insert((0, required)).0 += 1;
}
Ok(holders.into_values().any(|(drives, required)| drives >= required))
}
/// Publish an internal tier free-version record without changing its
/// delete-marker shape or remote-tier identity. The caller holds the
/// source and target object locks; a write quorum is required before the
+98 -26
View File
@@ -25,7 +25,8 @@ use super::super::{
reduce_write_quorum_errs,
};
use crate::api::bucket::metadata_sys;
use crate::disk::DiskAPI;
use crate::disk::{DiskAPI, DiskStore, VolumeInfo};
use futures::{Stream, StreamExt, stream::FuturesUnordered};
#[derive(Clone, Copy)]
pub(crate) enum BucketInfoQuorum {
@@ -34,6 +35,39 @@ pub(crate) enum BucketInfoQuorum {
HealCandidates,
}
async fn stat_bucket_volume(disk: Option<DiskStore>, bucket: &str) -> crate::disk::error::Result<VolumeInfo> {
match disk {
Some(disk) => disk.stat_volume(bucket).await,
None => Err(DiskError::DiskNotFound),
}
}
async fn collect_bucket_presence(
mut probes: impl Stream<Item = crate::disk::error::Result<()>> + Unpin,
disk_count: usize,
) -> Result<()> {
let required = disk_count.div_ceil(2).max(1);
let mut successes = 0;
let mut errors = Vec::new();
while let Some(result) = probes.next().await {
match result {
Ok(()) => {
successes += 1;
// The reducer favors success on ties, so the remaining disks
// cannot change this decision. Presence doesn't use timestamps.
if successes == required {
return Ok(());
}
}
Err(err) => errors.push(Some(err)),
}
}
errors.resize_with(errors.len() + successes, || None);
Err(reduce_read_quorum_errs(&errors, BUCKET_OP_IGNORED_ERRS, required)
.unwrap_or(DiskError::ErasureReadQuorum)
.into())
}
impl SetDisks {
/// Require proof from every configured disk before retiring a bucket
/// generation whose visible volume was removed outside the storage API.
@@ -43,12 +77,9 @@ impl SetDisks {
return Err(Error::ErasureReadQuorum);
}
let futures = disks.into_iter().map(|disk| async move {
match disk {
Some(disk) => disk.stat_volume(bucket).await.map(|_| ()),
None => Err(DiskError::DiskNotFound),
}
});
let futures = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) });
let results = join_all(futures).await;
let mut volume_present = false;
let mut first_unknown = None;
@@ -70,31 +101,32 @@ impl SetDisks {
Ok(())
}
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let probes = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) })
.collect::<FuturesUnordered<_>>();
collect_bucket_presence(probes, disk_count).await
}
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let mut futures = Vec::with_capacity(disk_count);
for disk in disks {
let bucket = bucket.to_string();
futures.push(async move {
match disk {
Some(disk) => disk.stat_volume(&bucket).await,
None => Err(DiskError::DiskNotFound),
}
});
}
let results = join_all(futures).await;
let mut infos = Vec::with_capacity(results.len());
let probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
let results = join_all(probes).await;
let mut first_info = None;
let mut errs = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(info) => {
infos.push(Some(info));
if first_info.is_none() {
first_info = Some(info);
}
errs.push(None);
}
Err(err) => {
infos.push(None);
errs.push(Some(err));
}
}
@@ -113,10 +145,7 @@ impl SetDisks {
return Err(err.into());
}
infos
.into_iter()
.flatten()
.next()
first_info
.map(|info| BucketInfo {
name: info.name,
created: info.created,
@@ -341,3 +370,46 @@ impl BucketOperations for SetDisks {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{FutureExt, stream};
#[test]
fn bucket_presence_returns_with_a_silent_peer() {
let probes = stream::iter([Err(DiskError::VolumeNotFound), Ok(()), Ok(())]).chain(stream::pending());
collect_bucket_presence(probes, 4)
.now_or_never()
.expect("read quorum must return before the fourth probe replies")
.expect("two successes win even if both other disks report a missing volume");
}
#[tokio::test]
async fn bucket_presence_preserves_absence_and_read_quorum_errors() {
let probes = stream::iter([Ok(()), Err(DiskError::VolumeNotFound), Err(DiskError::DiskNotFound)]);
assert!(
collect_bucket_presence(probes.chain(stream::pending()), 4)
.now_or_never()
.is_none(),
"the last disk can still prove either presence or absence"
);
let missing = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::VolumeNotFound),
]);
assert!(matches!(collect_bucket_presence(missing, 4).await, Err(Error::VolumeNotFound)));
let unavailable = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::DiskNotFound),
]);
assert!(matches!(collect_bucket_presence(unavailable, 4).await, Err(Error::ErasureReadQuorum)));
}
}
@@ -128,6 +128,8 @@ pub(crate) struct DeleteRecoverySummary {
/// Groups blocked by a `LegacyAmbiguous` residue. Unlike other blocks this
/// is deterministic: the residue cannot be classified by retrying.
pub legacy_ambiguous: usize,
/// First committed transaction with a confirmed live generation conflict.
pub conflicting_transaction: Option<Uuid>,
pub pending: usize,
pub failed: usize,
pub reclaimed: usize,
@@ -145,6 +147,8 @@ pub(crate) struct DeleteRecoveryContext<'a> {
pub work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
pub dry_run: bool,
pub explicit_delete: bool,
/// A heal can report a blocked group. Foreground deletes retain the settlement error.
pub classify_generation_conflicts: bool,
/// Only the locked heal path may repair a live marker-creation source.
pub repair_marker_source: bool,
pub namespace_owner: Option<Arc<dyn Send + Sync>>,
@@ -161,6 +165,7 @@ impl<'a> DeleteRecoveryContext<'a> {
work_budget: None,
dry_run: false,
explicit_delete: false,
classify_generation_conflicts: false,
repair_marker_source: false,
namespace_owner: None,
transaction_guard: None,
@@ -178,16 +183,28 @@ impl DeleteRecoverySummary {
self.rolled_back += other.rolled_back;
self.blocked += other.blocked;
self.legacy_ambiguous += other.legacy_ambiguous;
self.conflicting_transaction = self.conflicting_transaction.or(other.conflicting_transaction);
self.pending += other.pending;
self.failed += other.failed;
self.reclaimed += other.reclaimed;
}
/// The error a heal must return when recovery left this key unresolved.
/// An ambiguous legacy residue is permanent and gets its own error; other
/// pending or blocked groups remain the retryable `SlowDown`.
pub(crate) fn unresolved_heal_error(&self) -> Option<StorageError> {
if self.legacy_ambiguous > 0 {
pub(crate) fn generation_conflict_error(&self, bucket: &str, object: &str) -> Option<StorageError> {
self.conflicting_transaction
.map(|transaction| StorageError::DeleteRecoveryGenerationConflict {
bucket: bucket.to_owned(),
object: rustfs_utils::path::decode_dir_object(object),
transaction,
})
}
/// The error an exact-key heal must return when recovery left it unresolved.
pub(crate) fn unresolved_heal_error(&self, bucket: &str, object: &str) -> Option<StorageError> {
if self.pending == 0
&& let Some(error) = self.generation_conflict_error(bucket, object)
{
Some(error)
} else if self.legacy_ambiguous > 0 {
Some(StorageError::DeleteRecoveryLegacyAmbiguous)
} else if self.pending > 0 || self.blocked > 0 {
Some(StorageError::SlowDown)
@@ -241,6 +258,30 @@ fn receipt(state: DeleteRecoveryState) -> bool {
matches!(state, DeleteRecoveryState::QuorumCommitted | DeleteRecoveryState::CommitFinished)
}
fn has_conflicting_null_generation(copies: &[DeleteRecoveryInspection], authority: &DeleteRecoveryJournal) -> bool {
if authority.requests.is_empty() || !authority.deleted_versions.contains(&Uuid::nil()) {
return false;
}
let null_generation = |version: &&DeleteRecoveryVersionIdentity| version.version_id.is_none_or(|id| id.is_nil());
let Some(source) = authority.original_versions.iter().find(null_generation) else {
return false;
};
copies.iter().any(|copy| {
copy.state == DeleteRecoveryState::Absent
&& copy.current_digest.is_some()
&& copy
.current_versions
.iter()
.find(null_generation)
.is_some_and(|live| live != source)
&& copies.iter().filter(|peer| receipt(peer.state)).all(|peer| {
peer.journal
.as_ref()
.is_some_and(|journal| !journal.matches_adoption_source(&copy.current_versions))
})
})
}
fn validate(inspection: &DeleteRecoveryInspection, object: &str, transaction: Uuid) -> Result<()> {
if inspection.protocol_version != DELETE_RECOVERY_PROTOCOL_VERSION
|| inspection.id.object != object
@@ -861,6 +902,7 @@ impl SetDisks {
work_budget,
dry_run,
explicit_delete,
classify_generation_conflicts,
repair_marker_source,
namespace_owner,
published_hint,
@@ -1162,6 +1204,25 @@ impl SetDisks {
if can_finish {
let certified_same_transaction = authority.is_some();
let reference = authority.or(prepared).ok_or(DiskError::FileCorrupt)?;
if classify_generation_conflicts
&& !dry_run
&& certified_same_transaction
&& has_conflicting_null_generation(copies, reference)
{
// A stale settlement fingerprint alone is retryable. Confirm the same
// evidence on every participant under the key and transaction fences.
let fresh = inspect(&disks, bucket, object, transaction, work_budget.as_deref())
.await
.into_iter()
.collect::<Result<Vec<_>>>()?;
if !can_commit() || fresh != *copies {
return Err(DiskError::OutdatedXLMeta);
}
summary.blocked += 1;
summary.conflicting_transaction.get_or_insert(transaction);
unresolved = true;
continue;
}
if dry_run {
if copies.iter().any(|copy| {
if certified_same_transaction
@@ -1302,6 +1363,10 @@ impl SetDisks {
}
}
}
// A sibling settlement may have changed the live generation after inspection.
if mutated {
summary.conflicting_transaction = None;
}
if !unresolved && !dry_run {
// GC is a key-wide barrier: every predecessor must have settled
// before the last surviving commit witness can disappear.
@@ -1492,17 +1557,17 @@ mod tests {
// rustfs/rustfs#8608: a legacy residue is deterministic and must not be
// reported as request-rate pressure.
let resolved = DeleteRecoverySummary::default();
assert!(resolved.unresolved_heal_error().is_none());
assert!(resolved.unresolved_heal_error("bucket", "object").is_none());
let pending = DeleteRecoverySummary {
pending: 1,
..Default::default()
};
assert!(matches!(pending.unresolved_heal_error(), Some(StorageError::SlowDown)));
assert!(matches!(pending.unresolved_heal_error("bucket", "object"), Some(StorageError::SlowDown)));
let blocked = DeleteRecoverySummary {
blocked: 1,
..Default::default()
};
assert!(matches!(blocked.unresolved_heal_error(), Some(StorageError::SlowDown)));
assert!(matches!(blocked.unresolved_heal_error("bucket", "object"), Some(StorageError::SlowDown)));
let ambiguous = DeleteRecoverySummary {
blocked: 1,
legacy_ambiguous: 1,
@@ -1510,7 +1575,7 @@ mod tests {
..Default::default()
};
assert!(matches!(
ambiguous.unresolved_heal_error(),
ambiguous.unresolved_heal_error("bucket", "object"),
Some(StorageError::DeleteRecoveryLegacyAmbiguous)
));
let mut total = DeleteRecoverySummary::default();
+2 -1
View File
@@ -3765,6 +3765,7 @@ impl SetDisks {
crate::set_disk::DeleteRecoveryContext {
dry_run: opts.dry_run,
explicit_delete,
classify_generation_conflicts: true,
repair_marker_source: true,
transaction_guard: transaction_guard.clone(),
namespace_owner: (!opts.dry_run).then(|| {
@@ -3812,7 +3813,7 @@ impl SetDisks {
None,
));
}
if let Some(error) = recovery.unresolved_heal_error() {
if let Some(error) = recovery.unresolved_heal_error(bucket, object) {
return Err(error);
}
}
+262 -5
View File
@@ -580,6 +580,67 @@ impl Drop for CappedMultipartStagingGuard {
}
}
/// Interim local pre-commit RAII cleanup owner for staged multipart part
/// artifacts under `.rustfs.sys/tmp/<tmp_part>`.
///
/// Armed right before opening part writers and transferred/disarmed once commit
/// takes ownership. If a `put_object_part` future is dropped or cancelled
/// before commit handoff (for example on client disconnect), `Drop` runs after
/// the inner future's writers have already dropped (LIFO order) and schedules
/// prompt cleanup of `.rustfs.sys/tmp/<tmp_part>` instead of leaving orphans
/// until the 24h stale-tmp sweep.
struct PreCommitPartStagingCleanupGuard {
state: Option<(SetDisks, String)>,
}
impl PreCommitPartStagingCleanupGuard {
fn disarmed() -> Self {
Self { state: None }
}
fn arm(&mut self, set: SetDisks, tmp_part: String) {
self.state = Some((set, tmp_part));
}
fn disarm(&mut self) {
self.state = None;
}
fn take_for_transfer(&mut self) -> Option<(SetDisks, String)> {
self.state.take()
}
fn armed_target(&self) -> Option<(&SetDisks, &str)> {
self.state.as_ref().map(|(set, tmp)| (set, tmp.as_str()))
}
}
impl Drop for PreCommitPartStagingCleanupGuard {
fn drop(&mut self) {
let Some((set, tmp_part)) = self.state.take() else {
return;
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
// Yield once so any just-dropped local file writer handles finish
// unwinding before recursive staging deletion runs.
tokio::task::yield_now().await;
if let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await {
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "drop_cleanup_failed",
tmp_part = %tmp_part,
error = ?err,
"Set disk multipart staging drop cleanup failed"
);
}
});
}
}
}
fn capped_multipart_staging_semaphore(upload_id_path: &str) -> Arc<tokio::sync::Semaphore> {
CAPPED_MULTIPART_STAGING
.get_or_init(|| Mutex::new(HashMap::new()))
@@ -3383,6 +3444,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
let mut commit_owns_cleanup = false;
// Declared before the inner async block so LIFO drop order closes all
// opened part writers first before `Drop` schedules tmp reclamation.
let mut staging_cleanup = PreCommitPartStagingCleanupGuard::disarmed();
let result: Result<PartInfo> = async {
let erasure =
Arc::new(coding::Erasure::try_new(fi.erasure.data_blocks, fi.erasure.parity_blocks, fi.erasure.block_size)
@@ -3397,6 +3461,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.unwrap_or_else(|| erasure.shard_size());
let writer_setup_stage_start = rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now);
staging_cleanup.arm(self.clone(), tmp_part.clone());
let (mut writers, errors) = create_part_writers(
&shuffle_disks,
&tmp_part_path,
@@ -3635,6 +3700,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let commit_opts = opts.clone();
let commit_staged_quota_reservation = staged_quota_reservation.take();
commit_owns_cleanup = true;
// Transfer pre-commit cleanup ownership exactly once at commit handoff:
// - Detached commit runs to completion and owns tmp cleanup exclusively.
// - Inline commit (`!detach_commit_owner`) retains the guard only until
// `rename_part` begins so pre-rename cancellation still cleans tmp
// while post-rename/committed artifacts can never be touched.
let mut commit_staging_cleanup = if detach_commit_owner {
staging_cleanup.disarm();
PreCommitPartStagingCleanupGuard::disarmed()
} else {
let mut transferred = PreCommitPartStagingCleanupGuard::disarmed();
if let Some((set, tmp)) = staging_cleanup.take_for_transfer() {
transferred.arm(set, tmp);
}
transferred
};
// The body is already staged. Keep every commit guard through the
// prepare, publish, settlement/rollback and temporary cleanup I/O,
// even when the HTTP request stops awaiting this task.
@@ -3743,6 +3823,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
achieved: 0,
});
}
// Disarm before rename_part so a Drop guard can never race
// with rename or touch committed multipart staging.
commit_staging_cleanup.disarm();
let rename_started = rustfs_io_metrics::put_stage_timer();
let rename_result = commit_set
.rename_part(
@@ -3801,6 +3884,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
"failed to clean multipart commit staging"
);
}
// Disarm only after inline error cleanup completes so dropping
// mid-cleanup still triggers Drop-backed reclamation.
commit_staging_cleanup.disarm();
result
};
if detach_commit_owner {
@@ -3813,11 +3899,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
.await;
if !commit_owns_cleanup
&& result.is_err()
&& let Err(err) = self.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await
{
warn!(tmp_part = %tmp_part, error = ?err, "failed to cleanup multipart temporary data");
if !commit_owns_cleanup && result.is_err() {
if let Some((set, tmp)) = staging_cleanup.armed_target()
&& let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, tmp).await
{
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "cleanup_failed",
tmp_part = %tmp,
error = ?err,
"failed to cleanup multipart temporary data"
);
}
staging_cleanup.disarm();
}
result
@@ -9959,6 +10055,167 @@ mod tests {
);
}
#[tokio::test]
async fn cancelled_put_object_part_mid_upload_cleans_tmp_staging_via_drop_guard() {
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-mid-upload-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// Exceed the 1 MiB erasure block size so the streaming encoder writes
// the first full block to staged tmp shard files before stalling on the
// remaining body bytes.
let declared_size = 2 * 1024 * 1024;
let stalled_entered = Arc::new(tokio::sync::Notify::new());
let stalled_entered_clone = Arc::clone(&stalled_entered);
let stream = futures::stream::unfold(0u8, move |step| {
let stalled_entered = Arc::clone(&stalled_entered_clone);
async move {
match step {
0 => Some((Ok::<Bytes, std::io::Error>(Bytes::from(vec![0x33; 1024 * 1024])), 1)),
_ => {
stalled_entered.notify_one();
std::future::pending::<()>().await;
None
}
}
}
});
let input = tokio_util::io::StreamReader::new(Box::pin(stream));
let mut reader = PutObjReader::new(
HashReader::from_stream(input, declared_size, declared_size, None, None, false)
.expect("hash reader should be constructed"),
);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let put = tokio::spawn(async move {
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
tokio::time::timeout(Duration::from_secs(10), stalled_entered.notified())
.await
.expect("upload should open part writers and stall mid-stream");
tokio::time::timeout(Duration::from_secs(10), async {
while non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("in-flight upload must have created staged tmp artifacts before cancellation");
put.abort();
assert!(
put.await
.expect_err("aborted put_object_part task should be cancelled")
.is_cancelled()
);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("pre-commit Drop guard must promptly reclaim staged tmp artifacts on cancellation");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn cancelled_put_object_part_before_commit_cleans_tmp_and_committed_part_survives() {
use tokio::io::AsyncReadExt as _;
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-precommit-and-committed-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// 1. Cancel after full encode/writer-close but BEFORE commit_owns_cleanup handoff.
let precommit_barrier = MultipartCommitBarrier::install(bucket, object, MultipartCommitPause::PutPartBeforeLockAcquire);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let cancelled_put = tokio::spawn(async move {
let mut reader = PutObjReader::from_vec(vec![0x61; 8192]);
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
precommit_barrier.wait_until_paused().await;
assert!(
!non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"staged tmp part must exist while paused before commit lock"
);
cancelled_put.abort();
assert!(
cancelled_put
.await
.expect_err("cancelled pre-commit put should be aborted")
.is_cancelled()
);
drop(precommit_barrier);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("Drop guard must reclaim tmp staging cancelled before commit lock");
// 2. Upload part 1 to completion and verify Drop guard does NOT delete committed data.
let payload = vec![0x77; 8192];
let mut reader = PutObjReader::from_vec(payload.clone());
let part = set_disks
.put_object_part(bucket, object, &upload.upload_id, 1, &mut reader, &ObjectOptions::default())
.await
.expect("committed part upload should succeed");
assert!(
non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"successful commit must leave no tmp entries"
);
set_disks
.clone()
.complete_multipart_upload(
bucket,
object,
&upload.upload_id,
vec![CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.expect("completing multipart upload with committed part must succeed");
let mut object_reader = set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("completed object must remain readable");
let mut restored = Vec::new();
object_reader
.stream
.read_to_end(&mut restored)
.await
.expect("completed object must read intact");
assert_eq!(restored, payload, "Drop guard must never delete committed part data");
}
#[tokio::test]
async fn capped_staging_queue_does_not_poll_the_part_reader() {
use futures::StreamExt;
@@ -5927,6 +5927,14 @@ impl SetDisks {
|| commit_decommission_object_lock_guard.is_some()
|| commit_publication_guard.is_some();
let commit_write_completion = opts.write_completion;
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
&& commit_object_lock_guard.is_some()
&& !is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
&& !quota_mutation_fence
&& commit_scanner_publication_scope.is_none()
&& scanner_publication_lease_tokens.is_none();
let commit_allows_early_ack = write_context.allows_early_ack(commit_write_completion)
&& !(opts.data_movement && opts.has_decommission_capacity_reservation())
&& commit_owns_namespace_guard
@@ -6254,6 +6262,7 @@ impl SetDisks {
commit_scanner_publication_lease_tokens.as_ref(),
)
.with_publication_scope(commit_scanner_publication_scope.clone())
.with_quorum_bounded_dispatch(bound_rename_dispatch)
.with_rollback_receipt(commit_rollback_receipt.clone())
.with_namespace_commit_guard(
(!is_meta_bucketname(&commit_bucket))
+24 -14
View File
@@ -5035,27 +5035,37 @@ mod metadata_cache_tests {
disk.make_volume(bucket).await.expect("bucket volume should be created");
}
let mut reader = PutObjReader::from_vec(vec![7u8; 1024]);
set.put_object(bucket, object, &mut reader, &ObjectOptions::default())
.await
.expect("test object should be written");
// A quorum-acknowledged PUT can leave a rename running on a healthy
// disk. This test needs an error-free fanout to reach cache publication.
set.put_object(
bucket,
object,
&mut reader,
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("the fixture PUT should drain its commit fanout");
let barrier = MetadataCachePublishBarrier::install(bucket, object);
let stale_generation = set
.get_object_metadata_cache_generation(bucket, object)
.expect("metadata cache generation should be active");
let reader_set = Arc::clone(&set);
let read = tokio::spawn(async move {
reader_set
.get_object_fileinfo(bucket, object, &ObjectOptions::default(), true, false)
.await
});
barrier.wait_until_paused().await;
let opts = ObjectOptions::default();
let read = set.get_object_fileinfo(bucket, object, &opts, true, false);
tokio::pin!(read);
tokio::select! {
() = barrier.wait_until_paused() => {}
result = &mut read => match result {
Ok(_) => panic!("metadata read returned without reaching cache publication"),
Err(err) => panic!("metadata read failed before cache publication: {err}"),
},
}
set.invalidate_get_object_metadata_cache(bucket, object).await;
barrier.release();
let snapshot = read
.await
.expect("metadata read task should not panic")
.expect("metadata fanout should still return its selected FileInfo");
let snapshot = read.await.expect("metadata fanout should still return its selected FileInfo");
assert!(snapshot.owned.is_some());
assert!(snapshot.has_valid_representation());
+15 -33
View File
@@ -24,7 +24,7 @@ use crate::disk::{
};
use crate::error::is_err_bucket_not_found;
use crate::runtime::sources as runtime_sources;
use crate::set_disk::{BucketInfoQuorum, get_lock_acquire_timeout};
use crate::set_disk::{BucketInfoQuorum, SetDisks, get_lock_acquire_timeout};
use crate::storage_api_contracts::admin::DiskSetSelector;
use crate::storage_api_contracts::bucket::{BUCKET_LIFECYCLE_LOCK_OBJECT, SRBucketDeleteOp};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
@@ -1702,65 +1702,47 @@ impl ECStore {
#[instrument(skip(self))]
pub(crate) async fn get_bucket_info_from_sets(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Write)
self.probe_bucket_sets(|set| async move { set.get_bucket_info(bucket, opts).await })
.await
}
pub(crate) async fn get_bucket_info_from_sets_at_read_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
self.probe_bucket_sets(|set| async move { set.check_bucket_presence_at_read_quorum(bucket).await })
.await
}
async fn get_bucket_info_from_sets_with_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
quorum: BucketInfoQuorum,
) -> Result<BucketInfo> {
async fn probe_bucket_sets<T, F: Future<Output = Result<T>>>(&self, probe: impl Fn(Arc<SetDisks>) -> F) -> Result<T> {
// One host may participate in several pools after expansion. Resolve the
// namespace against each erasure set so disks from different pools can
// never be combined into one bucket quorum.
// Bucket validation is request-path IO. Keep the previous peer fanout's
// latency shape by probing every set concurrently; scanner listings use
// a separate bounded path below because they run continuously.
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| async move {
let result = match quorum {
BucketInfoQuorum::Read => set.stat_bucket_with_quorum(bucket, quorum).await,
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => set.get_bucket_info(bucket, opts).await,
};
(pool_index, set_index, result)
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| {
let result = probe(set);
async move { (pool_index, set_index, result.await) }
}))
.await;
scoped_results.sort_unstable_by_key(|(pool_index, set_index, _)| (*pool_index, *set_index));
let mut first_info = None;
let mut first_error = None;
let mut first_success = None;
for (_, _, result) in scoped_results {
match result {
Ok(info) if first_info.is_none() => first_info = Some(info),
Ok(value) if first_success.is_none() => first_success = Some(value),
Ok(_) => {}
Err(err) if is_err_strict_volume_not_found(&err) => {}
Err(err) if first_error.is_none() => first_error = Some(err),
Err(_) => {}
Err(err) => return Err(err),
}
}
if let Some(err) = first_error {
return Err(err);
}
first_info.ok_or(Error::VolumeNotFound)
first_success.ok_or(Error::VolumeNotFound)
}
#[instrument(skip(self))]
pub(super) async fn handle_get_bucket_info(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
let mut info = match self.get_bucket_info_from_sets(bucket, opts).await {
Ok(info) => info,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket, opts).await,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket).await,
Err(err) => return Err(err),
};
@@ -1775,14 +1757,14 @@ impl ECStore {
Ok(info)
}
async fn get_bucket_info_at_read_quorum(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
async fn get_bucket_info_at_read_quorum(&self, bucket: &str) -> Result<BucketInfo> {
// Lock order: bucket lifecycle -> internal metadata object read locks.
// Keep create/delete from changing the namespace while a read quorum
// confirms both physical presence and persisted bucket metadata.
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
await_bucket_namespace_operation(Some(&guard), bucket, "bucket read quorum validation", async {
let mut info = self
.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
.probe_bucket_sets(|set| async move { set.stat_bucket_with_quorum(bucket, BucketInfoQuorum::Read).await })
.await?;
let (metadata, persisted) = metadata_sys::get_config_from_disk_with_presence_in(&self.ctx, bucket).await?;
if !persisted {
@@ -809,6 +809,9 @@ async fn recover_hint(
let mut failures = RecoveryFailures::default();
match outcome {
Some(Ok(_)) => {}
// The receipts remain discoverable by the inventory sweep. A new foreground
// ticket can also recheck them after the operator changes the evidence.
Some(Err(crate::error::StorageError::DeleteRecoveryGenerationConflict { .. })) => failures.blocked = 1,
Some(Err(error)) => {
let (count, reason) = match error {
crate::error::StorageError::ErasureReadQuorum => (&mut failures.pending, FailureReason::MissingQuorum),
+4 -2
View File
@@ -421,6 +421,7 @@ impl ECStore {
let recovery_context = crate::set_disk::DeleteRecoveryContext {
dry_run: opts.dry_run,
explicit_delete,
classify_generation_conflicts: true,
namespace_owner: (!opts.dry_run)
.then(|| Arc::new((scope.clone(), store.ctx.begin_namespace_commit_for_bucket(&bucket))) as Arc<dyn Send + Sync>),
..crate::set_disk::DeleteRecoveryContext::new(Some(scope.incarnation), &can_commit)
@@ -457,6 +458,7 @@ impl ECStore {
state = "insufficient_evidence",
bucket = ?bucket,
object = ?decode_dir_object(object),
transaction = ?summary.conflicting_transaction,
pool = opts.pool,
set = opts.set,
legacy_ambiguous = summary.legacy_ambiguous,
@@ -467,8 +469,8 @@ impl ECStore {
if object.is_some() && summary.pending > 0 {
return Err(StorageError::ErasureReadQuorum);
}
if object.is_some() && !opts.dry_run && summary.blocked > 0 {
return Err(StorageError::SlowDown);
if let Some(object) = &object && !opts.dry_run && summary.blocked > 0 {
return Err(summary.generation_conflict_error(&bucket, object).unwrap_or(StorageError::SlowDown));
}
let delete_recovery = rustfs_madmin::heal_commands::DeleteRecoveryStatus {
pending: summary.pending,
+249 -12
View File
@@ -6451,8 +6451,14 @@ mod tests {
};
if let Some(split) = multipart_split {
assert!(split > 0 && split < body.len(), "multipart source split must create two non-empty parts");
// Upload initiation belongs to the current bucket generation. The
// historical object timestamp is assigned at completion.
let init_opts = ObjectOptions {
mod_time: None,
..write_opts.clone()
};
let upload = pool
.new_multipart_upload(bucket, object, &write_opts)
.new_multipart_upload(bucket, object, &init_opts)
.await
.expect("create physical data-movement source upload");
let mut completed_parts = Vec::with_capacity(2);
@@ -7609,7 +7615,7 @@ mod tests {
..versioned.clone()
};
let upload = store.pools[0]
.new_multipart_upload(&bucket, object, &native_opts)
.new_multipart_upload(&bucket, object, &versioned)
.await
.expect("real pool-zero Init");
let part = store.pools[0]
@@ -8445,6 +8451,133 @@ mod tests {
.expect("join data movement test thread");
}
/// Fails the migration if it reads the source body.
struct SourceBodyMustNotBeRead;
impl tokio::io::AsyncRead for SourceBodyMustNotBeRead {
fn poll_read(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
_buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Err(std::io::Error::other("the source body must not be read again")))
}
}
/// A rebalance that stops after the target commit and before the source
/// cleanup leaves the version in both pools. The next attempt must settle
/// on the committed copy instead of uploading every part again.
#[test]
#[serial_test::serial(storage_class_env)]
fn rebalance_multipart_retry_skips_the_copy_the_target_already_holds() {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()
.expect("build data movement test runtime");
runtime.block_on(async move {
let temp_dir = tempfile::tempdir().expect("create data movement store dir");
let (_ctx, store, _shutdown) = without_storage_class_env(build_isolated_test_store(
temp_dir.path(),
"data-movement-equivalent-target",
&[4, 4],
))
.await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("data-movement-equivalent-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create data movement bucket");
*store.rebalance_meta.write().await = Some(active_rebalance_meta_for_pool(store.pools.len(), 0));
assert!(store.is_pool_rebalancing(0).await);
let object = "multipart-object";
let version_id = Uuid::new_v4();
let first_part_size = 5 * 1024 * 1024;
let mut body = vec![b'a'; first_part_size];
body.push(b'b');
let source_reader = seed_data_movement_source_reader(
&store,
&bucket,
object,
DataMovementSourceSeed {
pool_idx: 0,
version_id: Some(version_id),
body,
multipart_split: Some(first_part_size),
mod_time: OffsetDateTime::UNIX_EPOCH + time::Duration::SECOND,
user_defined: HashMap::new(),
},
)
.await;
assert!(source_reader.object_info.is_multipart());
let committed = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
source_reader,
None,
"test_data_movement",
)
.await
.expect("the first attempt commits the target copy");
assert_eq!(committed, crate::data_movement::DataMovementCopy::Committed);
let read_opts = ObjectOptions {
versioned: true,
version_id: Some(version_id.to_string()),
include_part_checksums: true,
..Default::default()
};
let target = store.pools[1]
.get_object_info(&bucket, object, &read_opts)
.await
.expect("the target holds the committed copy");
// The run stopped here: the source is still on its pool.
let mut retry_reader = store.pools[0]
.get_object_reader(
&bucket,
object,
None,
HeaderMap::new(),
&ObjectOptions {
raw_data_movement_read: true,
..read_opts.clone()
},
)
.await
.expect("the source version is still present");
retry_reader.stream = Box::new(SourceBodyMustNotBeRead);
let retried = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
retry_reader,
None,
"test_data_movement",
)
.await
.expect("an equivalent target settles the retry without another copy");
assert_eq!(retried, crate::data_movement::DataMovementCopy::Committed);
let after = store.pools[1]
.get_object_info(&bucket, object, &read_opts)
.await
.expect("the committed copy is still on the target");
assert_eq!(after.data_dir, target.data_dir, "the retry must not rewrite the committed copy");
});
})
.expect("spawn data movement test thread")
.join()
.expect("join data movement test thread");
}
#[test]
#[serial_test::serial(storage_class_env)]
fn data_movement_multipart_replaces_only_unlocked_owned_generation() {
@@ -8801,9 +8934,9 @@ mod tests {
let retain_until = (OffsetDateTime::now_utc() + time::Duration::days(1))
.format(&time::format_description::well_known::Rfc3339)
.expect("retain-until date should format");
for (object, replacement_source, mode) in [
("compliance-target.bin", "compliance-target-replacement.bin", "COMPLIANCE"),
("governance-target.bin", "governance-target-replacement.bin", "GOVERNANCE"),
for (object, mode) in [
("compliance-target.bin", "COMPLIANCE"),
("governance-target.bin", "GOVERNANCE"),
] {
let retained_metadata = HashMap::from([
(rustfs_filemeta::metadata_keys::OBJECT_LOCK_MODE.to_string(), mode.to_string()),
@@ -8816,26 +8949,44 @@ mod tests {
store.clone(),
0,
bucket.clone(),
source_reader(object, old_body.clone(), old_time, retained_metadata.clone()).await,
source_reader(object, old_body.clone(), old_time, HashMap::new()).await,
None,
"test_retained_target_seed",
)
.await
.expect("seed retained migrated target");
let mut replacement_source_reader =
source_reader(replacement_source, new_body.clone(), new_time, retained_metadata).await;
replacement_source_reader.object_info.name = object.to_string();
.expect("seed migrated target");
// Model retention already present on the target independently of the source.
// Preserve the migration ownership markers so WORM is the rejecting check.
for disk in store.pools[1].disk_set[0].disk_inventory().await {
disk.expect("target disk should be online")
.update_metadata(
&bucket,
object,
rustfs_filemeta::FileInfo {
version_id: Some(version_id),
metadata: retained_metadata.clone(),
..Default::default()
},
&crate::disk::UpdateMetadataOpts::default(),
)
.await
.expect("seed retention on the exact target version");
}
let err = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
replacement_source_reader,
source_reader(object, new_body.clone(), new_time, HashMap::new()).await,
None,
"test_retained_target_replace",
)
.await
.expect_err("active retention must block stale target replacement");
assert!(err.to_string().contains("complete_multipart_upload"), "unexpected retention error: {err}");
assert!(
crate::data_movement::data_movement_error_is_stage(&err, "complete_multipart_upload")
&& err.to_string().contains("Prefix access is denied"),
"unexpected retention error: {err}"
);
let mut retained_reader = store.pools[1]
.get_object_reader(
@@ -22005,6 +22156,92 @@ mod tests {
assert_eq!(body, original_body);
}
#[tokio::test]
#[serial_test::serial]
async fn single_put_records_object_lock_snapshot_stages() {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rustfs_io_metrics::{
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ, PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK, put_stage_metrics_enabled, set_put_stage_metrics_enabled,
};
struct RestorePutStageFlag(bool);
impl Drop for RestorePutStageFlag {
fn drop(&mut self) {
set_put_stage_metrics_enabled(self.0);
}
}
let temp = tempfile::tempdir().expect("create snapshot test store dir");
let (ctx, store, _shutdown) =
without_storage_class_env(build_isolated_test_store(temp.path(), "put-snapshot-stages", &[4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = format!("snapshot-stages-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create snapshot bucket");
let opts = ObjectOptions {
expected_bucket_incarnation_id: Some(store.bucket_incarnation_id(&bucket).await.expect("load bucket incarnation")),
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
};
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let _recorder = metrics::set_default_local_recorder(&recorder);
let _flag = RestorePutStageFlag(put_stage_metrics_enabled());
let take_stage_counts = || {
let stages = [
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
];
let mut counts = [0; 3];
for (key, _, _, value) in snapshotter.snapshot().into_vec() {
let key = key.key();
if key.name() != "rustfs_s3_put_object_stage_duration_ms" {
continue;
}
if let Some(index) = stages
.iter()
.position(|stage| key.labels().any(|label| label.key() == "stage" && label.value() == *stage))
{
assert_eq!(key.labels().count(), 1, "snapshot timings must have only a static stage label");
let DebugValue::Histogram(samples) = value else {
panic!("snapshot timing must be recorded as a histogram");
};
counts[index] += samples.len();
}
}
counts
};
set_put_stage_metrics_enabled(false);
store
.put_object(&bucket, "metrics-off", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect("ordinary PUT with metrics disabled");
assert_eq!(take_stage_counts(), [0, 0, 0]);
set_put_stage_metrics_enabled(true);
store
.put_object(&bucket, "metrics-on", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect("ordinary PUT with metrics enabled");
assert_eq!(take_stage_counts(), [1, 1, 1]);
crate::bucket::metadata_sys::inject_object_lock_disk_read_error_in(&ctx, &bucket)
.await
.expect("inject authority read error");
let error = store
.put_object(&bucket, "read-failed", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect_err("authority failure must still reject the PUT");
assert!(error.to_string().contains("injected Object Lock metadata disk read failure"));
assert_eq!(take_stage_counts(), [1, 1, 1], "each stage records once even when the final read fails");
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial(storage_class_env)]
@@ -100,12 +100,15 @@ mod multipart_copy_heal_tests {
.collect::<Vec<_>>();
let options = ObjectOptions {
versioned: true,
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
write_completion: WriteCompletion::TailDrained,
..Default::default()
};
let init_opts = ObjectOptions {
mod_time: None,
..options.clone()
};
let upload = store.pools[0]
.new_multipart_upload(&bucket, &object, &options)
.new_multipart_upload(&bucket, &object, &init_opts)
.await
.expect("actual native C Init");
let part = store.pools[0]
@@ -130,7 +133,11 @@ mod multipart_copy_heal_tests {
etag: part.etag,
..Default::default()
}],
&options,
&ObjectOptions {
// Pin the committed timestamp without backdating the staged upload.
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
..options
},
)
.await
.expect("actual native C quorum publication");
+252 -142
View File
@@ -2110,8 +2110,22 @@ fn batch_delete_action_key(object: &ObjectToDelete) -> (&str, Option<Uuid>) {
(object.object_name.as_str(), object.version_id)
}
fn batch_delete_targets_pool(creates_latest_marker: bool, marker_target_pool_idx: Option<usize>, pool_idx: usize) -> bool {
!creates_latest_marker || marker_target_pool_idx == Some(pool_idx)
#[derive(Clone, Copy)]
enum BatchDeleteRoute {
Inactive,
AllPools,
PendingMarker,
Marker(usize),
}
impl BatchDeleteRoute {
fn targets(self, pool_idx: usize) -> bool {
match self {
Self::Inactive | Self::PendingMarker => false,
Self::AllPools => true,
Self::Marker(target) => target == pool_idx,
}
}
}
#[cfg(test)]
@@ -2197,52 +2211,33 @@ fn inject_batch_delete_pool_errors(
}
}
fn resolve_batch_delete_pool_results<'a>(
initial_error: Option<Error>,
pool_results: impl IntoIterator<Item = (&'a DeletedObject, &'a Option<Error>)>,
) -> (Option<DeletedObject>, Option<Error>, bool) {
let mut failure = initial_error.map(|err| (None, err));
let mut deleted = None;
let mut fallback: Option<(DeletedObject, Option<Error>)> = None;
let mut attempted = false;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum BatchDeleteOutcome {
SilentMiss,
Missing,
Deleted,
Failed,
}
for (pool_delete, pool_error) in pool_results {
attempted = true;
match pool_error {
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => {
if fallback.as_ref().is_none_or(|(_, error)| error.is_none()) {
fallback = Some(((*pool_delete).clone(), Some(err.clone())));
}
}
Some(err) => {
if failure.is_none() {
failure = Some((Some((*pool_delete).clone()), err.clone()));
}
}
None if pool_delete.found => {
if deleted.is_none() {
deleted = Some((*pool_delete).clone());
}
}
None => {
if fallback.is_none() {
fallback = Some(((*pool_delete).clone(), None));
}
}
}
fn apply_batch_delete_pool_result(
selected: &mut Option<BatchDeleteOutcome>,
deleted: &mut DeletedObject,
error: &mut Option<Error>,
pool_delete: DeletedObject,
pool_error: Option<Error>,
) {
let outcome = match &pool_error {
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => BatchDeleteOutcome::Missing,
Some(_) => BatchDeleteOutcome::Failed,
None if pool_delete.found => BatchDeleteOutcome::Deleted,
None => BatchDeleteOutcome::SilentMiss,
};
// Results arrive in pool order. Equal priorities keep the first result.
if selected.is_none_or(|current| outcome > current) {
*selected = Some(outcome);
*deleted = pool_delete;
*error = pool_error;
}
if let Some((failed_delete, err)) = failure {
return (failed_delete, Some(err), attempted);
}
if let Some(deleted) = deleted {
return (Some(deleted), None, attempted);
}
if let Some((deleted, err)) = fallback {
return (Some(deleted), err, attempted);
}
(None, None, attempted)
}
fn transition_restore_pool_opts(opts: &ObjectOptions) -> ObjectOptions {
@@ -2774,6 +2769,7 @@ async fn await_conditional_capability_set_probe_gate(bucket: &str) -> Result<()>
}
struct BatchDeletePhasePlan<'a> {
/// Unique input positions in request order.
indices: &'a [usize],
pool_generations: HashMap<usize, HashMap<String, CurrentDeleteGeneration>>,
marker_targets: &'a HashMap<String, usize>,
@@ -3308,15 +3304,34 @@ impl ECStore {
pub(crate) async fn object_lock_config_snapshot_for_single_put(&self, bucket: &str) -> Result<Arc<ObjectLockConfigSnapshot>> {
check_valid_bucket_name(bucket)?;
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
let lifecycle_lock_started = rustfs_io_metrics::put_stage_timer();
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
lifecycle_lock_started,
);
let lifecycle_guard = lifecycle_guard?;
let metadata_lock_started = rustfs_io_metrics::put_stage_timer();
let metadata_guard = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_read_lock_in_for_purpose(
&self.ctx,
bucket,
"object_lock_snapshot_metadata_read",
)
.await?;
let (state, bucket_incarnation_id, config_revision, quota_res) =
get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await?;
.await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
metadata_lock_started,
);
let metadata_guard = metadata_guard?;
let authority_read_started = rustfs_io_metrics::put_stage_timer();
let authority = get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
authority_read_started,
);
let (state, bucket_incarnation_id, config_revision, quota_res) = authority?;
if lifecycle_guard.is_lock_lost() || metadata_guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost while loading the Object Lock snapshot"));
}
@@ -6204,10 +6219,7 @@ impl ECStore {
mut pool_generations,
marker_targets: conditional_marker_targets,
} = plan;
let mut active = vec![false; objects.len()];
for idx in indices {
active[*idx] = true;
}
debug_assert!(indices.windows(2).all(|pair| pair[0] < pair[1]));
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
@@ -6215,46 +6227,55 @@ impl ECStore {
.delete_replication_config_snapshot
.as_deref()
.expect("batch delete replication config snapshot should be loaded");
let latest_marker_objects = objects
.iter()
.enumerate()
.map(|(idx, object)| {
active[idx] && del_errs[idx].is_none() && batch_delete_creates_latest_marker(object, delete_config_snapshot)
})
.collect::<Vec<_>>();
let marker_target_results = join_all(objects.iter().zip(&latest_marker_objects).map(|(object, creates_marker)| {
let admitted_target = conditional_marker_targets.get(&object.object_name).copied();
async move {
if *creates_marker {
// Routing is part of condition admission. A rebalance
// start cannot replace the validated current owner.
Some(match admitted_target {
Some(pool_idx) => Ok(pool_idx),
None => self.get_pool_idx_no_lock(bucket, &object.object_name, 0).await,
})
} else {
None
}
let mut routes = vec![BatchDeleteRoute::Inactive; objects.len()];
let mut has_markers = false;
let mut pending_markers = 0;
for &idx in indices {
let object = &objects[idx];
if !batch_delete_creates_latest_marker(object, delete_config_snapshot) {
routes[idx] = BatchDeleteRoute::AllPools;
continue;
}
}))
.await;
let mut marker_target_pool_indices = Vec::with_capacity(objects.len());
for (idx, target_result) in marker_target_results.into_iter().enumerate() {
match target_result {
Some(Ok(pool_idx)) => marker_target_pool_indices.push(Some(pool_idx)),
Some(Err(err)) => {
del_errs[idx] = Some(err);
marker_target_pool_indices.push(None);
}
None => marker_target_pool_indices.push(None),
has_markers = true;
// Rebalancing cannot replace the owner used to admit a conditional delete.
if let Some(&pool_idx) = conditional_marker_targets.get(&object.object_name) {
routes[idx] = BatchDeleteRoute::Marker(pool_idx);
} else {
routes[idx] = BatchDeleteRoute::PendingMarker;
pending_markers += 1;
}
}
if pending_markers != 0 {
let lookups = indices
.iter()
.copied()
.filter(|&idx| matches!(routes[idx], BatchDeleteRoute::PendingMarker))
// Bound join_all's size hint by the unresolved markers.
.take(pending_markers)
.map(|idx| async move { (idx, self.get_pool_idx_no_lock(bucket, &objects[idx].object_name, 0).await) });
let lookup_results = join_all(lookups).await;
for (idx, result) in lookup_results {
routes[idx] = match result {
Ok(pool_idx) => BatchDeleteRoute::Marker(pool_idx),
Err(err) => {
del_errs[idx] = Some(err);
BatchDeleteRoute::Inactive
}
};
}
}
let _capacity_fence = if !self.single_pool() && latest_marker_objects.iter().any(|creates_marker| *creates_marker) {
let _capacity_fence = if !self.single_pool() && has_markers {
// Only marker destinations can grow. Other pools participate in
// exact deletion under the same metadata read fence and must not
// be treated as publication targets merely because they retire.
let mut target_pool_indices = marker_target_pool_indices.iter().flatten().copied().collect::<Vec<_>>();
let mut target_pool_indices = indices
.iter()
.filter_map(|&idx| match routes[idx] {
BatchDeleteRoute::Marker(pool_idx) => Some(pool_idx),
_ => None,
})
.collect::<Vec<_>>();
target_pool_indices.sort_unstable();
target_pool_indices.dedup();
match self
@@ -6282,16 +6303,15 @@ impl ECStore {
continue;
}
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = objects
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = indices
.iter()
.enumerate()
.map(|&idx| (idx, &objects[idx]))
.filter(|(idx, object)| {
active[*idx] && del_errs[*idx].is_none()
routes[*idx].targets(pool.pool_idx)
// A newly rebalancing pool still owes every admitted
// conditional key its guarded mutation. Ordinary keys
// retain the existing rebalance skip behavior.
&& (!rebalancing || guarded_generations.is_some_and(|generations| generations.contains_key(&object.object_name)))
&& batch_delete_targets_pool(latest_marker_objects[*idx], marker_target_pool_indices[*idx], pool.pool_idx)
})
.map(|(idx, object)| (idx, object.clone()))
.unzip();
@@ -6319,20 +6339,23 @@ impl ECStore {
});
}
let results = join_all(futures).await;
for idx in 0..del_objects.len() {
let pool_results = results.iter().filter_map(|(object_indices, (dels, errs, _))| {
let pool_object_idx = object_indices.binary_search(&idx).ok()?;
Some((&dels[pool_object_idx], &errs[pool_object_idx]))
});
let (deleted, error, attempted) = resolve_batch_delete_pool_results(del_errs[idx].take(), pool_results);
if let Some(deleted) = deleted {
del_objects[idx] = deleted;
let mut selected: Vec<_> = del_errs
.iter()
.map(|error| error.as_ref().map(|_| BatchDeleteOutcome::Failed))
.collect();
for (object_indices, (pool_deleted, pool_errors, pool_accounting)) in join_all(futures).await {
debug_assert_eq!(object_indices.len(), pool_deleted.len());
debug_assert_eq!(object_indices.len(), pool_errors.len());
let mut pool_accounting = pool_accounting.into_iter();
for (idx, (deleted, error)) in object_indices.into_iter().zip(pool_deleted.into_iter().zip(pool_errors)) {
apply_batch_delete_pool_result(&mut selected[idx], &mut del_objects[idx], &mut del_errs[idx], deleted, error);
// Accounting follows the last pool that attempted this index.
accounting[idx] = pool_accounting.next().flatten();
}
del_errs[idx] = error;
}
if !attempted && del_errs[idx].is_none() && latest_marker_objects[idx] {
for &idx in indices {
if matches!(routes[idx], BatchDeleteRoute::Marker(_)) && selected[idx].is_none() {
del_objects[idx] = DeletedObject {
object_name: objects[idx].object_name.clone(),
version_id: objects[idx].version_id,
@@ -6342,12 +6365,6 @@ impl ECStore {
}
}
for (object_indices, (_, _, pool_accounting)) in &results {
for (pool_object_idx, object_idx) in object_indices.iter().enumerate() {
accounting[*object_idx] = pool_accounting.get(pool_object_idx).cloned().flatten();
}
}
(del_objects, del_errs, accounting)
}
@@ -6360,9 +6377,8 @@ impl ECStore {
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
// encode object name
let objects: Vec<ObjectToDelete> = objects
.iter()
.map(|v| {
let mut v = v.clone();
.into_iter()
.map(|mut v| {
v.object_name = encode_dir_object(v.object_name.as_str());
v
})
@@ -6595,7 +6611,7 @@ impl ECStore {
// the phase only runs for the keys this batch actually holds, and
// only its outcomes replace the outer per-key state.
let indices = (0..objects.len()).filter(|idx| del_errs[*idx].is_none()).collect::<Vec<_>>();
let (phase_deleted, mut phase_errors, mut phase_accounting) = self
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6608,7 +6624,7 @@ impl ECStore {
)
.await;
for idx in indices {
del_objects[idx] = phase_deleted[idx].clone();
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
@@ -6625,7 +6641,7 @@ impl ECStore {
}
}
if !conditional_indices.is_empty() {
let (deleted, mut errors, mut receipts) = self
let (mut deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6638,7 +6654,7 @@ impl ECStore {
)
.await;
for idx in &conditional_indices {
del_objects[*idx] = deleted[*idx].clone();
del_objects[*idx] = std::mem::take(&mut deleted[*idx]);
del_errs[*idx] = errors[*idx].take();
accounting[*idx] = receipts[*idx].take();
}
@@ -6671,7 +6687,7 @@ impl ECStore {
if !ordinary_indices.is_empty() {
// The guarded phase has finished all rollback/receipt work.
// These actions receive neither its CAS nor its transaction.
let (deleted, mut errors, mut receipts) = self
let (mut deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6684,7 +6700,7 @@ impl ECStore {
)
.await;
for idx in ordinary_indices {
del_objects[idx] = deleted[idx].clone();
del_objects[idx] = std::mem::take(&mut deleted[idx]);
del_errs[idx] = errors[idx].take();
accounting[idx] = receipts[idx].take();
}
@@ -9762,9 +9778,11 @@ mod tests {
..Default::default()
};
assert!(batch_delete_creates_latest_marker(&latest, &versioned));
assert!(!batch_delete_targets_pool(true, Some(1), 0));
assert!(batch_delete_targets_pool(true, Some(1), 1));
assert!(!batch_delete_targets_pool(true, Some(1), 2));
assert!(!BatchDeleteRoute::Marker(1).targets(0));
assert!(BatchDeleteRoute::Marker(1).targets(1));
assert!(!BatchDeleteRoute::Marker(1).targets(2));
assert!(!BatchDeleteRoute::Inactive.targets(0));
assert!(!BatchDeleteRoute::PendingMarker.targets(0));
let explicit = ObjectToDelete {
object_name: "explicit".to_string(),
@@ -9772,11 +9790,23 @@ mod tests {
..Default::default()
};
assert!(!batch_delete_creates_latest_marker(&explicit, &versioned));
assert!(batch_delete_targets_pool(false, Some(1), 0));
assert!(BatchDeleteRoute::AllPools.targets(0));
let unversioned = DeleteReplicationConfigSnapshot::default();
assert!(!batch_delete_creates_latest_marker(&latest, &unversioned));
assert!(batch_delete_targets_pool(false, None, 0));
assert!(BatchDeleteRoute::AllPools.targets(1));
}
fn reduce_test_pool_results(
mut error: Option<Error>,
pool_results: impl IntoIterator<Item = (DeletedObject, Option<Error>)>,
) -> (DeletedObject, Option<Error>, Option<BatchDeleteOutcome>) {
let mut selected = error.as_ref().map(|_| BatchDeleteOutcome::Failed);
let mut deleted = DeletedObject::default();
for (pool_delete, pool_error) in pool_results {
apply_batch_delete_pool_result(&mut selected, &mut deleted, &mut error, pool_delete, pool_error);
}
(deleted, error, selected)
}
#[test]
@@ -9802,15 +9832,14 @@ mod tests {
let failed = (DeletedObject::default(), Some(source_error.clone()));
let succeeded = (success.clone(), None);
let pool_results = if source_first {
vec![failed, succeeded]
[failed, succeeded]
} else {
vec![succeeded, failed]
[succeeded, failed]
};
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
let (_, error, selected) = reduce_test_pool_results(None, pool_results);
assert!(attempted);
assert!(matches!(selected, Some(BatchDeleteOutcome::Failed)));
assert_eq!(error, Some(source_error.clone()));
}
}
@@ -9833,34 +9862,54 @@ mod tests {
for missing_first in [true, false] {
let succeeded = (success.clone(), None);
let pool_results = if missing_first {
vec![missing.clone(), succeeded]
[missing.clone(), succeeded]
} else {
vec![succeeded, missing.clone()]
[succeeded, missing.clone()]
};
let (deleted, error, attempted) =
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
let (deleted, error, selected) = reduce_test_pool_results(None, pool_results);
assert!(attempted);
let deleted = deleted.expect("successful pool result should be retained");
assert!(matches!(selected, Some(BatchDeleteOutcome::Deleted)));
assert!(deleted.found);
assert_eq!(deleted.object_name, success.object_name.as_str());
assert!(error.is_none());
}
let missing_only = [missing];
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, missing_only.iter().map(|(deleted, error)| (deleted, error)));
assert!(attempted);
let (_, error, selected) = reduce_test_pool_results(None, [missing]);
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
assert_eq!(error, Some(missing_error));
}
let silent_missing = [(DeletedObject::default(), None)];
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, silent_missing.iter().map(|(deleted, error)| (deleted, error)));
assert!(attempted);
let (_, error, selected) = reduce_test_pool_results(None, [(DeletedObject::default(), None)]);
assert!(matches!(selected, Some(BatchDeleteOutcome::SilentMiss)));
assert!(error.is_none());
}
#[test]
fn batch_delete_pool_reduction_keeps_the_first_equal_outcome_and_preflight_error() {
let miss = |name: &str| {
(
DeletedObject {
object_name: name.to_owned(),
..Default::default()
},
Some(StorageError::ObjectNotFound("bucket".to_owned(), name.to_owned())),
)
};
let silent = (DeletedObject::default(), None);
let (deleted, error, selected) = reduce_test_pool_results(None, [silent, miss("first"), miss("second")]);
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
assert_eq!(deleted.object_name, "first");
assert_eq!(error, miss("first").1);
let (deleted, error, _) = reduce_test_pool_results(
Some(StorageError::PreconditionFailed),
[(miss("pool").0, Some(StorageError::ErasureWriteQuorum))],
);
assert!(deleted.object_name.is_empty());
assert_eq!(error, Some(StorageError::PreconditionFailed));
assert!(reduce_test_pool_results(None, []).2.is_none());
}
#[tokio::test]
async fn lifecycle_null_version_cas_distinguishes_absent_and_replacement_pools() {
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration as VersioningConfiguration;
@@ -13116,6 +13165,67 @@ mod tests {
));
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn batch_delete_preserves_results_and_accounting_across_sets() {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx.update_erasure_type(SetupType::Erasure).await;
let (_temp_dirs, sets) = make_local_two_set_sets_with_ctx(Arc::clone(&ctx)).await;
let store = Arc::new(new_prepared_reader_test_store_from_pools(
vec![Arc::clone(&sets)],
vec![sets.endpoints.clone()],
ctx,
));
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = format!("batch-delete-{}", Uuid::new_v4().simple());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket on both sets");
let keys: Vec<_> = [1, 0, 1]
.into_iter()
.enumerate()
.map(|(index, set)| {
(0..100)
.map(|suffix| format!("{index}-{suffix}"))
.find(|key| Arc::ptr_eq(&sets.get_disks_by_key(key), &sets.disk_set[set]))
.expect("fixture key routed to the selected set")
})
.collect();
for indices in [&[0, 1, 2][..], &[0, 2, 1], &[0, 2], &[1]] {
for &index in indices {
let mut data = PutObjReader::from_vec(vec![0; index + 1]);
sets.put_object(&bucket, &keys[index], &mut data, &ObjectOptions::default())
.await
.expect("seed an object with a distinct size");
}
let batch = indices
.iter()
.map(|&index| ObjectToDelete {
object_name: keys[index].clone(),
..Default::default()
})
.collect();
let (deleted, errors, accounting) = sets
.delete_objects_with_accounting(&bucket, batch, ObjectOptions::default())
.await;
assert_eq!(errors.len(), indices.len());
assert!(errors.iter().all(Option::is_none), "{errors:?}");
assert_eq!(
deleted.iter().map(|object| object.object_name.as_str()).collect::<Vec<_>>(),
indices.iter().map(|&index| keys[index].as_str()).collect::<Vec<_>>()
);
assert_eq!(
accounting
.into_iter()
.map(|receipt| receipt.and_then(|receipt| receipt.size))
.collect::<Vec<_>>(),
indices.iter().map(|&index| u64::try_from(index + 1).ok()).collect::<Vec<_>>()
);
}
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn select_snapshot_allows_store_delete_for_object_in_nonzero_set() {
+1 -1
View File
@@ -288,7 +288,7 @@ impl ECStore {
RenameDataGuards {
scanner_publication_lease_token: scanner_token,
external_guard,
namespace_owner: None,
..Default::default()
},
);
if scanner_token.is_some() {
+125 -4
View File
@@ -134,15 +134,18 @@ fn classify_iam_error(error: &IamError) -> Result<CredentialLookup, ProviderErro
}
/// Builds the gateway credential for one IAM identity. No authorization happens here: a
/// disabled or invalid principal still resolves, marked disabled, and the gateway refuses it
/// exactly as it refuses an unknown key.
/// disabled or otherwise invalid principal still resolves, marked disabled, and the gateway
/// refuses it identically to an unknown key. An expired STS session is the one exception: its
/// expiry is carried in [`SessionBinding`] without calling `.disable()` so the gateway checks the
/// signature and session token first and answers `400 ExpiredToken` to its holder.
fn to_gateway_credentials(access_key: &str, identity: &UserIdentity, valid: bool) -> Result<Credentials, ProviderError> {
let cred = &identity.credentials;
let mut credentials = Credentials::new(access_key, cred.secret_key.as_bytes()).map_err(|_| ProviderError::Backend)?;
// A service account carries a claims token internally, but its clients never present it, so
// it authenticates as a long-term credential (as `check_session_token` treats it in legacy).
if !cred.session_token.is_empty() && !cred.is_service_account() {
let is_sts_session = !cred.session_token.is_empty() && !cred.is_service_account();
if is_sts_session {
// A temporary credential without an expiry cannot become a gateway session, which always
// ends. Refusing it as a fault is the fail-closed answer; a never-ending session is not.
let expiration = cred.expiration.ok_or(ProviderError::Backend)?;
@@ -152,7 +155,16 @@ fn to_gateway_credentials(access_key: &str, identity: &UserIdentity, valid: bool
.map_err(|_| ProviderError::Backend)?;
}
if !valid || cred.status == ACCOUNT_OFF {
// Leave STS sessions enabled when expiration is the sole reason `valid` is false so the
// gateway evaluates `SessionBinding` against `RequestNow` and returns `400 ExpiredToken`.
// Disabled, structurally invalid, or non-expired invalid STS credentials, as well as expired
// service accounts and long-term users, remain disabled (`403`).
let expired_sts_only = is_sts_session
&& cred.status != ACCOUNT_OFF
&& cred.access_key.len() >= 3
&& cred.secret_key.len() >= 8
&& cred.is_expired();
if (!valid && !expired_sts_only) || cred.status == ACCOUNT_OFF {
credentials = credentials.disable();
}
Ok(credentials)
@@ -459,4 +471,113 @@ mod tests {
assert!(matches!(provider.lookup("rootadmin").await, Err(ProviderError::Unavailable)));
assert_eq!(iam.calls.load(Ordering::SeqCst), 0);
}
/// Positive — an expired STS credential keeps its session binding enabled so the gateway can
/// verify possession first and answer `400 ExpiredToken` via `SessionBinding`.
#[tokio::test]
async fn credentials_expired_sts_stays_enabled_for_gateway_expiry_refusal() {
let expires_at = (OffsetDateTime::now_utc() - time::Duration::hours(1)).unix_timestamp();
let iam = fake(true, move || {
let mut cred = user("on");
cred.session_token = "expired-sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(OffsetDateTime::from_unix_timestamp(expires_at).expect("valid timestamp"));
found(cred, false)
});
let credentials = expect_found(lookup(iam, ACCESS_KEY).await);
assert!(!credentials.is_disabled());
let binding = credentials
.session_binding()
.expect("expired STS retains its session binding");
assert_eq!(binding.expires_at_unix_seconds(), expires_at);
let now = RequestNow::from_unix_seconds(expires_at + 1);
assert_eq!(
credentials.admit(Some(b"expired-sts-token"), now),
Err(rustfs_gateway::CredentialRefusal::SessionExpired)
);
assert_eq!(
credentials.admit(Some(b"wrong-token"), now),
Err(rustfs_gateway::CredentialRefusal::SessionTokenMismatch)
);
assert_eq!(
credentials.admit(None, now),
Err(rustfs_gateway::CredentialRefusal::SessionCredentialWithoutToken)
);
}
/// Negative — disabled, structurally invalid, or non-expired invalid STS credentials, and
/// expired service accounts, must still be disabled so the gateway answers `403`.
#[tokio::test]
async fn credentials_non_expiry_invalid_sts_and_expired_service_account_stay_disabled() {
let past = OffsetDateTime::now_utc() - time::Duration::hours(1);
let future = OffsetDateTime::now_utc() + time::Duration::hours(1);
let disabled_expired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("off");
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(disabled_expired_sts.is_disabled());
assert_eq!(
disabled_expired_sts.admit(Some(b"sts-token"), RequestNow::from_unix_seconds(past.unix_timestamp() + 1)),
Err(rustfs_gateway::CredentialRefusal::Disabled)
);
let invalid_unexpired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(future);
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(invalid_unexpired_sts.is_disabled());
let short_key_expired_sts = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.access_key = "ab".to_owned();
cred.session_token = "sts-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
found(cred, false)
}),
"ab",
)
.await,
);
assert!(short_key_expired_sts.is_disabled());
let expired_service_account = expect_found(
lookup(
fake(true, move || {
let mut cred = user("on");
cred.session_token = "service-account-claims-token".to_owned();
cred.parent_user = "parent".to_owned();
cred.expiration = Some(past);
cred.claims =
Some([(rustfs_credentials::IAM_POLICY_CLAIM_NAME_SA.to_owned(), "inherited-policy".into())].into());
found(cred, false)
}),
ACCESS_KEY,
)
.await,
);
assert!(expired_service_account.is_disabled());
assert!(expired_service_account.session_binding().is_none());
}
}
+3 -1
View File
@@ -285,7 +285,9 @@ pub(crate) fn classify_storage_error(error: &EcstoreError) -> HealErrorClass {
EcstoreError::NoHealRequired => HealErrorClass::NoHealRequired,
// An ambiguous legacy delete residue needs operator inspection;
// retrying the same heal cannot resolve it (backlog#2902).
EcstoreError::DeleteRecoveryLegacyAmbiguous => HealErrorClass::Permanent,
EcstoreError::DeleteRecoveryLegacyAmbiguous | EcstoreError::DeleteRecoveryGenerationConflict { .. } => {
HealErrorClass::Permanent
}
EcstoreError::Timeout => HealErrorClass::LockContention,
EcstoreError::DiskNotFound
| EcstoreError::VolumeNotFound
+35
View File
@@ -290,6 +290,24 @@ impl HealManager {
"Heal scheduler task completed"
);
}
Err(Error::Storage(crate::heal::StorageError::DeleteRecoveryGenerationConflict {
bucket,
object,
transaction,
})) => {
error!(
target: "rustfs::heal::manager",
event = EVENT_HEAL_SCHEDULER_STATE,
component = LOG_COMPONENT_HEAL,
subsystem = LOG_SUBSYSTEM_MANAGER,
state = "blocked_delete_generation_conflict",
task_id,
bucket,
object,
%transaction,
"Committed delete conflicts with the live object generation"
);
}
Err(e @ Error::LegacyMrfUnverified { .. }) => {
warn!(
target: "rustfs::heal::manager",
@@ -492,6 +510,23 @@ impl HealManager {
}
publish_verified_mrf_repair_events(&notice_targets, &completed_status_for_verified_events);
publish_unverified_legacy_mrf_events(&notice_targets, &completed_status_for_verified_events, &result);
if matches!(completed_status, HealTaskStatus::Failed { .. })
&& let Err(Error::Storage(crate::heal::StorageError::DeleteRecoveryGenerationConflict {
bucket,
object,
transaction,
})) = &result
{
for anchor in notice_targets.iter().filter_map(|target| target.durable_anchor.as_ref()) {
if anchor.kind == rustfs_common::mrf_channel::MrfKind::PartialWrite
&& anchor.bucket.as_ref() == bucket
&& anchor.object.as_ref() == object
&& Some(anchor.bucket_incarnation_id) == task.expected_mrf_bucket_incarnation_id
{
crate::heal::mrf_queue::note_delete_generation_conflict(anchor, *transaction);
}
}
}
// Single-object MRF attempts retain one storage result.
// Use the original result even if the report was size
// limited, without certifying independent integrity.
+20 -1
View File
@@ -189,6 +189,10 @@ pub async fn accept_unverified_legacy_risk(request: MrfLegacyRiskAcceptanceReque
}
enum MrfLifecycleCommand {
BlockDeleteGenerationConflict {
anchor: MrfDurableRepairAnchor,
transaction: Uuid,
},
Get {
id: Uuid,
_permit: tokio::sync::OwnedSemaphorePermit,
@@ -216,6 +220,16 @@ enum MrfLifecycleCommand {
},
}
pub(super) fn note_delete_generation_conflict(anchor: &MrfDurableRepairAnchor, transaction: Uuid) {
if let Some(sender) = GLOBAL_MRF_LIFECYCLE_SENDER.get() {
// A busy controller still owns the active responsibility and will retry it.
let _ = sender.try_send(MrfLifecycleCommand::BlockDeleteGenerationConflict {
anchor: anchor.clone(),
transaction,
});
}
}
/// Committed checkpoint publication, inspection and owner-scoped cleanup.
pub mod snapshot;
@@ -1154,7 +1168,7 @@ impl MrfRuntime {
node_local: true,
checkpoint_owner: self.runtime_checkpoint.map(|(owner, _)| owner),
checkpoint_sequence: self.runtime_checkpoint.map(|(_, sequence)| sequence),
held_count: lifecycle.held_count,
held_count: lifecycle.held_count + lifecycle.blocked_delete_generation_count,
legacy_generation_unknown_count: lifecycle.legacy_generation_unknown_count,
bucket_incarnation_changed_count: lifecycle.bucket_incarnation_changed_count,
operator_accepted_count: lifecycle.operator_accepted_count,
@@ -1339,6 +1353,9 @@ impl MrfRuntime {
async fn handle_lifecycle_command(&mut self, manager: &HealManager, command: MrfLifecycleCommand) {
match command {
MrfLifecycleCommand::BlockDeleteGenerationConflict { anchor, transaction } => {
self.partial_writes.park_delete_generation_conflict(&anchor, transaction);
}
MrfLifecycleCommand::List {
after,
limit,
@@ -2537,6 +2554,8 @@ async fn finalize_mrf_consumer(
lifecycle_receiver.close();
while let Some(command) = lifecycle_receiver.recv().await {
match command {
// Replay re-inspects the durable receipts after restart.
MrfLifecycleCommand::BlockDeleteGenerationConflict { .. } => {}
MrfLifecycleCommand::Get { response, .. } => {
let _ = response.send(Err(MrfLifecycleControlError::Unavailable));
}
+3 -2
View File
@@ -99,7 +99,8 @@ pub(super) fn now_ms() -> u64 {
}
pub(super) fn publish_summary(runtime: &MrfRuntime, counts: &super::partial_write::PartialWriteLifecycleSummary) {
let unverified = counts.held_count
let held_count = counts.held_count + counts.blocked_delete_generation_count;
let unverified = held_count
+ counts.legacy_generation_unknown_count
+ counts.bucket_incarnation_changed_count
+ counts.operator_accepted_count;
@@ -110,7 +111,7 @@ pub(super) fn publish_summary(runtime: &MrfRuntime, counts: &super::partial_writ
checkpoint_owner: runtime.runtime_checkpoint.map(|(owner, _)| owner),
checkpoint_sequence: runtime.runtime_checkpoint.map(|(_, sequence)| sequence),
active_responsibility_count: runtime.partial_writes.depth().saturating_sub(unverified),
held_count: counts.held_count,
held_count,
legacy_generation_unknown_count: counts.legacy_generation_unknown_count,
bucket_incarnation_changed_count: counts.bucket_incarnation_changed_count,
operator_accepted_count: counts.operator_accepted_count,
@@ -69,6 +69,14 @@ impl PartialWriteKey {
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum ResponsibilityState {
Active {},
// The receipts are the durable evidence. Replay the active obligation and
// re-inspect them on restart, including when rolling back to a V1 reader.
#[serde(skip)]
BlockedDeleteGenerationConflict {
bucket_incarnation_id: Uuid,
transaction: Uuid,
since_ms: u64,
},
SourceAndCurrentGenerationUnknown {
since_ms: u64,
next_probe_at_ms: u64,
@@ -106,7 +114,7 @@ impl ResponsibilityState {
fn estimated_bytes(&self) -> usize {
match self {
Self::Active {} => 0,
Self::Active {} | Self::BlockedDeleteGenerationConflict { .. } => 0,
Self::SourceAndCurrentGenerationUnknown { .. } => 2 * std::mem::size_of::<u64>() + std::mem::size_of::<u32>(),
Self::HeldUnverifiedLegacy { .. } => std::mem::size_of::<Uuid>() + std::mem::size_of::<u64>(),
Self::LegacyGenerationUnknown { .. } => std::mem::size_of::<Uuid>() + std::mem::size_of::<u64>(),
@@ -123,7 +131,10 @@ impl ResponsibilityState {
pub(super) fn bucket_incarnation_id(&self) -> Option<Uuid> {
match self {
Self::Active {} | Self::SourceAndCurrentGenerationUnknown { .. } => None,
Self::HeldUnverifiedLegacy {
Self::BlockedDeleteGenerationConflict {
bucket_incarnation_id, ..
}
| Self::HeldUnverifiedLegacy {
bucket_incarnation_id, ..
}
| Self::OperatorAcceptedUnverified {
@@ -164,6 +175,7 @@ impl ResponsibilityCheckpoint {
}
match &self.state {
ResponsibilityState::Active {} => true,
ResponsibilityState::BlockedDeleteGenerationConflict { .. } => false,
ResponsibilityState::SourceAndCurrentGenerationUnknown { .. } => self.source_bucket_incarnation_id.is_none(),
ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id, ..
@@ -256,6 +268,7 @@ impl Responsibility {
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct PartialWriteLifecycleSummary {
pub held_count: usize,
pub blocked_delete_generation_count: usize,
pub legacy_generation_unknown_count: usize,
pub bucket_incarnation_changed_count: usize,
pub operator_accepted_count: usize,
@@ -463,6 +476,27 @@ impl PartialWrites {
}
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
self.park(
anchor,
ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id: anchor.bucket_incarnation_id,
since_ms: unix_now_ms(),
},
)
}
pub(super) fn park_delete_generation_conflict(&mut self, anchor: &MrfDurableRepairAnchor, transaction: Uuid) -> bool {
self.park(
anchor,
ResponsibilityState::BlockedDeleteGenerationConflict {
bucket_incarnation_id: anchor.bucket_incarnation_id,
transaction,
since_ms: unix_now_ms(),
},
)
}
fn park(&mut self, anchor: &MrfDurableRepairAnchor, state: ResponsibilityState) -> bool {
let key = PartialWriteKey::from_anchor(anchor);
let Some(entry) = self.entries.get_mut(&key) else {
return false;
@@ -475,10 +509,7 @@ impl PartialWrites {
return false;
}
let old_cost = Self::entry_cost(entry);
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
bucket_incarnation_id: anchor.bucket_incarnation_id,
since_ms: unix_now_ms(),
};
entry.state = state;
self.bytes = self.bytes.saturating_sub(old_cost).saturating_add(Self::entry_cost(entry));
true
}
@@ -492,6 +523,7 @@ impl PartialWrites {
summary.legacy_generation_unknown_count += 1;
}
}
ResponsibilityState::BlockedDeleteGenerationConflict { .. } => summary.blocked_delete_generation_count += 1,
ResponsibilityState::HeldUnverifiedLegacy { since_ms, .. } => {
summary.held_count += 1;
summary.oldest_unverified_legacy_enqueued_at_ms = Some(
@@ -528,7 +560,10 @@ impl PartialWrites {
responsibility_id: entry.responsibility_id,
source_bucket_incarnation_id: entry.source_bucket_incarnation_id,
last_operator_acceptance: entry.last_operator_acceptance.clone(),
state: entry.state.clone(),
state: match entry.state {
ResponsibilityState::BlockedDeleteGenerationConflict { .. } => ResponsibilityState::Active {},
_ => entry.state.clone(),
},
})
})
.collect()
@@ -649,6 +684,9 @@ impl PartialWrites {
return Err("a different operator disposition already exists");
}
ResponsibilityState::Active {} => return Err("responsibility is not held as unverified legacy"),
ResponsibilityState::BlockedDeleteGenerationConflict { .. } => {
return Err("delete generation conflict requires recheck");
}
ResponsibilityState::SourceAndCurrentGenerationUnknown { .. } => {
return Err("current bucket incarnation is unresolved");
}
@@ -817,6 +855,11 @@ impl PartialWrites {
let (status, bucket_incarnation_id, held_since_ms) = match &entry.state {
ResponsibilityState::Active {} if entry.generation_unobserved() => ("legacy_generation_unobserved", None, None),
ResponsibilityState::Active {} => ("active", None, None),
ResponsibilityState::BlockedDeleteGenerationConflict {
bucket_incarnation_id,
since_ms,
..
} => ("blocked_delete_generation_conflict", Some(*bucket_incarnation_id), Some(*since_ms)),
ResponsibilityState::SourceAndCurrentGenerationUnknown { since_ms, .. } => {
("source_and_current_generation_unknown", None, Some(*since_ms))
}
@@ -854,6 +897,10 @@ impl PartialWrites {
enqueued_at_ms: entry.intent.enqueued_at_ms,
status: status.to_string(),
held_since_ms,
delete_transaction_id: match entry.state {
ResponsibilityState::BlockedDeleteGenerationConflict { transaction, .. } => Some(transaction),
_ => None,
},
accepted: entry.last_operator_acceptance.clone(),
last_identity_probe_result: entry.last_identity_probe_result.map(str::to_string),
last_identity_probe_at_ms: entry.last_identity_probe_at_ms,
@@ -1181,6 +1228,8 @@ pub struct MrfLegacyResponsibility {
pub enqueued_at_ms: u64,
pub status: String,
pub held_since_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub delete_transaction_id: Option<Uuid>,
pub accepted: Option<MrfOperatorAcceptance>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_identity_probe_result: Option<String>,
@@ -1460,6 +1509,7 @@ mod tests {
let scheduling = schedule();
let expected = PartialWriteLifecycleSummary {
held_count: 2,
blocked_delete_generation_count: 0,
legacy_generation_unknown_count: 3,
bucket_incarnation_changed_count: 1,
operator_accepted_count: 2,
@@ -1910,6 +1960,45 @@ mod tests {
);
}
#[test]
fn delete_generation_conflict_stops_dispatch_and_rechecks_the_same_responsibility_on_replay() {
let original = intent("delete-generation");
let source = Uuid::new_v4();
let anchor = MrfDurableRepairAnchor::from_intent(&original, source).expect("source-bound responsibility");
let mut writes = PartialWrites::default();
writes
.admit_with_source_incarnation(original.clone(), Some(source), 1, 8192)
.expect("admit responsibility");
writes.mark_persisted();
writes
.entries
.get_mut(&PartialWriteKey::from_anchor(&anchor))
.expect("admitted entry")
.anchor = Some(anchor.clone());
let before = writes.checkpoint_records(super::super::intent_digest);
let transaction = Uuid::new_v4();
let stale = MrfDurableRepairAnchor::from_intent(&intent("delete-generation"), source).expect("another lease");
assert!(!writes.park_delete_generation_conflict(&stale, transaction));
assert!(writes.park_delete_generation_conflict(&anchor, transaction));
assert!(writes.ready_keys(Instant::now() + Duration::from_secs(3600), 1).is_empty());
let checkpoint = writes.checkpoint_records(super::super::intent_digest);
assert_eq!(checkpoint, before, "the original obligation remains readable by older peers");
let record = checkpoint.first().expect("retained responsibility");
let row = writes
.responsibility(record.responsibility_id)
.expect("inspect blocked responsibility");
assert_eq!(row.status, "blocked_delete_generation_conflict");
assert_eq!(row.delete_transaction_id, Some(transaction));
let mut replay = PartialWrites::default();
replay
.admit_with_source_incarnation(original.clone(), Some(source), 1, 8192)
.expect("replay durable intent");
assert!(replay.restore_state(&original, record));
replay.mark_persisted();
assert_eq!(replay.ready_keys(Instant::now(), 1), [PartialWriteKey::from_anchor(&anchor)]);
}
#[test]
fn unverified_legacy_without_matching_lifecycle_checkpoint_rechecks_after_restart() {
let original = intent("legacy");
+162
View File
@@ -366,6 +366,168 @@ async fn unversioned_deleted_partial_write_is_discharged_by_an_absence_proof_inn
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn committed_delete_generation_conflict_parks_partial_write_until_recheck() {
use rustfs_common::mrf_channel::{MrfScope, persist_partial_write_intent_with_incarnation};
use storage_api::integration::{DeleteOptions, DeleteRecoveryAction, DeleteRecoveryState, lookup_config_for_pools};
let bucket = "partial-delete-conflict";
let object = "slice";
temp_env::async_with_vars(
[
("RUSTFS_STORAGE_CLASS_STANDARD", Some("EC:3")),
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
],
async {
let root = tempfile::tempdir().expect("fixture root");
let stop = tokio_util::sync::CancellationToken::new();
stop.cancel(); // The test owns recovery of the seeded receipts.
let env = TestECStoreEnv::builder()
.disk_count(9)
.base_dir(root.path())
.shutdown_token(stop)
.build()
.await;
env.ecstore.set_storage_class(
lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 storage class for the nine-drive set"),
);
env.make_bucket(bucket, false).await;
put(&env, bucket, object, &vec![1; 1024 * 1024], false).await;
put(&env, bucket, "other-generation", &vec![2; 1024 * 1024], false).await;
let live = env.disk_paths[8].join(bucket).join(object);
let matching = root.path().join("saved-source");
let foreign = env.disk_paths[8].join(bucket).join("other-generation");
std::fs::rename(&live, &matching).expect("save the matching ninth shard");
std::fs::rename(&foreign, &live).expect("return a drive with a different generation");
let foreign_meta = std::fs::read(live.join("xl.meta")).expect("live foreign metadata");
let set = env.ecstore.pools[0].get_disks(0);
let disks = set
.disks
.read()
.await
.iter()
.map(|d| d.clone().expect("online disk"))
.collect::<Vec<_>>();
let shard = disks[8]
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("live foreign shard");
assert_eq!((shard.erasure.data_blocks, shard.erasure.parity_blocks), (6, 3));
let foreign_payload = live
.join(shard.data_dir.expect("external shard data directory").to_string())
.join("part.1");
let foreign_bytes = std::fs::read(&foreign_payload).expect("original generation B shard");
let incarnation = set.bucket_incarnation_id_from_disk(bucket).await.expect("bucket incarnation");
let transaction = uuid::Uuid::new_v4();
for disk in &disks[..8] {
disk.delete_version_recoverable(
bucket,
object,
rustfs_filemeta::FileInfo {
name: object.to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
delete_recovery_bucket_incarnation: Some(incarnation),
..Default::default()
},
)
.await
.expect("prepare delete of generation A");
}
let mut receipts = Vec::new();
for disk in &disks[..8] {
let prepared = disk
.inspect_delete_transaction(bucket, object, transaction)
.await
.expect("prepared delete");
let committed = disk
.settle_delete_transaction(
bucket,
object,
transaction,
prepared.fingerprint,
DeleteRecoveryAction::PublishCommit,
)
.await
.expect("publish committed receipt");
assert_eq!(committed.state, DeleteRecoveryState::QuorumCommitted);
receipts.push(committed);
}
let manager = manager(&env);
mrf_queue::spawn_mrf_consumer(manager.clone());
persist_partial_write_intent_with_incarnation(
bucket,
object,
None,
MrfScope {
pool_index: 0,
set_index: 0,
},
Some(incarnation),
)
.await
.expect("persist the original partial-write responsibility");
manager.start().await.expect("start scheduler");
assert!(
wait_until(|| async {
mrf_queue::list_legacy_responsibilities(None, 16).await.is_ok_and(|page| {
page.responsibilities.iter().any(|row| {
row.bucket == bucket
&& row.object == object
&& row.status == "blocked_delete_generation_conflict"
&& row.delete_transaction_id == Some(transaction)
})
})
})
.await,
"confirmed conflict must park the exact responsibility"
);
let held = mrf_queue::list_legacy_responsibilities(None, 16)
.await
.expect("parked responsibilities")
.responsibilities
.into_iter()
.find(|row| row.delete_transaction_id == Some(transaction))
.expect("blocked transaction");
assert!(snapshot_contains(object).await);
assert_eq!(std::fs::read(live.join("xl.meta")).expect("preserved live metadata"), foreign_meta);
assert_eq!(std::fs::read(foreign_payload).expect("preserved live shard"), foreign_bytes);
for (disk, before) in disks.iter().zip(receipts) {
assert_eq!(
disk.inspect_delete_transaction(bucket, object, transaction)
.await
.expect("retained receipt"),
before
);
}
assert_eq!(
disks[8]
.inspect_delete_transaction(bucket, object, transaction)
.await
.expect("untouched ninth disk")
.state,
DeleteRecoveryState::Absent
);
std::fs::rename(&live, &foreign).expect("retain the conflicting generation separately");
std::fs::rename(&matching, &live).expect("restore matching evidence");
mrf_queue::recheck_legacy_responsibility(held.responsibility_id, incarnation)
.await
.expect("operator recheck");
assert!(
wait_until(|| async { !snapshot_contains(object).await }).await,
"matching source must let recovery finish"
);
assert!(!live.join("xl.meta").exists());
manager.stop().await.expect("stop scheduler");
},
)
.await;
}
#[test]
fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof() {
const STACK_SIZE: usize = 8 * 1024 * 1024;
+1
View File
@@ -21,6 +21,7 @@ pub(crate) mod endpoint_index {
// still touch directly.
#[allow(unused_imports)]
pub(crate) mod integration {
pub(crate) use rustfs_ecstore::api::config::storageclass::lookup_config_for_pools;
pub(crate) use rustfs_ecstore::api::disk::{
DeleteOptions, DeleteRecoveryAction, DeleteRecoveryState, DiskAPI, DiskError, DiskOption, DiskStore, Endpoint,
RUSTFS_META_BUCKET, ReadOptions, new_disk,
+104 -4
View File
@@ -173,6 +173,7 @@ enum PreparedServicePolicyMode {
tokio::task_local! {
static BUCKET_TAG_DELETION: ();
static SCOPED_ROOT_CREDENTIALS: Option<Credentials>;
}
/// Scope authorization to the server's DeleteBucketTagging operation. The IAM action is shared
@@ -181,6 +182,22 @@ pub async fn with_bucket_tag_deletion<F: std::future::Future>(operation: F) -> F
BUCKET_TAG_DELETION.scope((), operation).await
}
/// Scope IAM root-credential lookup for the duration of `operation` to the
/// caller's request-scoped server context rather than the process-ambient root
/// credentials (rustfs/backlog#1469).
pub async fn with_scoped_root_credentials<F: std::future::Future>(
root_credentials: Option<Credentials>,
operation: F,
) -> F::Output {
SCOPED_ROOT_CREDENTIALS.scope(root_credentials, operation).await
}
fn effective_root_credentials() -> Option<Credentials> {
SCOPED_ROOT_CREDENTIALS
.try_with(Clone::clone)
.unwrap_or_else(|_| crate::root_credentials::credentials())
}
#[derive(Clone)]
enum PreparedIamMode {
TerminalDeny,
@@ -1439,6 +1456,10 @@ impl<T: Store> IamSys<T> {
return Err(IamError::InvalidSecretKeyLength);
}
if args.policy.as_deref().is_some_and(|policy| !policy.is_empty()) {
return Err(IamError::InvalidArgument);
}
let (updated_at, secret_changed, parent_guard) = self
.store
.add_user_at_with_secret_change(access_key, args, updated_at, allow_status_change)
@@ -1578,8 +1599,8 @@ impl<T: Store> IamSys<T> {
}
pub async fn check_key(&self, access_key: &str) -> Result<(Option<UserIdentity>, bool)> {
if let Some(sys_cred) = crate::root_credentials::credentials()
&& sys_cred.access_key == access_key
if let Some(sys_cred) = effective_root_credentials()
&& bool::from(sys_cred.access_key.as_bytes().ct_eq(access_key.as_bytes()))
{
return Ok((Some(UserIdentity::new(sys_cred)), true));
}
@@ -1607,12 +1628,17 @@ impl<T: Store> IamSys<T> {
return Ok(true);
}
if identity.sts_generation.is_none() {
if cred.is_service_account() || crate::is_root_access_key(&cred.parent_user) {
let root_cred = effective_root_credentials();
if cred.is_service_account()
|| root_cred
.as_ref()
.is_some_and(|root| bool::from(root.access_key.as_bytes().ct_eq(cred.parent_user.as_bytes())))
{
return Ok(true);
}
// OIDC and broker-issued plugin attempts have separate parent authorities.
// A freshly published identity may not yet have its decoded claims cached.
if let Some(key) = crate::root_credentials::token_signing_key()
if let Some(key) = root_cred.map(|root| root.secret_key)
&& let Ok(claims) = get_claims_from_token_with_secret(&cred.session_token, &key)
&& claims.get("parent").and_then(Value::as_str) == Some(cred.parent_user.as_str())
&& (is_verified_or_legacy_federated_session(&claims, &cred.parent_user)
@@ -8789,4 +8815,78 @@ mod tests {
assert!(matches!(result, Err(IamError::InvalidArgument)));
}
#[tokio::test]
async fn create_user_rejects_non_empty_policy_field_fail_closed() {
let iam_sys = IamSys::new(
IamCache::new(StsTestMockStore::new(true))
.await
.expect("IAM cache should initialize"),
);
let err = iam_sys
.create_user(
"alice-policy-reject",
&AddOrUpdateUserReq {
secret_key: "secret-key-123456".to_string(),
policy: Some("readwrite".to_string()),
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect_err("non-empty AddOrUpdateUserReq.policy must fail closed");
assert!(matches!(err, IamError::InvalidArgument), "unexpected error: {err:?}");
assert!(
iam_sys.get_user("alice-policy-reject").await.is_none(),
"rejected user creation must not leave a user in cache"
);
}
#[tokio::test]
async fn check_key_respects_scoped_root_credentials() {
let _ = rustfs_credentials::init_global_action_credentials(
Some("ambient-root".to_string()),
Some("ambient-root-secret".to_string()),
);
let ambient_root = crate::root_credentials::credentials().expect("global action credentials should be initialized");
let iam_sys = IamSys::new(
IamCache::new(StsTestMockStore::new(true))
.await
.expect("IAM cache should initialize"),
);
let scoped_root = Credentials {
access_key: "scoped-server-b-root".to_string(),
secret_key: "scoped-server-b-secret".to_string(),
status: "on".to_string(),
..Default::default()
};
let (ambient_in_b, ambient_valid) =
with_scoped_root_credentials(Some(scoped_root.clone()), iam_sys.check_key(&ambient_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(
ambient_in_b.is_none() && !ambient_valid,
"process-ambient root key must not authenticate inside a different scoped root context"
);
let (scoped_in_b, scoped_valid) =
with_scoped_root_credentials(Some(scoped_root.clone()), iam_sys.check_key(&scoped_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(scoped_valid);
assert_eq!(
scoped_in_b.expect("scoped root must resolve").credentials.access_key,
scoped_root.access_key
);
let (none_in_b, none_valid) = with_scoped_root_credentials(None, iam_sys.check_key(&ambient_root.access_key))
.await
.expect("check_key should succeed cleanly");
assert!(
none_in_b.is_none() && !none_valid,
"empty scoped root credentials must fail closed instead of falling back to ambient root"
);
}
}
+49 -14
View File
@@ -74,7 +74,7 @@ static GET_STAGE_LOCAL_SUMMARY_SEQUENCE: AtomicU64 = AtomicU64::new(0);
type GetStageLocalSummaryKey = (&'static str, &'static str, &'static str, &'static str);
/// Sampled local aggregate for one bounded GetObject stage label set.
/// Sampled local aggregate for one bounded stage label set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetStageLocalSummary {
pub path: &'static str,
@@ -85,7 +85,21 @@ pub struct GetStageLocalSummary {
pub duration_nanoseconds: u64,
}
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummary>>> =
impl GetStageLocalSummary {
fn key(&self) -> GetStageLocalSummaryKey {
(self.path, self.stage, self.object_class, self.size_bucket)
}
}
/// A local summary row with its peak in the same sampling window.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetStageLocalSummaryWithMax {
pub summary: GetStageLocalSummary,
/// Largest sampled duration since the previous drain.
pub max_duration_nanoseconds: u64,
}
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummaryWithMax>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
/// Global switch for all remaining (non GET/PUT-stage) metric emission in this
@@ -130,12 +144,23 @@ pub fn get_stage_local_summary_sample_rate() -> u64 {
}
pub fn take_get_stage_local_summary() -> Vec<GetStageLocalSummary> {
let mut rows = drain_get_stage_local_summary(|row| row.summary);
rows.sort_unstable_by_key(GetStageLocalSummary::key);
rows
}
/// Drain the same sampling window as [`take_get_stage_local_summary`] and include each sorted row's maximum.
pub fn take_get_stage_local_summary_with_max() -> Vec<GetStageLocalSummaryWithMax> {
let mut rows = drain_get_stage_local_summary(std::convert::identity);
rows.sort_unstable_by_key(|row| row.summary.key());
rows
}
fn drain_get_stage_local_summary<T>(mut project: impl FnMut(GetStageLocalSummaryWithMax) -> T) -> Vec<T> {
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
return Vec::new();
};
let mut rows = summary.drain().map(|(_, row)| row).collect::<Vec<_>>();
rows.sort_unstable_by_key(|row| (row.path, row.stage, row.object_class, row.size_bucket));
rows
summary.drain().map(|(_, row)| project(row)).collect()
}
fn record_get_stage_local_summary(
@@ -165,16 +190,20 @@ fn record_get_stage_local_summary(
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
return;
};
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummary {
path,
stage,
object_class,
size_bucket,
sampled_count: 0,
duration_nanoseconds: 0,
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummaryWithMax {
summary: GetStageLocalSummary {
path,
stage,
object_class,
size_bucket,
sampled_count: 0,
duration_nanoseconds: 0,
},
max_duration_nanoseconds: 0,
});
row.sampled_count = row.sampled_count.saturating_add(1);
row.duration_nanoseconds = row.duration_nanoseconds.saturating_add(duration_nanoseconds);
row.summary.sampled_count = row.summary.sampled_count.saturating_add(1);
row.summary.duration_nanoseconds = row.summary.duration_nanoseconds.saturating_add(duration_nanoseconds);
row.max_duration_nanoseconds = row.max_duration_nanoseconds.max(duration_nanoseconds);
}
/// Enable or disable general (non GET/PUT-stage) metric emission.
@@ -232,6 +261,9 @@ pub const PUT_STAGE_PUT_OBJECT_OPERATION_AWAIT_TOTAL: &str = "put_object_operati
pub const PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT: &str = "put_object_operation_body_to_commit_submit";
pub const PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN: &str = "put_object_operation_result_return";
pub const PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY: &str = "put_object_operation_first_poll_delay";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK: &str = "put_object_commit_ready_snapshot_lifecycle_lock";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK: &str = "put_object_commit_ready_snapshot_metadata_lock";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ: &str = "put_object_commit_ready_snapshot_authority_read";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY: &str =
"put_object_commit_namespace_lock_acquired_to_commit_ready";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP: &str =
@@ -4547,6 +4579,9 @@ mod tests {
PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT,
PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN,
PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_EXPECTED_VERSION_LOOKUP,
+63 -6
View File
@@ -212,13 +212,19 @@ impl KeystoneAuthProvider {
claims.insert("keystone_roles".to_string(), json!(token.roles));
claims.insert("auth_source".to_string(), json!("keystone"));
// Keep `parent_user` in the `keystone:` namespace (matching `access_key`) so an external
// Keystone username can never collide with a local IAM user or the root access key in
// service-account ownership or admin checks. The username remains available in `name`
// and `claims["keystone_username"]`.
let access_key = format!("keystone:{}", token.user_id);
Credentials {
access_key: format!("keystone:{}", token.user_id),
access_key: access_key.clone(),
secret_key: String::new(), // Not used for token auth
session_token: token.token.clone(),
expiration: Some(token.expires_at),
status: "active".to_string(),
parent_user: token.username.clone(),
parent_user: access_key,
groups,
claims: Some(claims),
name: Some(token.username.clone()),
@@ -303,13 +309,64 @@ mod tests {
let cred = provider.keystone_token_to_credentials(&token);
assert_eq!(cred.access_key, "keystone:user123");
assert_eq!(cred.parent_user, "testuser");
assert_eq!(cred.parent_user, "keystone:user123");
assert_eq!(cred.name.as_deref(), Some("testuser"));
assert_eq!(cred.groups, Some(vec!["Member".to_string(), "admin".to_string()]));
assert!(cred.claims.is_some());
let claims = cred.claims.unwrap();
assert_eq!(claims.get("keystone_user_id").unwrap().as_str().unwrap(), "user123");
assert_eq!(claims.get("keystone_project_id").unwrap().as_str().unwrap(), "proj456");
let claims = cred.claims.expect("keystone claims must be populated");
assert_eq!(claims.get("keystone_user_id").and_then(|v| v.as_str()), Some("user123"));
assert_eq!(claims.get("keystone_username").and_then(|v| v.as_str()), Some("testuser"));
assert_eq!(claims.get("keystone_project_id").and_then(|v| v.as_str()), Some("proj456"));
}
#[test]
fn test_keystone_parent_user_uses_namespaced_identity_not_username() {
let client = KeystoneClient::new(
"http://localhost:5000".to_string(),
crate::KeystoneVersion::V3,
None,
None,
None,
"Default".to_string(),
true,
Duration::from_secs(30),
);
let provider = KeystoneAuthProvider::new(client, 100, Duration::from_secs(60), true);
for (user_id, colliding_username) in [("uid-alice", "alice"), ("uid-root-lookalike", "rustfsadmin")] {
let token = KeystoneToken {
token: "test-token".to_string(),
user_id: user_id.to_string(),
username: colliding_username.to_string(),
project_id: None,
project_name: None,
domain_id: Some("default".to_string()),
domain_name: Some("Default".to_string()),
roles: vec!["member".to_string()],
expires_at: time::OffsetDateTime::now_utc() + time::Duration::hours(1),
issued_at: time::OffsetDateTime::now_utc(),
};
let cred = provider.keystone_token_to_credentials(&token);
let expected_identity = format!("keystone:{user_id}");
assert_eq!(cred.access_key, expected_identity);
assert_eq!(cred.parent_user, expected_identity);
assert_ne!(
cred.parent_user, colliding_username,
"parent_user must never carry the bare Keystone username"
);
assert_eq!(cred.name.as_deref(), Some(colliding_username));
assert_eq!(
cred.claims
.as_ref()
.and_then(|claims| claims.get("keystone_username"))
.and_then(|value| value.as_str()),
Some(colliding_username)
);
}
}
#[test]
+1
View File
@@ -134,6 +134,7 @@ pub fn desired_context_binding(existing: Option<u8>) -> Option<u8> {
/// opened by a node that predates it (the unwrap fails authentication), so the
/// switch must only be enabled once every node in the cluster runs a release
/// that understands `context_binding`. Reading bound envelopes needs no switch.
// RUSTFS_COMPAT_TODO(backlog-1667-kms-envelope-aad): keep Local and Vault KV2 DEK envelope AAD writes off by default during rolling upgrades while older nodes lack context_binding support. Remove after the minimum supported release understands CONTEXT_BINDING_AAD_V1 and the default flips to true.
pub fn envelope_aad_write_enabled() -> bool {
use crate::config::ENV_KMS_ENVELOPE_AAD;
use rustfs_utils::get_env_bool;
@@ -21,13 +21,17 @@ pub(super) fn rules() -> Vec<Rule> {
vec![
Rule {
evidence_fields: strings(["host"]),
anchors: strings(["Create pool endpoints host"]),
anchors: strings(["startup_endpoint_dns_failed", "Startup endpoint DNS resolution failed"]),
..base(
"endpoint-resolve-failed",
P1Unavailable,
"startup",
"启动期端点主机名解析失败",
all([contains("Create pool endpoints host"), contains("not found")]),
any([
field("event", "startup_endpoint_dns_failed"),
contains("Startup endpoint DNS resolution failed"),
all([contains("Create pool endpoints host"), contains("not found")]),
]),
"启动期端点主机名解析失败(DNS 未就绪/拼写错误/hosts 缺失)。",
"容器/K8s 场景确认 DNS 就绪顺序;核对 volumes 参数拼写。",
)
@@ -453,6 +453,15 @@ fn smoke_samples_hit_exact_rule_sets() {
&["unknown-access-key"],
);
exact(&msg("HTTP transport failed: BrokenPipe while streaming response body"), &[]);
exact(
&Sample {
fields: &[("event", "startup_endpoint_dns_failed"), ("host", "node5")],
..msg("DNS deadline exhausted")
},
&["endpoint-resolve-failed"],
);
exact(&msg("Startup endpoint DNS resolution failed"), &["endpoint-resolve-failed"]);
exact(&msg("retrying endpoint local-host detection after temporary DNS error"), &[]);
// Internode auth failures legitimately hit both the internode rule and
// the generic client signature rule.
exact(
+4
View File
@@ -99,6 +99,10 @@ pub struct AddOrUpdateUserReq {
#[serde(rename = "secretKey")]
pub secret_key: String,
/// Deprecated legacy field from older admin payloads. `/admin/v3/add-user`
/// manages user credentials and status only and rejects non-empty values
/// with `InvalidArgument`; callers must attach policies via the dedicated
/// policy-attachment endpoints.
#[serde(rename = "policy", skip_serializing_if = "Option::is_none")]
pub policy: Option<String>,
+9 -3
View File
@@ -157,8 +157,12 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
| Variable | Default | Description |
|-------------------------------------------------|--------------|-------------------------------------------------------------|
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB), applied to rolled logs and to compressed archives separately; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB) shared across rolled logs and compressed archives when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is unset; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` | unset | Optional dedicated byte budget for compressed archives (`.gz`/`.zst`). Unset = share remaining `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` after rolled logs; `0` = unlimited archive bytes (retention days still apply) |
| `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES` | unset | Unset or unparsable: the active file rolls at 256 MiB, or at a quarter of the byte budget when that is smaller (at least 1 MiB). A value: the active file rolls at that size and the cleaner also processes rolled files above it. `0` = no size roll |
| `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` | `32` | Maximum rolled files compressed per cleanup pass (`0` = unlimited); over-budget files beyond this cap are deleted directly without compression |
| `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` | `10000` | Global file-sink event rate limit (events/sec); `0` disables sink-side rate limiting |
| `RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC` | unset | Per-callsite file-sink event rate limit (events/sec) so one noisy site cannot starve others; unset = `(sink_max / 4).max(1)`, `0` = disabled |
| `RUSTFS_OBS_LOG_COMPRESS_OLD_FILES` | `true` | Compress files before deleting |
| `RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL` | `6` | Gzip level `1` (fastest) – `9` (best) |
| `RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM` | `zstd` | Compression codec: `zstd` or `gzip` |
@@ -176,9 +180,9 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
### Disk usage bound
With the defaults the log directory holds at most the byte budget of rolled logs, the same budget of compressed archives, and one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
With the defaults the log directory holds at most the shared `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget across rolled logs and compressed archives combined (or independent rolled and archive budgets when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is set), plus one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled and newly created archives are accounted for in the same pass. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
The bound is not instantaneous: the directory can exceed it by what is written while one cleanup pass runs, archives created by a pass are trimmed by the next one, and a cleaner that compresses more slowly than logs are produced falls behind. Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget and `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, which leaves the active file bounded only by the rotation period. Neither setting limits how fast logs are produced.
To stay bounded under sustained failures or log storms: the file layer attaches a sink-side rate-limiting filter (`RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` with per-callsite fairness isolation); each cleanup pass compresses at most `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` files and directly deletes older mandatory over-budget excess without compression; and if rotation continuously fails, `RollingAppender` sheds active-file writes past a bounded ceiling (2x roll size on transient failures, tightened to 1x after 3 consecutive failures) until rotation recovers. The bound is still not instantaneous (bytes written while a cleanup pass runs can transiently exceed it). Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget, `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, and `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC=0` disables sink-side rate limiting.
The cleaner recognizes only its own process's active file. Do not let two processes write log files that match the same pattern in one directory: a file another process is still writing looks like a rolled log, and the minimum file age no longer shields it once the budget is exceeded.
@@ -200,6 +204,8 @@ The log rotation and cleanup pipeline emits these metrics (via the `metrics` fac
| `rustfs_log_cleaner_rotation_failures_total` | counter | Failed file rotations |
| `rustfs_log_cleaner_rotation_duration_seconds` | histogram | Rotation latency |
| `rustfs_log_cleaner_active_file_size_bytes` | gauge | Current active log file size |
| `rustfs_log_cleaner_rotation_dropped_bytes_total` | counter | Bytes shed by the rolling appender when continuous rotation failure hits the active-file cap |
| `rustfs_log_cleaner_sink_dropped_events_total` | counter | File-sink log events shed by the sink-side rate limiter |
These metrics cover compression, cleanup, and file rotation end-to-end.
+216 -45
View File
@@ -31,6 +31,7 @@ use crossbeam_deque::{Injector, Steal, Stealer, Worker};
use crossbeam_utils::{Backoff, thread};
use metrics::{counter, gauge, histogram};
use rustfs_config::DEFAULT_LOG_KEEP_FILES;
use rustfs_config::observability::DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -56,10 +57,20 @@ fn compressed_file_retention_window(days: u64) -> Duration {
struct CompressionTaskResult {
/// Original file metadata so successful workers can be deleted later.
file: FileInfo,
/// Archive created on disk (absent in dry-run mode or on compression error).
archive: Option<FileInfo>,
/// Whether compression completed successfully for this file.
compressed: bool,
}
#[derive(Debug, Default)]
struct BatchProcessOutcome {
deleted_files: usize,
freed_bytes: u64,
deleted_source_bytes: u64,
created_archives: Vec<FileInfo>,
}
/// Log-file lifecycle manager.
///
/// A cleaner instance is immutable after construction and therefore safe to
@@ -76,10 +87,19 @@ pub struct LogCleaner {
pub(super) match_mode: FileMatchMode,
/// Maximum number of newest regular log files to keep.
pub(super) keep_files: usize,
/// Optional cap for the cumulative size of regular logs.
/// Optional cap for the cumulative size of regular logs (and shared with
/// compressed archives when `max_archive_size_bytes` is `None`).
pub(super) max_total_size_bytes: u64,
/// Optional dedicated byte budget for compressed archives.
/// - `None`: archives share the remaining `max_total_size_bytes` budget
/// after surviving rolled logs are accounted for.
/// - `Some(0)`: unlimited archive bytes (retention days still apply).
/// - `Some(cap)`: independent archive byte budget `cap`.
pub(super) max_archive_size_bytes: Option<u64>,
/// Optional cap for an individual regular log file.
pub(super) max_single_file_size_bytes: u64,
/// Maximum regular logs compressed in a single cleanup pass (`0` = unlimited).
pub(super) max_compress_files_per_pass: usize,
/// Whether selected regular logs should be compressed before deletion.
pub(super) compress_old_files: bool,
/// Gzip compression level used when gzip is selected or used as fallback.
@@ -163,24 +183,26 @@ impl LogCleaner {
)?;
logs.sort_by_key(|f| f.modified);
let aged_rolled_bytes: u64 = logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let recent_rolled_bytes: u64 = recent_logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let all_rolled_bytes = aged_rolled_bytes.saturating_add(recent_rolled_bytes);
let mut to_delete = Vec::new();
if !logs.is_empty() {
let total_size: u64 = logs.iter().map(|f| f.size).sum();
info!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
state = "scan_completed",
regular_log_files = logs.len(),
total_bytes = total_size,
total_megabytes = total_size as f64 / 1024.0 / 1024.0,
total_bytes = aged_rolled_bytes,
total_megabytes = aged_rolled_bytes as f64 / 1024.0 / 1024.0,
"log cleaner state changed"
);
// Select the oldest files first, then additionally trim any files
// that still violate configured size constraints.
to_delete = self.select_files_to_process(&logs, total_size);
to_delete = self.select_files_to_process(&logs, aged_rolled_bytes);
}
// `min_file_age_seconds` keeps freshly rolled files readable for a
@@ -201,20 +223,57 @@ impl LogCleaner {
to_delete.extend(over_budget);
}
let mut deleted_source_bytes = 0u64;
if !to_delete.is_empty() {
let (deleted, freed) = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_delete)?
} else {
self.serial_compress_and_delete(&to_delete)?
};
total_deleted += deleted;
total_freed += freed;
// Sort oldest-first so per-pass compression capping and direct
// over-budget eviction stay deterministic.
to_delete.sort_by_key(|f| f.modified);
let (to_compress, to_direct_delete) = self.partition_files_for_pass(&to_delete, all_rolled_bytes);
if !to_direct_delete.is_empty() {
warn!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
result = "compression_cap_bypassed_over_budget",
compressed_files = to_compress.len(),
direct_deleted_files = to_direct_delete.len(),
max_compress_files_per_pass = self.max_compress_files_per_pass,
max_total_size_bytes = self.max_total_size_bytes,
"log cleaner state changed"
);
let (deleted, freed, source_bytes) = self.delete_files_with_source_bytes(&to_direct_delete)?;
total_deleted += deleted;
total_freed += freed;
deleted_source_bytes = deleted_source_bytes.saturating_add(source_bytes);
}
if !to_compress.is_empty() {
let outcome = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_compress)?
} else {
self.serial_compress_and_delete(&to_compress)?
};
total_deleted += outcome.deleted_files;
total_freed += outcome.freed_bytes;
deleted_source_bytes = deleted_source_bytes.saturating_add(outcome.deleted_source_bytes);
for archive in outcome.created_archives {
if let Some(existing) = compressed_archives.iter_mut().find(|entry| entry.path == archive.path) {
*existing = archive;
} else {
compressed_archives.push(archive);
}
}
}
}
let surviving_rolled_bytes = all_rolled_bytes.saturating_sub(deleted_source_bytes);
let effective_archive_budget = self.effective_archive_budget(surviving_rolled_bytes);
if !compressed_archives.is_empty() {
let to_delete = self.select_archives_to_delete(&mut compressed_archives);
let to_delete = self.select_archives_to_delete(&mut compressed_archives, effective_archive_budget);
if !to_delete.is_empty() {
let (d, f) = self.delete_files(&to_delete)?;
let (d, f, _) = self.delete_files_with_source_bytes(&to_delete)?;
total_deleted += d;
total_freed += f;
}
@@ -309,16 +368,73 @@ impl LogCleaner {
to_delete
}
/// Partition selected regular logs into `(compress_and_delete, direct_delete)`
/// while enforcing `max_compress_files_per_pass` when compression is active.
///
/// - Under the byte budget: compresses at most `max_compress_files_per_pass`
/// files and defers the rest to subsequent cleanup passes so CPU spikes
/// are amortized across ticks.
/// - Over the byte budget: compresses the newest `max_compress_files_per_pass`
/// mandatory files and directly deletes older mandatory excess files
/// without compression so the disk budget is enforced in a single pass.
fn partition_files_for_pass(&self, sorted_candidates: &[FileInfo], all_rolled_bytes: u64) -> (Vec<FileInfo>, Vec<FileInfo>) {
if !self.compress_old_files
|| self.max_compress_files_per_pass == 0
|| sorted_candidates.len() <= self.max_compress_files_per_pass
{
return (sorted_candidates.to_vec(), Vec::new());
}
let cap = self.max_compress_files_per_pass;
if self.max_total_size_bytes == 0 {
return (sorted_candidates[..cap].to_vec(), Vec::new());
}
// Compute how many oldest candidates must be evicted right now to bring
// rolled logs back under `max_total_size_bytes`.
let mut remaining = all_rolled_bytes;
let mut mandatory_count = 0usize;
for file in sorted_candidates {
if remaining <= self.max_total_size_bytes {
break;
}
remaining = remaining.saturating_sub(file.size);
mandatory_count += 1;
}
if mandatory_count <= cap {
// Compressing `cap` files already satisfies the byte budget; defer
// any additional keep_files/single-file candidates to later passes.
(sorted_candidates[..cap].to_vec(), Vec::new())
} else {
let direct_count = mandatory_count - cap;
let direct = sorted_candidates[..direct_count].to_vec();
let compress = sorted_candidates[direct_count..mandatory_count].to_vec();
(compress, direct)
}
}
/// Compute the effective byte budget applied to compressed archives.
///
/// - Explicit `Some(0)`: unlimited archive bytes (retention days still apply).
/// - Explicit `Some(cap)`: dedicated archive byte cap independent of rolled logs.
/// - Unset (`None`) with `max_total_size_bytes > 0`: shares the remaining
/// `max_total_size_bytes` budget after `surviving_rolled_bytes` so rolled
/// logs + archives stay within the single configured total budget.
/// - Unset (`None`) with `max_total_size_bytes == 0`: unlimited.
fn effective_archive_budget(&self, surviving_rolled_bytes: u64) -> Option<u64> {
match self.max_archive_size_bytes {
Some(0) => None,
Some(cap) => Some(cap),
None if self.max_total_size_bytes > 0 => Some(self.max_total_size_bytes.saturating_sub(surviving_rolled_bytes)),
None => None,
}
}
/// Select compressed archives to delete: those older than the retention
/// window, plus — regardless of retention — the oldest archives needed to
/// bring the archive set back under `max_total_size_bytes`.
///
/// The byte cap is the crucial part: with `compressed_file_retention_days`
/// set to 0 (retention disabled) and compression enabled, age-based expiry
/// never fires, so without this cap archives would grow without bound (the
/// cap on regular logs does not cover them). Bounding the archive set by the
/// same byte budget keeps disk usage finite even when retention is off.
fn select_archives_to_delete(&self, files: &mut [FileInfo]) -> Vec<FileInfo> {
/// bring the archive set back under `effective_archive_budget`.
fn select_archives_to_delete(&self, files: &mut [FileInfo], effective_archive_budget: Option<u64>) -> Vec<FileInfo> {
if self.compressed_file_retention_days > MAX_RETENTION_DAYS_BEFORE_SATURATION {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -352,8 +468,8 @@ impl LogCleaner {
}
// 2. Byte-cap trim: drop the oldest surviving archives until the set
// fits under the configured total. 0 means "no cap".
if self.max_total_size_bytes > 0 {
// fits under `effective_archive_budget`. `None` means "no byte cap".
if let Some(archive_budget) = effective_archive_budget {
let mut remaining: u64 = files
.iter()
.enumerate()
@@ -361,7 +477,7 @@ impl LogCleaner {
.map(|(_, file)| file.size)
.sum();
for (idx, file) in files.iter().enumerate() {
if remaining <= self.max_total_size_bytes {
if remaining <= archive_budget {
break;
}
if selected[idx] {
@@ -387,7 +503,7 @@ impl LogCleaner {
/// Compression workers only decide whether an archive was created; the main
/// thread remains responsible for actual source removal so deletion policy
/// and error reporting stay deterministic.
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
if files.len() <= 1 {
return self.serial_compress_and_delete(files);
}
@@ -484,7 +600,7 @@ impl LogCleaner {
// starts from a cheap spin again.
backoff.reset();
let mut file = file;
let compressed = match compress_file(&file.path, &options) {
let (compressed, archive) = match compress_file(&file.path, &options) {
Ok(output) => {
debug!(
event = EVENT_LOG_CLEANER_STATE,
@@ -499,15 +615,21 @@ impl LogCleaner {
"log cleaner state changed"
);
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
true
let archive = (!options.dry_run).then(|| FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
(true, archive)
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "parallel_compression_failed", "log cleaner state changed");
false
(false, None)
}
};
if tx.send(CompressionTaskResult { file, compressed }).is_err() {
if tx.send(CompressionTaskResult { file, archive, compressed }).is_err() {
break;
}
}
@@ -516,18 +638,22 @@ impl LogCleaner {
drop(tx);
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
for result in rx {
if result.compressed {
deletable.push(result.file);
if let Some(archive) = result.archive {
created_archives.push(archive);
}
}
}
deletable
(deletable, created_archives)
});
// Any worker panic triggers deterministic fallback behavior.
let deletable = match scope_result {
Ok(deletable) => deletable,
let (deletable, created_archives) = match scope_result {
Ok(outcome) => outcome,
Err(_) => {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -541,7 +667,7 @@ impl LogCleaner {
}
};
let (deleted, freed) = self.delete_files(&deletable)?;
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
let elapsed = started_at.elapsed().as_secs_f64();
// NOTE on metric scope: attempts/successes count only *victim* steals
// (not the injector `steal_batch_and_pop`), and a multi-task stolen
@@ -576,7 +702,12 @@ impl LogCleaner {
"log cleaner state changed"
);
Ok((deleted, freed))
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
}
/// Attempt to steal a task from peer workers using randomized victim order.
@@ -620,9 +751,10 @@ impl LogCleaner {
///
/// This path is also used whenever the task set is too small to benefit
/// from worker orchestration.
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
let started_at = Instant::now();
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
if self.compress_old_files {
let options = self.compression_options();
@@ -644,6 +776,14 @@ impl LogCleaner {
let mut file = file.clone();
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
deletable.push(file);
if !options.dry_run {
created_archives.push(FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
}
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "serial_compression_failed", "log cleaner state changed");
@@ -654,10 +794,15 @@ impl LogCleaner {
deletable.extend(files.iter().cloned());
}
let (deleted, freed) = self.delete_files(&deletable)?;
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
histogram!(METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS).record(started_at.elapsed().as_secs_f64());
Ok((deleted, freed))
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
}
/// Snapshot compression-related configuration for a single cleanup pass.
@@ -708,26 +853,30 @@ impl LogCleaner {
}
}
/// Delete the supplied files and return `(deleted_count, freed_bytes)`.
/// Delete the supplied files and return
/// `(deleted_count, freed_bytes, deleted_source_bytes)`.
///
/// In dry-run mode the returned counters still reflect the projected work
/// so callers and metrics can report what would have happened.
pub(super) fn delete_files(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn delete_files_with_source_bytes(&self, files: &[FileInfo]) -> Result<(usize, u64, u64), std::io::Error> {
let mut deleted = 0usize;
let mut freed = 0u64;
let mut source_bytes = 0u64;
for f in files {
if self.dry_run {
info!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_delete", file = ?f.path, bytes = f.size, "log cleaner state changed");
deleted += 1;
freed += f.projected_freed_bytes;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
continue;
}
match self.secure_delete(&f.path) {
Ok(()) => {
deleted += 1;
freed += f.projected_freed_bytes;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
debug!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "deleted", file = ?f.path, bytes = f.size, projected_freed_bytes = f.projected_freed_bytes, "log cleaner state changed");
}
Err(e) => {
@@ -746,7 +895,7 @@ impl LogCleaner {
let _ = dir.sync_all();
}
Ok((deleted, freed))
Ok((deleted, freed, source_bytes))
}
}
@@ -761,7 +910,9 @@ pub struct LogCleanerBuilder {
match_mode: FileMatchMode,
keep_files: usize,
max_total_size_bytes: u64,
max_archive_size_bytes: Option<u64>,
max_single_file_size_bytes: u64,
max_compress_files_per_pass: usize,
compress_old_files: bool,
gzip_compression_level: u32,
compressed_file_retention_days: u64,
@@ -787,7 +938,9 @@ impl LogCleanerBuilder {
match_mode: FileMatchMode::Prefix,
keep_files: DEFAULT_LOG_KEEP_FILES,
max_total_size_bytes: 0,
max_archive_size_bytes: None,
max_single_file_size_bytes: 0,
max_compress_files_per_pass: DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
compress_old_files: false,
gzip_compression_level: 6,
compressed_file_retention_days: 0,
@@ -816,18 +969,34 @@ impl LogCleanerBuilder {
self
}
/// Cap the aggregate size of retained regular log files.
/// Cap the aggregate size of retained regular log files (and compressed
/// archives when `max_archive_size_bytes` is unset).
pub fn max_total_size_bytes(mut self, max_total_size_bytes: u64) -> Self {
self.max_total_size_bytes = max_total_size_bytes;
self
}
/// Set a dedicated byte budget for compressed archives independent of
/// `max_total_size_bytes`. Pass `None` to share `max_total_size_bytes`,
/// `Some(0)` for unlimited archive bytes, or `Some(cap)` for a separate cap.
pub fn max_archive_size_bytes(mut self, max_archive_size_bytes: Option<u64>) -> Self {
self.max_archive_size_bytes = max_archive_size_bytes;
self
}
/// Cap the size of any individual regular log file.
pub fn max_single_file_size_bytes(mut self, max_single_file_size_bytes: u64) -> Self {
self.max_single_file_size_bytes = max_single_file_size_bytes;
self
}
/// Cap how many rolled log files may be compressed in a single cleanup pass
/// (`0` = unlimited).
pub fn max_compress_files_per_pass(mut self, max_compress_files_per_pass: usize) -> Self {
self.max_compress_files_per_pass = max_compress_files_per_pass;
self
}
/// Enable archival compression before deleting selected source logs.
pub fn compress_old_files(mut self, compress_old_files: bool) -> Self {
self.compress_old_files = compress_old_files;
@@ -959,7 +1128,9 @@ impl LogCleanerBuilder {
match_mode: self.match_mode,
keep_files: self.keep_files,
max_total_size_bytes: self.max_total_size_bytes,
max_archive_size_bytes: self.max_archive_size_bytes,
max_single_file_size_bytes: self.max_single_file_size_bytes,
max_compress_files_per_pass: self.max_compress_files_per_pass,
compress_old_files: self.compress_old_files,
// gzip level 0 is a valid "store" (no compression) mode, so keep the
// lower bound at 0 rather than silently bumping it to 1.
+186
View File
@@ -743,4 +743,190 @@ mod tests {
assert_eq!(std::fs::metadata(&gz)?.len(), archive_len, "existing valid archive unchanged");
Ok(())
}
/// P2-6: under the byte budget, a single cleanup pass compresses at most
/// `max_compress_files_per_pass` rolled files and defers the remaining
/// backlog to subsequent passes instead of spiking CPU.
#[test]
fn single_pass_compression_cap_defers_under_budget_backlog() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..5u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((10 - i) * 60));
}
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(0)
.max_total_size_bytes(0)
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted_pass_1, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_1, 2, "first pass must compress at most 2 files");
assert!(dir.join("app.log.2024-01-00.gz").exists());
assert!(dir.join("app.log.2024-01-01.gz").exists());
for i in 2..5 {
assert!(
dir.join(format!("app.log.2024-01-0{i}")).exists(),
"deferred file {i} must wait for a later pass"
);
assert!(!dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
let (deleted_pass_2, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_2, 2, "second pass compresses the next 2 files");
let (deleted_pass_3, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_3, 1, "third pass finishes the backlog");
Ok(())
}
/// P2-6 under storm pressure: when rolled files exceed `max_total_size_bytes`,
/// at most `max_compress_files_per_pass` files are compressed and older
/// mandatory over-budget files are deleted directly so the disk cap holds in
/// one pass without unbounded CPU work.
#[test]
fn single_pass_compression_cap_evicts_over_budget_excess_without_compressing() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..6u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((60 - i * 5) * 60));
}
// 6 KiB rolled, 2 KiB rolled budget -> 4 files must be evicted immediately.
// Separate archive budget keeps the 2 created archives visible for assertion.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(10 * 1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 4, "all 4 over-budget files must be removed in one pass");
// Oldest 2 deleted directly without compression.
for i in 0..2 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(
!dir.join(format!("app.log.2024-01-0{i}.gz")).exists(),
"excess over-budget file {i} must bypass compression"
);
}
// Newest 2 of the evicted 4 are compressed (respecting cap=2).
for i in 2..4 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
// Newest 2 remain as plain rolled logs within the 2 KiB budget.
for i in 4..6 {
assert!(dir.join(format!("app.log.2024-01-0{i}")).exists());
}
Ok(())
}
/// When `max_archive_size_bytes` is unset, rolled logs and compressed
/// archives share the single `max_total_size_bytes` ceiling instead of each
/// consuming up to `max_total_size_bytes` independently.
#[test]
fn shared_total_budget_bounds_rolled_logs_and_archives_together() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-03"), Duration::from_secs(100));
set_mtime_ago(&dir.join("app.log.2024-01-04"), Duration::from_secs(50));
// 2 KiB rolled + 2 KiB archives = 4 KiB total; shared budget is 3 KiB.
// Rolled logs (2 KiB) fit, leaving 1 KiB for archives -> oldest archive goes.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(3 * 1024)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 1, "oldest archive must be trimmed to keep rolled+archives <= total budget");
assert!(!dir.join("app.log.2024-01-01.gz").exists());
assert!(dir.join("app.log.2024-01-02.gz").exists());
assert!(dir.join("app.log.2024-01-03").exists());
assert!(dir.join("app.log.2024-01-04").exists());
Ok(())
}
/// Setting `max_archive_size_bytes(Some(cap))` enforces separate rolled-log
/// and archive budgets independently, including archives created in the same
/// cleanup pass.
#[test]
fn explicit_separate_archive_budget_applies_independently_and_same_pass() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
// Rolled logs fit inside 2 KiB rolled budget while separate archive budget is 3 KiB.
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(3 * 1024))
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
assert_eq!(
cleaner.cleanup()?,
(0, 0),
"both rolled (2 KiB <= 2 KiB) and archives (2 KiB <= 3 KiB) fit their separate budgets"
);
// Now tighten the separate archive budget to 1024 bytes while compressing a new log in the same pass.
create_log_file(&dir, "app.log.2024-01-00", 2048)?;
set_mtime_ago(&dir.join("app.log.2024-01-00"), Duration::from_secs(400));
let tight = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(2)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let _ = tight.cleanup()?;
let archive_bytes: u64 = std::fs::read_dir(&dir)?
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().ends_with(".gz"))
.map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
.sum();
assert!(
archive_bytes <= 1024,
"same-pass newly created archives must obey the archive budget (got {archive_bytes} bytes)"
);
Ok(())
}
}
+83 -14
View File
@@ -26,17 +26,19 @@ use rustfs_config::observability::{
DEFAULT_OBS_ENVIRONMENT_PRODUCTION, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP,
DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS,
ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS,
ENV_OBS_ENVIRONMENT, ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES,
ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES,
ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN, ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME,
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS, ENV_OBS_LOG_PARALLEL_COMPRESS,
ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS, ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS, ENV_OBS_ENVIRONMENT,
ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES, ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS,
ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES, ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN,
ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME, ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS,
ENV_OBS_LOG_PARALLEL_COMPRESS, ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
ENV_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, ENV_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOGGER_LEVEL, ENV_OBS_LOGS_EXPORT_ENABLED,
ENV_OBS_METER_INTERVAL, ENV_OBS_METRIC_ENDPOINT, ENV_OBS_METRICS_EXPORT_ENABLED, ENV_OBS_PROFILING_ENDPOINT,
ENV_OBS_PROFILING_EXPORT_ENABLED, ENV_OBS_SAMPLE_RATIO, ENV_OBS_SERVICE_NAME, ENV_OBS_SERVICE_VERSION, ENV_OBS_TLS_CA_FILE,
@@ -188,14 +190,34 @@ pub struct OtelConfig {
pub log_keep_files: Option<usize>,
// ── Log cleanup ───────────────────────────────────────────────────────────
/// Byte budget for rolled log files, and separately for compressed
/// archives (default: 2 GiB); `0` means no budget. The active file is not
/// counted.
/// Byte budget for rolled log files (and shared with compressed archives
/// when `log_max_archive_size_bytes` is unset); default 2 GiB, `0` = no
/// budget. The active file is not counted.
pub log_max_total_size_bytes: Option<u64>,
/// Optional separate byte budget for compressed archives (`.gz`/`.zst`).
/// When unset, archives share the remaining `log_max_total_size_bytes`
/// budget with surviving rolled logs. `Some(0)` removes the archive byte
/// cap while keeping retention days active.
#[serde(default)]
pub log_max_archive_size_bytes: Option<u64>,
/// Per-file size ceiling (bytes). Unset or unparsable: the active file
/// rolls at 256 MiB (less under a small byte budget) and the cleaner
/// applies no per-file trim. `0`: no size roll and no trim.
pub log_max_single_file_size_bytes: Option<u64>,
/// Maximum rolled log files compressed in a single cleanup pass (default:
/// `32`; `0` = unlimited). Over-budget files beyond this cap are deleted
/// directly without compression so disk usage remains bounded.
#[serde(default)]
pub log_max_compress_files_per_pass: Option<usize>,
/// Global file-sink event rate limit in events/sec (default: `10_000`;
/// `0` = unlimited).
#[serde(default)]
pub log_sink_max_events_per_sec: Option<u64>,
/// Per-callsite file-sink event rate limit in events/sec. Unset defaults
/// to `(log_sink_max_events_per_sec / 4).max(1)`; `0` disables per-callsite
/// isolation while retaining the global sink ceiling.
#[serde(default)]
pub log_sink_per_callsite_max_events_per_sec: Option<u64>,
/// Compress eligible files with gzip before deletion (default: `true`).
pub log_compress_old_files: Option<bool>,
/// Gzip compression level `1`–`9` (default: `6`).
@@ -347,8 +369,19 @@ impl OtelConfig {
log_keep_files,
// Log cleanup
log_max_total_size_bytes: Some(get_env_u64(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES)),
// Unset stays `None`: archives then share the remaining total budget.
log_max_archive_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES),
// Unset stays `None`: the appender and the cleaner default differently.
log_max_single_file_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES),
log_max_compress_files_per_pass: Some(get_env_usize(
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
)),
log_sink_max_events_per_sec: Some(get_env_u64(
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
)),
log_sink_per_callsite_max_events_per_sec: get_env_opt_u64(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC),
log_compress_old_files: Some(get_env_bool(ENV_OBS_LOG_COMPRESS_OLD_FILES, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES)),
log_gzip_compression_level: Some(get_env_u64(
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
@@ -642,4 +675,40 @@ mod tests {
});
});
}
#[test]
fn log_disk_bounds_and_sink_rate_limit_env_defaults_and_overrides() {
with_profiling_env_lock(|| {
temp_env::with_vars_unset(
[
ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES,
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, None);
assert_eq!(config.log_max_compress_files_per_pass, Some(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS));
assert_eq!(config.log_sink_max_events_per_sec, Some(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, None);
},
);
temp_env::with_vars(
[
(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, Some("4096")),
(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, Some("8")),
(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, Some("500")),
(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, Some("100")),
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, Some(4096));
assert_eq!(config.log_max_compress_files_per_pass, Some(8));
assert_eq!(config.log_sink_max_events_per_sec, Some(500));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, Some(100));
},
);
});
}
}
+4
View File
@@ -38,6 +38,8 @@ pub(crate) const METRIC_LOG_CLEANER_ROTATION_TOTAL: &str = "rustfs_log_cleaner_r
pub(crate) const METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL: &str = "rustfs_log_cleaner_rotation_failures_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS: &str = "rustfs_log_cleaner_rotation_duration_seconds";
pub(crate) const METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES: &str = "rustfs_log_cleaner_active_file_size_bytes";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL: &str = "rustfs_log_cleaner_rotation_dropped_bytes_total";
pub(crate) const METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL: &str = "rustfs_log_cleaner_sink_dropped_events_total";
/// Check whether Observability metric is enabled
pub fn observability_metric_enabled() -> bool {
@@ -224,6 +226,8 @@ mod tests {
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES,
METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL,
];
for metric in metrics {
+17 -6
View File
@@ -37,16 +37,17 @@ use crate::cleaner::types::{CompressionAlgorithm, FileMatchMode};
use crate::config::OtelConfig;
use crate::global::{METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL, METRIC_LOG_CLEANER_RUNS_TOTAL, set_observability_metric_enabled};
use crate::telemetry::filter::{build_env_filter, effective_verbose_logging, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::rolling::{RollingAppender, Rotation};
use metrics::counter;
use rustfs_config::observability::{
DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOG_SPAN_EVENTS,
};
use rustfs_config::{APP_NAME, DEFAULT_LOG_KEEP_FILES, DEFAULT_LOG_ROTATION_TIME};
use rustfs_utils::get_env_str;
@@ -516,8 +517,12 @@ fn init_file_logging_internal(
let span_list = resolve_span_list(logger_level);
// File output stays machine-readable and free of ANSI sequences so the
// resulting files are safe to parse or ship to log processors.
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
// resulting files are safe to parse or ship to log processors, guarded by
// the sink-side rate limiter against unthrottled log storms.
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
// Optional stdout mirror: enabled explicitly via `log_stdout_enabled`, or
// unconditionally in non-production environments so developers still see
@@ -703,7 +708,11 @@ pub fn spawn_cleanup_task(
let max_total_size = config
.log_max_total_size_bytes
.unwrap_or(DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES);
let max_archive_size = config.log_max_archive_size_bytes;
let max_single_file_size = resolve_cleanup_single_file_limit(config);
let max_compress_files_per_pass = config
.log_max_compress_files_per_pass
.unwrap_or(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS);
let compress = config.log_compress_old_files.unwrap_or(DEFAULT_OBS_LOG_COMPRESS_OLD_FILES);
let gzip_level = config
.log_gzip_compression_level
@@ -743,7 +752,9 @@ pub fn spawn_cleanup_task(
.match_mode(match_mode)
.keep_files(keep_files)
.max_total_size_bytes(max_total_size)
.max_archive_size_bytes(max_archive_size)
.max_single_file_size_bytes(max_single_file_size)
.max_compress_files_per_pass(max_compress_files_per_pass)
.compress_old_files(compress)
.gzip_compression_level(gzip_level)
// Compression behavior stays fully config-driven, but the builder
+1
View File
@@ -47,6 +47,7 @@ mod guard;
mod http2_ping;
mod local;
mod otel;
mod rate_limit;
mod recorder;
mod resource;
mod rolling;
+5 -1
View File
@@ -42,6 +42,7 @@ use crate::global::set_observability_metric_enabled;
use crate::telemetry::filter::{build_env_filter, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::guard::{OtelGuard, ProfilingAgent};
use crate::telemetry::local::{build_json_log_layer, open_rolling_appender, spawn_cleanup_task};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::recorder::{Recorder, install_process_global_recorder};
use crate::telemetry::resource::build_resource;
use crate::telemetry::rolling::Rotation;
@@ -264,7 +265,10 @@ pub(super) fn init_observability_http(
crate::telemetry::local::validate_stdout_sink(&file_appender)?;
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
let cleanup_handle = spawn_cleanup_task(config, log_directory, log_filename, keep_files, roll_signal);
Ok((file_layer, guard, cleanup_handle, rotation_str))
})();
+445
View File
@@ -0,0 +1,445 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Sink-side rate-limiting tracing layer for file-backed log outputs.
//!
//! Protects on-disk log sinks against unthrottled hot-path log storms even if a
//! call site lacks a dedicated source-side throttle. Wraps only the file layer
//! via [`RateLimitedLayer`] so metrics, traces, and sibling layers remain
//! unaffected.
//!
//! Token accounting executes strictly in [`Layer::on_event`] (never for spans,
//! and only after upstream `EnvFilter` / target filters have admitted the
//! event), using lock-free single-word atomic fixed-window counters:
//! - a global file-sink ceiling across all call sites;
//! - a fixed-size per-callsite fairness table (zero heap growth) so one noisy
//! site cannot starve infrequent errors from other call sites.
use crate::config::OtelConfig;
use crate::global::METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL;
use metrics::counter;
use rustfs_config::observability::DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use tracing::{Dispatch, Event, Metadata, Subscriber, span, subscriber::Interest};
use tracing_subscriber::{Layer, layer::Context, registry::LookupSpan};
/// Number of fixed direct-mapped callsite fairness slots (power of two).
const CALLSITE_SLOTS: usize = 256;
/// Number of low bits reserved for the per-window event counter (`2^24 - 1`).
const COUNT_BITS: u32 = 24;
const COUNT_MASK: u64 = (1u64 << COUNT_BITS) - 1;
const WINDOW_MASK: u64 = (1u64 << (64 - COUNT_BITS)) - 1;
/// Clock abstraction for deterministic, sleep-free unit tests.
trait WindowClock: Send + Sync {
fn current_window(&self) -> u64;
}
struct MonotonicSecondClock {
started: Instant,
}
impl MonotonicSecondClock {
fn new() -> Self {
Self { started: Instant::now() }
}
}
impl WindowClock for MonotonicSecondClock {
fn current_window(&self) -> u64 {
self.started.elapsed().as_secs() & WINDOW_MASK
}
}
/// Lock-free fixed-window counter packed into one `AtomicU64`:
/// upper 40 bits = window index, lower 24 bits = admitted count in that window.
#[derive(Default)]
struct PackedWindowBucket {
state: AtomicU64,
}
impl PackedWindowBucket {
fn try_admit(&self, window: u64, limit: u64) -> bool {
if limit == 0 {
return true;
}
let capped_limit = limit.min(COUNT_MASK);
let window = window & WINDOW_MASK;
let mut packed = self.state.load(Ordering::Acquire);
loop {
let stored_window = packed >> COUNT_BITS;
let stored_count = packed & COUNT_MASK;
let next = if stored_window != window {
(window << COUNT_BITS) | 1
} else if stored_count < capped_limit {
(window << COUNT_BITS) | (stored_count + 1)
} else {
return false;
};
match self
.state
.compare_exchange_weak(packed, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => return true,
Err(observed) => packed = observed,
}
}
}
}
struct RateLimiterState {
global_limit_per_sec: u64,
per_callsite_limit_per_sec: u64,
global_bucket: PackedWindowBucket,
callsite_buckets: Box<[PackedWindowBucket; CALLSITE_SLOTS]>,
dropped_events: AtomicU64,
clock: Box<dyn WindowClock>,
}
/// Lock-free global and per-callsite event rate limiter backing [`RateLimitedLayer`].
#[derive(Clone)]
pub(crate) struct FileSinkRateLimitFilter {
state: Arc<RateLimiterState>,
}
impl FileSinkRateLimitFilter {
/// Construct from [`OtelConfig`] defaults and overrides.
///
/// When `log_sink_max_events_per_sec` is `Some(0)`, sink-side rate limiting
/// is disabled (pass-through). When `log_sink_per_callsite_max_events_per_sec`
/// is unset, each callsite bucket is capped at `(global / 4).max(1)` so a
/// single noisy site cannot exhaust the global sink budget.
pub(crate) fn from_config(config: &OtelConfig) -> Self {
let global_limit = config
.log_sink_max_events_per_sec
.unwrap_or(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC);
let per_callsite_limit = if global_limit == 0 {
0
} else {
config
.log_sink_per_callsite_max_events_per_sec
.unwrap_or_else(|| (global_limit / 4).max(1))
};
Self::new(global_limit, per_callsite_limit)
}
/// Construct with explicit per-second global and per-callsite limits.
pub(crate) fn new(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64) -> Self {
Self::with_clock(global_limit_per_sec, per_callsite_limit_per_sec, Box::new(MonotonicSecondClock::new()))
}
fn with_clock(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64, clock: Box<dyn WindowClock>) -> Self {
let callsite_buckets = Box::new(std::array::from_fn(|_| PackedWindowBucket::default()));
Self {
state: Arc::new(RateLimiterState {
global_limit_per_sec,
per_callsite_limit_per_sec,
global_bucket: PackedWindowBucket::default(),
callsite_buckets,
dropped_events: AtomicU64::new(0),
clock,
}),
}
}
/// Total events shed by this sink filter.
#[cfg(test)]
pub(crate) fn dropped_events(&self) -> u64 {
self.state.dropped_events.load(Ordering::Acquire)
}
fn callsite_slot(meta: &Metadata<'_>) -> usize {
// Deterministic FNV-1a hash of (target, file, line) into
// `[0, CALLSITE_SLOTS)` so slot mapping is stable across runs/ASLR.
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for byte in meta.target().as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h ^= 0xff;
h = h.wrapping_mul(0x0100_0000_01b3);
if let Some(file) = meta.file() {
for byte in file.as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
}
h ^= u64::from(meta.line().unwrap_or(0));
h = h.wrapping_mul(0x0100_0000_01b3);
h ^= h >> 32;
(h as usize) & (CALLSITE_SLOTS - 1)
}
fn allow_event(&self, meta: &Metadata<'_>) -> bool {
if self.state.global_limit_per_sec == 0 && self.state.per_callsite_limit_per_sec == 0 {
return true;
}
let window = self.state.clock.current_window();
// Check per-callsite fairness first so a single stormy site is dropped
// before it can consume the shared global budget reserved for other sites.
if self.state.per_callsite_limit_per_sec > 0 {
let slot = Self::callsite_slot(meta);
if !self.state.callsite_buckets[slot].try_admit(window, self.state.per_callsite_limit_per_sec) {
self.record_drop();
return false;
}
}
if self.state.global_limit_per_sec > 0 && !self.state.global_bucket.try_admit(window, self.state.global_limit_per_sec) {
self.record_drop();
return false;
}
true
}
fn record_drop(&self) {
self.state.dropped_events.fetch_add(1, Ordering::Relaxed);
counter!(METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL).increment(1);
}
}
/// Wrapping [`Layer`] that enforces a [`FileSinkRateLimitFilter`] strictly on
/// `on_event` for its inner file-sink layer while forwarding all span lifecycle
/// hooks untouched.
pub(crate) struct RateLimitedLayer<L> {
inner: L,
limiter: FileSinkRateLimitFilter,
}
impl<L> RateLimitedLayer<L> {
pub(crate) fn new(inner: L, limiter: FileSinkRateLimitFilter) -> Self {
Self { inner, limiter }
}
}
impl<S, L> Layer<S> for RateLimitedLayer<L>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
L: Layer<S>,
{
fn on_register_dispatch(&self, collector: &Dispatch) {
self.inner.on_register_dispatch(collector);
}
fn on_layer(&mut self, subscriber: &mut S) {
self.inner.on_layer(subscriber);
}
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
self.inner.register_callsite(metadata)
}
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
self.inner.enabled(metadata, ctx)
}
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
self.inner.on_record(span, values, ctx);
}
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
self.inner.on_follows_from(span, follows, ctx);
}
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
if self.limiter.allow_event(event.metadata()) {
self.inner.on_event(event, ctx);
}
}
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
self.inner.on_close(id, ctx);
}
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
self.inner.on_id_change(old, new, ctx);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::local::build_json_log_layer;
use std::io;
use std::sync::Mutex;
use tracing_subscriber::{EnvFilter, Registry, fmt::format::FmtSpan, layer::SubscriberExt};
struct ManualClock {
window: Arc<AtomicU64>,
}
impl WindowClock for ManualClock {
fn current_window(&self) -> u64 {
self.window.load(Ordering::Acquire)
}
}
#[derive(Clone, Default)]
struct CaptureWriter {
buf: Arc<Mutex<Vec<u8>>>,
}
struct CaptureGuard(Arc<Mutex<Vec<u8>>>);
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
type Writer = CaptureGuard;
fn make_writer(&'a self) -> Self::Writer {
CaptureGuard(Arc::clone(&self.buf))
}
}
impl io::Write for CaptureGuard {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.0.lock().expect("capture lock").extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl CaptureWriter {
fn lines(&self) -> Vec<String> {
let bytes = self.buf.lock().expect("capture lock").clone();
String::from_utf8(bytes)
.expect("valid UTF-8")
.lines()
.map(str::to_owned)
.collect()
}
}
fn test_filter(global: u64, per_callsite: u64) -> (FileSinkRateLimitFilter, Arc<AtomicU64>) {
let clock = Arc::new(AtomicU64::new(0));
let filter = FileSinkRateLimitFilter::with_clock(
global,
per_callsite,
Box::new(ManualClock {
window: Arc::clone(&clock),
}),
);
(filter, clock)
}
#[test]
fn storm_is_capped_per_window_and_recovers_on_next_window() {
let (filter, clock) = test_filter(5, 5);
let file_writer = CaptureWriter::default();
let stdout_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let stdout_layer = build_json_log_layer(stdout_writer.clone(), false, FmtSpan::NONE, false);
let subscriber = Registry::default().with(file_layer).with(stdout_layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..20 {
tracing::error!(idx, "storm event");
}
clock.store(1, Ordering::Release);
for idx in 0..3 {
tracing::error!(idx, "next window event");
}
});
assert_eq!(file_writer.lines().len(), 8, "5 in window 0 + 3 in window 1");
assert_eq!(filter.dropped_events(), 15, "15 excess storm events dropped");
assert_eq!(
stdout_writer.lines().len(),
23,
"sibling stdout layer must not be throttled by file-sink filter"
);
}
#[test]
fn noisy_callsite_cannot_starve_distinct_critical_callsite() {
let (filter, _clock) = test_filter(10, 3);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!("req", request_id = "req-42");
let _guard = span.enter();
for i in 0..50 {
tracing::warn!(i, "noisy site");
}
tracing::error!("distinct critical site");
});
let lines = file_writer.lines();
assert_eq!(lines.len(), 4, "3 from noisy site + 1 from critical site");
assert!(
lines
.iter()
.any(|line| line.contains("distinct critical site") && line.contains("req-42")),
"distinct callsite must still be logged with intact span request_id: {lines:?}"
);
assert_eq!(filter.dropped_events(), 47);
}
#[test]
fn upstream_env_filter_rejections_consume_zero_sink_budget() {
let (filter, _clock) = test_filter(2, 2);
let file_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(EnvFilter::new("error")).with(file_layer);
tracing::subscriber::with_default(subscriber, || {
for _ in 0..10 {
tracing::info!("filtered out upstream");
}
tracing::error!("first real error");
tracing::error!("second real error");
tracing::error!("third real error over budget");
});
assert_eq!(file_writer.lines().len(), 2);
assert_eq!(filter.dropped_events(), 1);
}
#[test]
fn zero_limits_disable_sink_rate_limiting() {
let (filter, _clock) = test_filter(0, 0);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..25 {
tracing::error!(idx, "unbounded event");
}
});
assert_eq!(file_writer.lines().len(), 25);
assert_eq!(filter.dropped_events(), 0);
}
}
+296 -25
View File
@@ -20,11 +20,12 @@
use crate::cleaner::types::FileMatchMode;
use crate::global::{
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS, METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
};
use jiff::{Timestamp, ZonedDateTime, tz::TimeZone};
use metrics::{counter, gauge, histogram};
use rustfs_config::observability::DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
@@ -50,6 +51,15 @@ pub enum Rotation {
/// timestamp tick.
static ROLL_UNIQUIFIER: AtomicU64 = AtomicU64::new(0);
const ROTATION_RETRY_COOLDOWN: Duration = Duration::from_secs(5);
const ROTATION_RETRY_MAX_COOLDOWN: Duration = Duration::from_secs(60);
/// Consecutive rotation failures after which the appender tightens its active
/// file hard cap instead of allowing a grace overrun.
const ROTATION_FAILURE_HARD_CAP_STREAK: u32 = 3;
/// Emergency grace active-file byte cap applied immediately on rotation
/// failure when size rolling was explicitly disabled (`max_size_bytes == 0`),
/// tightened to `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` once failures
/// reach `ROTATION_FAILURE_HARD_CAP_STREAK`.
const ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES: u64 = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES.saturating_mul(2);
impl Rotation {
fn check_should_roll(&self, last: i64, now: i64) -> bool {
@@ -86,6 +96,10 @@ pub struct RollingAppender {
// Store as seconds since Unix epoch
last_roll_ts: i64,
rotation_retry_cooldown_until: Option<Instant>,
rotation_retry_base_cooldown: Duration,
consecutive_rotation_failures: u32,
dropped_bytes_due_to_rotation_failure: u64,
shedding_warning_emitted_for_streak: bool,
/// Woken after every successful roll so the cleaner can enforce the
/// directory budget on the file that was just rolled.
roll_signal: Option<Arc<tokio::sync::Notify>>,
@@ -136,11 +150,15 @@ impl RollingAppender {
size: 0,
last_roll_ts: ZonedDateTime::now().timestamp().as_second(),
rotation_retry_cooldown_until: None,
rotation_retry_base_cooldown: ROTATION_RETRY_COOLDOWN,
consecutive_rotation_failures: 0,
dropped_bytes_due_to_rotation_failure: 0,
shedding_warning_emitted_for_streak: false,
roll_signal: None,
};
// Eagerly open the file to validate the path and capture accurate
// initial size / last-roll timestamp.
appender.open_file()?;
appender.open_file(true)?;
Ok(appender)
}
@@ -166,7 +184,7 @@ impl RollingAppender {
Ok((metadata.dev(), metadata.ino()))
}
fn open_file(&mut self) -> io::Result<()> {
fn open_file(&mut self, seed_last_roll_ts: bool) -> io::Result<()> {
if self.file.is_some() {
return Ok(());
}
@@ -188,14 +206,17 @@ impl RollingAppender {
let meta = file.metadata()?;
self.size = meta.len();
// Seed `last_roll_ts` from the file's modification time so that a
// process restart correctly triggers time-based rotation if the active
// file belongs to a previous period.
if let Ok(modified) = meta.modified() {
// Convert SystemTime to jiff::Timestamp
if let Ok(ts) = jiff::Timestamp::try_from(modified) {
self.last_roll_ts = ts.as_second();
}
// Seed `last_roll_ts` from the file's modification time only on initial
// startup so a process restart triggers time-based rotation when the
// active file belongs to a previous period. Reopening after a failed
// rotation must preserve `self.last_roll_ts` so subsequent time-based
// rotation retries continue after backoff instead of stalling for the
// rest of the period.
if seed_last_roll_ts
&& let Ok(modified) = meta.modified()
&& let Ok(ts) = jiff::Timestamp::try_from(modified)
{
self.last_roll_ts = ts.as_second();
}
self.file = Some(file);
@@ -222,7 +243,7 @@ impl RollingAppender {
// 1. Size-based check (Cheap, check first)
// If max_size is set (non-zero) and writing would exceed it, roll immediately.
if self.max_size_bytes > 0 && (self.size + write_len) > self.max_size_bytes {
if self.max_size_bytes > 0 && self.size.saturating_add(write_len) > self.max_size_bytes {
return true;
}
@@ -233,6 +254,45 @@ impl RollingAppender {
self.rotation.check_should_roll(self.last_roll_ts, now)
}
/// Hard ceiling enforced on the active log file while rotation is failing.
///
/// A transient rename failure keeps a bounded grace ceiling (`2 * max_size_bytes`,
/// or `ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES` when size rolling is off)
/// from the first failure so brief filesystem locks do not immediately lose logs
/// while still preventing an uncapped window during backoff. Sustained failures
/// (`>= ROTATION_FAILURE_HARD_CAP_STREAK`) tighten the cap to `max_size_bytes`
/// (or `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` when size rolling is off)
/// so an unrotatable file can never exhaust disk space.
fn rotation_failure_hard_cap(&self) -> Option<u64> {
if self.consecutive_rotation_failures == 0 {
return None;
}
if self.max_size_bytes > 0 {
if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(self.max_size_bytes)
} else {
Some(self.max_size_bytes.saturating_mul(2))
}
} else if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES)
} else {
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES)
}
}
fn record_rotation_failure(&mut self, rotate_started: Instant) {
self.consecutive_rotation_failures = self.consecutive_rotation_failures.saturating_add(1);
self.shedding_warning_emitted_for_streak = false;
let shift = self.consecutive_rotation_failures.saturating_sub(1).min(4);
let backoff = self
.rotation_retry_base_cooldown
.saturating_mul(1u32 << shift)
.min(ROTATION_RETRY_MAX_COOLDOWN);
self.rotation_retry_cooldown_until = Some(Instant::now() + backoff);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
}
fn roll(&mut self) -> io::Result<()> {
let rotate_started = std::time::Instant::now();
// 1. Close current file first to ensure all buffers are flushed to OS (if any)
@@ -241,6 +301,7 @@ impl RollingAppender {
&& let Err(e) = file.flush()
{
eprintln!("Failed to flush log file before rotation: {}", e);
self.record_rotation_failure(rotate_started);
return Err(e);
}
@@ -293,13 +354,15 @@ impl RollingAppender {
self.size = 0;
// 5. Re-open (creates new active file)
self.open_file()?;
self.open_file(false)?;
// Explicitly update last_roll_ts to the rotation time.
// This overrides whatever open_file() derived from mtime, ensuring
// we stick to the logical rotation time.
self.last_roll_ts = now.timestamp().as_second();
self.rotation_retry_cooldown_until = None;
self.consecutive_rotation_failures = 0;
self.shedding_warning_emitted_for_streak = false;
counter!(METRIC_LOG_CLEANER_ROTATION_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
gauge!(METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES).set(self.size as f64);
@@ -330,19 +393,18 @@ impl RollingAppender {
}
// 6. Recovery Failure
// If we exhausted retries, we MUST NOT lose log data.
// We re-open the ACTIVE file (which is still there because rename failed).
// The file will grow beyond max_size, but availability > strict sizing.
// Re-open the active file so transient rename errors keep logging up to
// `rotation_failure_hard_cap()`, while sustained failures shed excess
// writes instead of growing the unrotatable file without bound.
eprintln!(
"RollingAppender: Failed to rotate log file after {} retries. Error: {:?}",
MAX_RETRIES, last_error
);
self.rotation_retry_cooldown_until = Some(Instant::now() + ROTATION_RETRY_COOLDOWN);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
self.record_rotation_failure(rotate_started);
// Attempt to re-open existing active file to allow continued writing
self.open_file()?;
// without clobbering `last_roll_ts`.
self.open_file(false)?;
// Return the error so it can be logged/handled, even though we recovered the handle.
Err(last_error.unwrap_or_else(|| io::Error::other("Unknown rename error")))
@@ -353,21 +415,38 @@ impl Write for RollingAppender {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Ensure file is open
if self.file.is_none() {
self.open_file()?;
self.open_file(false)?;
}
// Check rotation
if self.should_roll(buf.len() as u64)
&& let Err(e) = self.roll()
{
// If rotation fails, we log to stderr and try to continue writing to the active file
// to avoid losing logs if possible.
// If rotation fails, we log to stderr and enforce the rotation-failure
// hard ceiling below instead of allowing unbounded disk growth.
eprintln!("RollingAppender: failed to rotate log file: {}", e);
}
// Shed writes above the active-file hard cap while rotation is broken.
if let Some(hard_cap) = self.rotation_failure_hard_cap()
&& self.size.saturating_add(buf.len() as u64) > hard_cap
{
let dropped = buf.len() as u64;
self.dropped_bytes_due_to_rotation_failure = self.dropped_bytes_due_to_rotation_failure.saturating_add(dropped);
counter!(METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL).increment(dropped);
if !self.shedding_warning_emitted_for_streak {
self.shedding_warning_emitted_for_streak = true;
eprintln!(
"RollingAppender: rotation failed {} consecutive times; shedding writes above {} bytes (active size {} bytes, total shed {} bytes) until rotation recovers",
self.consecutive_rotation_failures, hard_cap, self.size, self.dropped_bytes_due_to_rotation_failure
);
}
return Ok(buf.len());
}
// Ensure file is open (in case roll closed it and failed to open new one, or open_file failed above)
if self.file.is_none() {
self.open_file()?;
self.open_file(false)?;
}
if let Some(file) = &mut self.file {
@@ -724,4 +803,196 @@ mod tests {
assert!(!appender.should_roll(1));
}
#[test]
fn continuous_rotation_failure_caps_active_file_growth_and_recovers() {
let tmp = TempDir::new().expect("temp dir");
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)
.expect("create appender");
appender.rotation_retry_base_cooldown = Duration::from_millis(1);
// Fill active file to max_size.
appender.write_all(&[b'a'; 64]).expect("initial write");
assert_eq!(appender.size, 64);
// Simulate a transient first rotation failure: grace cap is 2 * max_size (128 bytes).
appender.record_rotation_failure(Instant::now());
appender.rotation_retry_cooldown_until = Some(Instant::now() + Duration::from_secs(60));
assert_eq!(appender.rotation_failure_hard_cap(), Some(128));
// 32 bytes fit within the 2x grace window.
appender.write_all(&[b'b'; 32]).expect("grace write");
assert_eq!(appender.size, 96);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 0);
// Additional writes that would exceed 2 * max_size must be shed instead of growing disk.
for _ in 0..100 {
appender.write_all(&[b'c'; 64]).expect("shedding returns Ok");
}
appender.flush().expect("flush");
assert!(
fs::metadata(tmp.path().join("app.log")).expect("active meta").len() <= 2 * max_size,
"active file must never exceed 2x max_size while rotation is failing"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 100 * 64);
// Sustained streak (>= 3) tightens cap down to max_size.
appender.record_rotation_failure(Instant::now());
appender.record_rotation_failure(Instant::now());
assert_eq!(appender.rotation_failure_hard_cap(), Some(max_size));
// Once cooldown expires and filesystem allows rename again, rotation recovers cleanly.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered\n").expect("recovered write");
appender.flush().expect("flush after recovery");
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert_eq!(fs::read_to_string(tmp.path().join("app.log")).expect("read active"), "recovered\n");
assert_eq!(count_files(tmp.path()), 2, "recovered rotation must archive previous active file");
}
#[cfg(unix)]
#[test]
fn readonly_directory_rotation_failure_stops_unbounded_file_growth() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let tmp = TempDir::new()?;
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(&[b'x'; 64])?;
appender.flush()?;
// Make the directory non-writable (0o555) while keeping app.log writable (0o644):
// rename() fails with PermissionDenied, while reopening app.log in append mode succeeds.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
// Privileged users (e.g. root in containers) bypass POSIX directory write bits.
if File::create(tmp.path().join(".write-probe")).is_ok() {
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
return Ok(());
}
let write_res = (|| -> io::Result<()> {
for _ in 0..200 {
appender.write_all(&[b'y'; 64])?;
}
appender.flush()
})();
// Always restore directory permissions before asserting / dropping TempDir.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
write_res?;
let final_len = fs::metadata(tmp.path().join("app.log"))?.len();
assert!(
final_len <= 2 * max_size,
"active file grew to {final_len} bytes under continuous rotation failure (cap {})",
2 * max_size
);
assert!(appender.consecutive_rotation_failures >= 1, "rotation failure must be recorded");
assert!(
appender.dropped_bytes_due_to_rotation_failure > 0,
"excess writes must be shed while directory prevents rotation"
);
// Directory is writable again; expire cooldown and verify clean recovery.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"after-recovery\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "after-recovery\n");
Ok(())
}
#[cfg(unix)]
#[test]
fn time_based_rotation_failure_preserves_last_roll_ts_and_caps_when_max_size_zero() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
struct RestoreDirPerms<'a>(&'a Path);
impl Drop for RestoreDirPerms<'_> {
fn drop(&mut self) {
let _ = fs::set_permissions(self.0, fs::Permissions::from_mode(0o755));
}
}
let tmp = TempDir::new()?;
let mut appender = RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Hourly, 0, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(b"seed\n")?;
appender.flush()?;
// Wind `last_roll_ts` back two hours so time-based rotation is due.
let original_last_roll_ts = ZonedDateTime::now().timestamp().as_second() - 7200;
appender.last_roll_ts = original_last_roll_ts;
let _restore = RestoreDirPerms(tmp.path());
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
if File::create(tmp.path().join(".write-probe")).is_ok() {
return Ok(());
}
// Failure #1: `open_file(false)` must NOT clobber `last_roll_ts`, and a
// bounded emergency ceiling must apply immediately from failure #1.
appender.write_all(b"after-failure-1\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 1);
assert_eq!(
appender.last_roll_ts, original_last_roll_ts,
"failed rotation reopen must preserve last_roll_ts so time-based retries keep firing"
);
assert_eq!(
appender.rotation_failure_hard_cap(),
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES),
"max_size_bytes == 0 must enforce a bounded grace cap starting on failure #1"
);
// Expire cooldown and retry twice more; `should_roll` must still fire
// even though the write above updated app.log's mtime to the current hour.
for expected_failures in [2u32, 3u32] {
appender.rotation_retry_cooldown_until = None;
assert!(
appender.should_roll(1),
"time-based rotation must remain due after failure #{}",
expected_failures - 1
);
appender.write_all(b"retry-write\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, expected_failures);
assert_eq!(appender.last_roll_ts, original_last_roll_ts);
}
// Sustained failure (>= 3) tightens the fallback cap and sheds excess writes.
assert_eq!(appender.rotation_failure_hard_cap(), Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES));
let pre_shed_len = fs::metadata(tmp.path().join("app.log"))?.len();
appender.size = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
appender.write_all(&[b'z'; 64])?;
appender.flush()?;
assert_eq!(
fs::metadata(tmp.path().join("app.log"))?.len(),
pre_shed_len,
"writes exceeding tightened fallback cap must be shed without disk growth"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 64);
// Restore writability, expire cooldown, and verify clean time-based recovery.
drop(_restore);
appender.size = pre_shed_len;
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered-hourly\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert!(
appender.last_roll_ts > original_last_roll_ts,
"successful recovery rotation must advance last_roll_ts"
);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "recovered-hourly\n");
assert_eq!(count_files(tmp.path()), 2);
Ok(())
}
}
+35 -1
View File
@@ -85,12 +85,25 @@ impl ActionSet {
/// `NotAction` always uses plain wildcard matching, so `NotAction: "s3:*"`
/// still excludes force-delete. An Allow grants force-delete only when its
/// `Action` list names it: an Allow built from `NotAction` alone never does.
///
/// An Allow built from `NotAction` stays within the action families named in
/// `not_actions`: excluding S3 actions never implies `admin:*`, `sts:*`, or
/// `kms:*` grants even when the statement carries a wildcard resource, while
/// an explicit admin `NotAction` keeps covering sibling admin actions. A Deny
/// keeps its full reach across every action family.
pub fn statement_covers(&self, not_actions: &ActionSet, action: &Action, deny: bool) -> bool {
if not_actions.is_match_for_effect(action, true) {
return false;
}
if self.is_empty() {
return deny || !action_requires_explicit_grant(action);
if not_actions.is_empty() {
return false;
}
if deny {
return true;
}
return !action_requires_explicit_grant(action)
&& not_actions.iter().any(|excluded| same_action_family(excluded, action));
}
self.is_match_for_effect(action, deny)
}
@@ -217,6 +230,16 @@ fn action_requires_explicit_grant(action: &Action) -> bool {
)
}
fn same_action_family(left: &Action, right: &Action) -> bool {
matches!(
(left, right),
(Action::S3Action(_), Action::S3Action(_))
| (Action::AdminAction(_), Action::AdminAction(_))
| (Action::StsAction(_), Action::StsAction(_))
| (Action::KmsAction(_), Action::KmsAction(_))
)
}
impl From<&Action> for &str {
fn from(value: &Action) -> &'static str {
match value {
@@ -645,6 +668,17 @@ pub enum AdminAction {
}
impl AdminAction {
pub(crate) fn is_resource_scoped(&self) -> bool {
self.is_table_resource_scoped()
|| matches!(
self,
AdminAction::SetBucketQuotaAdminAction
| AdminAction::SetBucketTargetAction
| AdminAction::GetBucketTargetAction
| AdminAction::InspectDataAction
)
}
pub(crate) fn is_table_resource_scoped(&self) -> bool {
matches!(
self,
+290
View File
@@ -1466,6 +1466,100 @@ mod test {
Ok(())
}
#[tokio::test]
async fn test_aws_userid_policy_variable_is_issuer_scoped_for_federated_sessions() -> Result<()> {
let resource_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::homes/${aws:userid}/*"]
}
]
}"#,
)?;
let condition_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::homes"],
"Condition": {
"StringLike": {
"s3:prefix": ["${aws:userid}/*"]
}
}
}
]
}"#,
)?;
let empty_conditions = HashMap::new();
// Two federated issuers can emit the same (or wildcard) `sub`; `parent` separates them.
for sub in ["1001", "*"] {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String(sub.to_string()));
claims.insert("parent".to_string(), Value::String("partner-parent".to_string()));
let get_args = |object| Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&get_args("partner-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("corporate-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("1001/file")).await);
for (prefix, expected) in [
("partner-parent/file", true),
("corporate-parent/file", false),
("1001/file", false),
] {
let conditions = HashMap::from([("prefix".to_string(), vec![prefix.to_string()])]);
let list_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::ListBucketAction),
bucket: "homes",
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert_eq!(condition_policy.is_allowed(&list_args).await, expected, "sub={sub} prefix={prefix}");
}
}
// When `parent` is absent, `${aws:userid}` still falls back to `sub`.
let sub_only_claims = HashMap::from([("sub".to_string(), Value::String("legacy-sub".to_string()))]);
let fallback_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object: "legacy-sub/file",
claims: &sub_only_claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&fallback_args).await);
Ok(())
}
#[tokio::test]
async fn test_aws_policy_variables_concatenation() -> Result<()> {
let data = r#"
@@ -2243,6 +2337,107 @@ mod test {
Ok(())
}
#[tokio::test]
async fn test_bucket_and_object_scoped_admin_actions_enforce_resource_bounds() -> Result<()> {
use crate::policy::action::{Action, AdminAction};
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
for (action_name, action) in [
("admin:SetBucketQuota", AdminAction::SetBucketQuotaAdminAction),
("admin:GetBucketTarget", AdminAction::GetBucketTargetAction),
("admin:SetBucketTarget", AdminAction::SetBucketTargetAction),
] {
let scoped_doc = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":["{action_name}"],"Resource":["arn:aws:s3:::allowed-bucket"]}}]}}"#
);
let scoped = Policy::parse_config(scoped_doc.as_bytes())?;
let allowed_args = Args {
account: "testuser",
groups: &groups,
action: Action::AdminAction(action),
bucket: "allowed-bucket",
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert!(
scoped.is_allowed(&allowed_args).await,
"{action_name} must allow the bucket named in Resource"
);
for denied_bucket in ["other-bucket", ""] {
let denied_args = Args {
bucket: denied_bucket,
..allowed_args
};
assert!(
!scoped.is_allowed(&denied_args).await,
"{action_name} scoped to allowed-bucket must deny bucket `{denied_bucket}`"
);
}
let unscoped_doc =
format!(r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":["{action_name}"]}}]}}"#);
let unscoped = Policy::parse_config(unscoped_doc.as_bytes())?;
for bucket in ["allowed-bucket", "other-bucket", ""] {
let args = Args { bucket, ..allowed_args };
assert!(
unscoped.is_allowed(&args).await,
"resource-less {action_name} statement must keep authorizing `{bucket}`"
);
}
}
let inspect_doc = r#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["admin:InspectData"],
"Resource": ["arn:aws:s3:::allowed-bucket/public/*"]
}
]
}"#;
let inspect_policy = Policy::parse_config(inspect_doc.as_bytes())?;
let base_inspect = Args {
account: "testuser",
groups: &groups,
action: Action::AdminAction(AdminAction::InspectDataAction),
bucket: "allowed-bucket",
conditions: &conditions,
is_owner: false,
object: "public/report.txt",
claims: &claims,
deny_only: false,
};
assert!(
inspect_policy.is_allowed(&base_inspect).await,
"InspectData must allow objects under the granted prefix"
);
for (bucket, object) in [
("allowed-bucket", "private/secret.txt"),
("other-bucket", "public/report.txt"),
("", ""),
] {
let denied = Args {
bucket,
object,
..base_inspect
};
assert!(
!inspect_policy.is_allowed(&denied).await,
"InspectData must deny `{bucket}/{object}` outside the granted resource"
);
}
Ok(())
}
#[test]
fn test_sts_statement_without_resource_is_valid() {
let data = r#"
@@ -4337,6 +4532,101 @@ mod test {
assert!(!allows(&deny_all_but("s3:GetObject"), "s3:ForceDeleteObject").await);
}
#[tokio::test]
async fn not_action_allow_does_not_grant_cross_family_actions() {
async fn eval(policy: &Policy, action: &str, bucket: &str, object: &str) -> bool {
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
let args = Args {
account: "user",
groups: &groups,
action: Action::try_from(action).expect("action parses"),
bucket,
conditions: &conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
policy.is_allowed(&args).await
}
// Admin/STS/KMS requests often pass an empty bucket/object (which resolves to
// "/") or a warehouse bucket; an S3 NotAction Allow must never cross into them.
for (resource_clause, bucket, object) in [
(r#""Resource":["arn:aws:s3:::*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::*/*"]"#, "", ""),
(r#""Resource":["*"]"#, "", ""),
(r#""NotResource":["arn:aws:s3:::secret/*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::warehouse","arn:aws:s3:::warehouse/*"]"#, "warehouse", ""),
] {
for not_action in ["s3:DeleteObject", "s3:*"] {
let iam = Policy::parse_config(
format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","NotAction":["{not_action}"],{resource_clause}}}]}}"#
)
.as_bytes(),
)
.expect("NotAction policy parses");
for action in [
"admin:CreateUser",
"admin:AttachUserOrGroupPolicy",
"admin:ListUsers",
"admin:GetTableBucket",
"sts:AssumeRole",
"kms:ListKeys",
"kms:Decrypt",
] {
assert!(
!eval(&iam, action, bucket, object).await,
"IAM NotAction {not_action} with {resource_clause} must not grant {action}"
);
}
}
}
// The same statement still grants non-excluded S3 actions (except force-delete).
let s3_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["s3:DeleteObject"],"Resource":["arn:aws:s3:::*"]}]}"#,
)
.expect("S3 NotAction policy parses");
assert!(allows(&s3_not_delete, "s3:GetObject").await);
assert!(!allows(&s3_not_delete, "s3:DeleteObject").await);
assert!(!allows(&s3_not_delete, "s3:ForceDeleteObject").await);
// An explicit admin NotAction stays confined to admin actions.
let admin_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["admin:DeleteUser"],"Resource":["*"]}]}"#,
)
.expect("admin NotAction policy parses");
assert!(eval(&admin_not_delete, "admin:CreateUser", "", "").await);
assert!(!eval(&admin_not_delete, "admin:DeleteUser", "", "").await);
assert!(!allows(&admin_not_delete, "s3:GetObject").await);
assert!(!eval(&admin_not_delete, "kms:ListKeys", "", "").await);
assert!(!eval(&admin_not_delete, "sts:AssumeRole", "", "").await);
// Deny + NotAction keeps covering every non-excluded action family.
let deny = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["admin:*"]},
{"Effect":"Allow","Action":["kms:*"]},
{"Effect":"Allow","Action":["sts:*"]},
{"Effect":"Deny","NotAction":["s3:GetObject"],"Resource":["arn:aws:s3:::*"]}
]}"#,
)
.expect("deny NotAction policy parses");
assert!(!eval(&deny, "admin:CreateUser", "", "").await);
assert!(!eval(&deny, "kms:ListKeys", "", "").await);
assert!(!eval(&deny, "sts:AssumeRole", "", "").await);
// An empty ActionSet paired with an empty NotAction fails closed.
let empty = crate::policy::ActionSet::default();
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), false));
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), true));
}
async fn bucket_allows(policy: &BucketPolicy, action: &str) -> bool {
let conditions = HashMap::new();
policy
+29
View File
@@ -133,6 +133,13 @@ impl Principal {
}
false
}
/// Returns `true` when the principal admits callers it does not name, matching
/// either the wildcard account `"*"` or the empty account `""` used to evaluate
/// unauthenticated requests.
pub fn is_public(&self) -> bool {
self.is_match("*") || self.is_match("")
}
}
impl Validator for Principal {
@@ -236,4 +243,26 @@ mod test {
assert!(!principal.is_match("logging.s3.amazonaws.com"));
assert!(!principal.is_match("other-principal"));
}
#[test_case(r#""*""#, true ; "wildcard_string")]
#[test_case(r#"{"AWS": ["*"]}"#, true ; "aws_wildcard")]
#[test_case(r#"{"AWS": "**"}"#, true ; "aws_double_wildcard")]
#[test_case(r#"{"AWS": "?"}"#, true ; "aws_single_char_wildcard")]
#[test_case(r#"{"AWS": [""]}"#, true ; "aws_empty_array")]
#[test_case(r#"{"AWS": ""}"#, true ; "aws_empty_string")]
#[test_case(r#"{"AWS": ["alice", ""]}"#, true ; "aws_named_and_empty")]
#[test_case(r#"{"AWS": ["?nobody"]}"#, true ; "aws_leading_question_mark")]
#[test_case(r#"{"AWS": ["*?nobody"]}"#, true ; "aws_star_question_mark")]
#[test_case(r#"{"AWS": ["alice"]}"#, false ; "aws_named")]
#[test_case(r#"{"AWS": ["alice*"]}"#, false ; "aws_named_prefix")]
#[test_case(r#"{"AWS": ["arn:aws:iam::123456789012:root"]}"#, false ; "aws_arn")]
#[test_case(r#"{"Service": ""}"#, false ; "service_empty")]
#[test_case(r#"{"Service": "logging.s3.amazonaws.com"}"#, false ; "service_named")]
fn test_principal_is_public(json: &str, expected: bool) {
let principal: Principal = serde_json::from_str(json).expect("Should parse");
assert_eq!(principal.is_public(), expected, "input: {json}");
// Unauthenticated requests are evaluated under the empty account; any principal
// matching it must be classified as public.
assert!(!principal.is_match("") || principal.is_public(), "input: {json}");
}
}
+1 -1
View File
@@ -144,7 +144,7 @@ impl Statement {
return false;
}
!matches!(args.action, Action::AdminAction(action) if action.is_table_resource_scoped())
!matches!(args.action, Action::AdminAction(action) if action.is_resource_scoped())
}
fn is_kms(&self) -> bool {
+177 -14
View File
@@ -72,38 +72,201 @@ fn inner_match(pattern: impl AsRef<str>, name: impl AsRef<str>, simple: bool) ->
}
fn deep_match(mut pattern: &[u8], mut name: &[u8], simple: bool) -> bool {
while !pattern.is_empty() {
match pattern[0] {
// Fast path: match literal and `?` prefix without heap allocation.
while let Some(&p) = pattern.first() {
match p {
b'*' => break,
b'?' => {
if name.is_empty() {
return simple;
}
name = &name[1..];
pattern = &pattern[1..];
}
b'*' => {
return pattern.len() == 1
|| deep_match(&pattern[1..], name, simple)
|| (!name.is_empty() && deep_match(pattern, &name[1..], simple));
}
_ => {
if name.is_empty() || name[0] != pattern[0] {
if name.first() != Some(&p) {
return false;
}
name = &name[1..];
pattern = &pattern[1..];
}
}
}
if pattern.is_empty() {
return name.is_empty();
}
// Collapse consecutive leading `*` tokens; a trailing run matches everything.
while pattern.first() == Some(&b'*') {
pattern = &pattern[1..];
}
if pattern.is_empty() {
return true;
}
// Allocation-free fast paths when no further `*` remains in the pattern.
if !pattern.contains(&b'*') {
if !pattern.contains(&b'?') {
return name.ends_with(pattern);
}
if !simple {
return name.len() >= pattern.len()
&& pattern
.iter()
.zip(&name[name.len() - pattern.len()..])
.all(|(&p, &c)| p == b'?' || p == c);
}
}
star_match(pattern, name, simple)
}
/// Iteratively matches the remainder of a pattern immediately following a `*`.
///
/// Maintains reachable positions in `name` (`O(name.len())` space independent of
/// `pattern.len()`) and collapses consecutive `*` tokens in `O(1)` each, avoiding
/// both exponential backtracking and recursion stack growth.
fn star_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
let n = name.len();
// dp[j]: the pattern prefix processed so far (starting from the leading `*`)
// matches `name[..j]`.
let mut dp = vec![true; n + 1];
let mut prev_was_star = true;
for &p in pattern {
match p {
b'*' => {
if prev_was_star {
continue;
}
prev_was_star = true;
let Some(first) = dp.iter().position(|&matched| matched) else {
return false;
};
dp[first..].fill(true);
}
b'?' => {
prev_was_star = false;
// In simple mode, reaching `?` when `name` is exhausted accepts
// whatever follows in `pattern`.
if simple && dp[n] {
return true;
}
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1];
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
literal => {
prev_was_star = false;
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1] && name[j - 1] == literal;
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
}
name = &name[1..];
pattern = &pattern[1..];
}
name.is_empty() && pattern.is_empty()
dp[n]
}
#[cfg(test)]
mod tests {
use super::{is_match, is_match_as_pattern_prefix, is_simple_match};
#[test]
fn many_wildcards_match_without_backtracking() {
let name = format!("vault/{}", "a".repeat(1000));
let pattern = format!("vault/{}", "*a".repeat(100));
assert!(is_match(&pattern, &name));
assert!(is_simple_match(&pattern, &name));
assert!(!is_match(format!("{pattern}*b"), &name));
assert!(!is_simple_match(format!("{pattern}*b"), &name));
let repeated = format!("{}*b", "a*".repeat(80));
let aaa = "a".repeat(800);
assert!(!is_match(&repeated, &aaa));
assert!(!is_simple_match(&repeated, &aaa));
}
#[test]
fn deep_star_runs_do_not_overflow_stack() {
let stars = "*".repeat(200_000);
assert!(is_match(&stars, "tenant-bkt/report.txt"));
assert!(is_simple_match(&stars, "tenant-bkt/report.txt"));
let stars_suffix = format!("{stars}x");
let long_name = "a".repeat(1024);
assert!(!is_match(&stars_suffix, &long_name));
assert!(!is_simple_match(&stars_suffix, &long_name));
assert!(is_match(&stars_suffix, format!("{long_name}x")));
let middle_stars = format!("a{}b{}c", "*".repeat(50_000), "*".repeat(50_000));
assert!(is_match(&middle_stars, format!("a{}b{}c", "x".repeat(200), "y".repeat(200))));
assert!(!is_match(&middle_stars, format!("a{}c", "x".repeat(200))));
}
#[test]
fn utf8_multibyte_patterns_and_names_match() {
assert!(is_match("桶/目录/*文档*", "桶/目录/2026年文档.txt"));
assert!(!is_match("桶/目录/*文档*", "桶/目录/2026年表格.txt"));
assert!(is_match("café*naïve", "café-et-naïve"));
assert!(!is_match("café*naïve", "café-et-naive"));
assert!(is_simple_match("*🎉*🚀", "prefix🎉mid🚀"));
assert!(!is_simple_match("*🎉*🚀", "prefix🎉mid"));
}
/// Reference backtracking definition used only for small exhaustive equivalence checks.
fn backtracking_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
match pattern.split_first() {
None => name.is_empty(),
Some((b'*', rest)) => {
backtracking_match(rest, name, simple) || (!name.is_empty() && backtracking_match(pattern, &name[1..], simple))
}
Some((b'?', _)) if name.is_empty() => simple,
Some((&p, rest)) => !name.is_empty() && (p == b'?' || p == name[0]) && backtracking_match(rest, &name[1..], simple),
}
}
fn strings(alphabet: &str, max_len: usize) -> Vec<String> {
let mut all = vec![String::new()];
let mut longest = all.clone();
for _ in 0..max_len {
longest = longest
.iter()
.flat_map(|s| alphabet.chars().map(move |c| format!("{s}{c}")))
.collect();
all.extend_from_slice(&longest);
}
all
}
#[test]
fn agrees_with_backtracking_match() {
let names = strings("ab", 5);
for pattern in strings("ab*?", 5) {
for name in &names {
let expected = |simple| backtracking_match(pattern.as_bytes(), name.as_bytes(), simple);
assert_eq!(is_match(&pattern, name), expected(false), "is_match({pattern:?}, {name:?})");
assert_eq!(is_simple_match(&pattern, name), expected(true), "is_simple_match({pattern:?}, {name:?})");
}
}
}
#[test_case::test_case("*", "s3:GetObject" => true ; "1")]
#[test_case::test_case("", "s3:GetObject" => false ; "2")]
#[test_case::test_case("", "" => true; "3")]
+36 -6
View File
@@ -158,10 +158,16 @@ impl VariableResolver {
self.context.username.clone()
}
/// `parent` is the issuer-scoped identity RustFS authorizes and exposes through the
/// `aws:userid` condition key. A raw federated `sub` is unique only within its issuer,
/// so it must never shadow `parent`.
fn resolve_userid_values(&self) -> Option<Vec<String>> {
self.get_claim_as_strings("parent")
.or_else(|| self.get_claim_as_strings("sub"))
}
fn resolve_userid(&self) -> Option<String> {
self.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent"))
.and_then(|mut vec| vec.pop())
self.resolve_userid_values().and_then(|mut vec| vec.pop())
}
fn resolve_principal_type(&self) -> String {
@@ -238,9 +244,7 @@ impl PolicyVariableResolver for VariableResolver {
match variable_name {
"aws:username" => self.resolve_username().map(|s| vec![s]),
"aws:userid" => self
.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent")),
"aws:userid" => self.resolve_userid_values(),
_ => self.resolve(variable_name).await.map(|s| vec![s]),
}
@@ -481,6 +485,32 @@ mod tests {
assert_eq!(result, vec!["AIDACKCEVSQ6C2EXAMPLE-bucket".to_string()]);
}
#[tokio::test]
async fn test_resolve_aws_variables_userid_prefers_parent_over_sub() {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String("1001".to_string()));
claims.insert("parent".to_string(), Value::String("issuer-scoped-parent".to_string()));
let mut context = VariableContext::new();
context.claims = Some(claims);
let resolver = VariableResolver::new(context.clone());
assert_eq!(resolver.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolver.resolve_multiple("aws:userid").await,
Some(vec!["issuer-scoped-parent".to_string()])
);
let result = resolve_aws_variables("homes/${aws:userid}/*", &resolver).await;
assert_eq!(result, vec!["homes/issuer-scoped-parent/*".to_string()]);
let cached = CachedAwsVariableResolver::new(context);
assert_eq!(cached.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolve_aws_variables("homes/${aws:userid}/*", &cached).await,
vec!["homes/issuer-scoped-parent/*".to_string()]
);
}
#[tokio::test]
async fn test_resolve_aws_variables_with_multiple_variables() {
let mut claims = HashMap::new();
+7
View File
@@ -84,7 +84,9 @@ ftps = ["dep:libunftp", "dep:unftp-core", "dep:rustls", "dep:rustfs-tls-runtime"
swift = [
"dep:rustfs-keystone",
"dep:rustfs-ecstore",
"dep:rustfs-kms",
"dep:rustfs-rio",
"dep:rustfs-sse",
"dep:axum",
"dep:tower",
"dep:regex",
@@ -150,8 +152,10 @@ rustls = { workspace = true, default-features = false, optional = true, features
# Swift specific dependencies (optional)
rustfs-keystone = { workspace = true, optional = true }
rustfs-ecstore = { workspace = true, optional = true }
rustfs-kms = { workspace = true, optional = true }
rustfs-gateway-types = { workspace = true }
rustfs-rio = { workspace = true, optional = true }
rustfs-sse = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
tower = { workspace = true, optional = true, features = ["timeout"] }
regex = { workspace = true, optional = true }
@@ -191,7 +195,10 @@ socket2 = { workspace = true, optional = true, features = ["all"] }
[dev-dependencies]
rcgen = { workspace = true }
tempfile = { workspace = true }
temp-env = { workspace = true }
proptest = "1"
rustfs-data-usage = { workspace = true }
rustfs-madmin = { workspace = true }
rustfs-test-utils = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "time"] }
tokio = { workspace = true, features = ["test-util", "macros", "fs"] }
@@ -32,7 +32,6 @@
#[cfg(feature = "webdav")]
use crate::common::client::s3::SessionCapacityView;
use crate::common::client::s3::{MultipartRequest, StorageBackend};
#[cfg(any(feature = "webdav", feature = "sftp"))]
use crate::common::session::SessionContext;
use async_trait::async_trait;
use bytes::Bytes;
+628 -136
View File
@@ -74,12 +74,17 @@
//! swift upload container --extract-archive archive.tar.gz
//! ```
use super::{SwiftError, SwiftResult, container, object};
use axum::http::{Response, StatusCode};
use super::{SwiftError, SwiftResult, account, container, object};
use axum::http::{HeaderMap, HeaderValue, Response, StatusCode};
use futures::StreamExt;
use rustfs_credentials::Credentials;
use rustfs_s3_types::Body;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
use tracing::{debug, error};
const LOG_COMPONENT_PROTOCOLS: &str = "protocols";
@@ -87,6 +92,140 @@ const LOG_SUBSYSTEM_SWIFT_BULK: &str = "swift_bulk";
const EVENT_SWIFT_BULK_DELETE_STATE: &str = "swift_bulk_delete_state";
const EVENT_SWIFT_BULK_EXTRACT_STATE: &str = "swift_bulk_extract_state";
/// Maximum request body size accepted by Swift bulk delete (8 MiB).
pub const MAX_BULK_DELETE_BODY_SIZE: usize = 8 * 1024 * 1024;
/// Maximum number of object paths accepted per Swift bulk delete request.
pub const MAX_BULK_DELETE_PATHS: usize = 10_000;
/// Maximum number of error entries retained in a bulk delete response.
pub const MAX_BULK_DELETE_ERRORS: usize = 1_000;
/// Maximum compressed request body size accepted by Swift bulk extract (64 MiB).
pub const MAX_BULK_EXTRACT_ARCHIVE_BYTES: usize = 64 * 1024 * 1024;
/// Maximum total decompressed bytes read from a bulk extract archive (256 MiB).
pub const MAX_BULK_EXTRACT_TOTAL_BYTES: u64 = 256 * 1024 * 1024;
/// Maximum single extracted file size in a bulk extract archive (64 MiB).
pub const MAX_BULK_EXTRACT_ENTRY_BYTES: u64 = 64 * 1024 * 1024;
/// Maximum number of regular files extracted per bulk extract archive.
pub const MAX_BULK_EXTRACT_FILES: usize = 1_000;
/// Maximum total tar entries (including directories) processed per bulk extract archive.
pub const MAX_BULK_EXTRACT_ENTRIES: usize = 10_000;
/// Maximum number of error entries retained in a bulk extract response.
pub const MAX_BULK_EXTRACT_ERRORS: usize = 1_000;
/// Limits enforced on bulk delete requests.
#[derive(Debug, Clone, Copy)]
pub struct BulkDeleteLimits {
pub max_body_bytes: usize,
pub max_paths: usize,
pub max_errors: usize,
}
impl Default for BulkDeleteLimits {
fn default() -> Self {
Self {
max_body_bytes: MAX_BULK_DELETE_BODY_SIZE,
max_paths: MAX_BULK_DELETE_PATHS,
max_errors: MAX_BULK_DELETE_ERRORS,
}
}
}
/// Limits enforced on bulk extract archives and their decompressed expansion.
#[derive(Debug, Clone, Copy)]
pub struct BulkExtractLimits {
pub max_archive_bytes: usize,
pub max_total_decompressed_bytes: u64,
pub max_entry_bytes: u64,
pub max_files: usize,
pub max_total_entries: usize,
pub max_errors: usize,
}
impl Default for BulkExtractLimits {
fn default() -> Self {
Self {
max_archive_bytes: MAX_BULK_EXTRACT_ARCHIVE_BYTES,
max_total_decompressed_bytes: MAX_BULK_EXTRACT_TOTAL_BYTES,
max_entry_bytes: MAX_BULK_EXTRACT_ENTRY_BYTES,
max_files: MAX_BULK_EXTRACT_FILES,
max_total_entries: MAX_BULK_EXTRACT_ENTRIES,
max_errors: MAX_BULK_EXTRACT_ERRORS,
}
}
}
/// Wrapper around an archive decompressor that aborts as soon as total
/// decompressed output exceeds `max_bytes`.
struct LimitedDecompressReader<R> {
inner: R,
max_bytes: u64,
bytes_read: u64,
exceeded: Arc<AtomicBool>,
}
impl<R> LimitedDecompressReader<R> {
fn new(inner: R, max_bytes: u64, exceeded: Arc<AtomicBool>) -> Self {
Self {
inner,
max_bytes,
bytes_read: 0,
exceeded,
}
}
}
impl<R: AsyncRead + Unpin> AsyncRead for LimitedDecompressReader<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
if self.exceeded.load(Ordering::Acquire) {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("decompressed archive exceeds maximum of {} bytes", self.max_bytes),
)));
}
let remaining = self.max_bytes.saturating_sub(self.bytes_read);
if remaining == 0 {
// Probe at most 1 byte into a local buffer so the caller's ReadBuf is
// never modified when returning Poll::Ready(Err(_)).
let mut probe = [0u8; 1];
let mut probe_buf = ReadBuf::new(&mut probe);
return match Pin::new(&mut self.inner).poll_read(cx, &mut probe_buf) {
Poll::Pending => Poll::Pending,
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
Poll::Ready(Ok(())) => {
if probe_buf.filled().is_empty() {
Poll::Ready(Ok(()))
} else {
self.exceeded.store(true, Ordering::Release);
Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("decompressed archive exceeds maximum of {} bytes", self.max_bytes),
)))
}
}
};
}
let cap = remaining.min(buf.remaining() as u64) as usize;
if cap == 0 {
return Poll::Ready(Ok(()));
}
let slice = buf.initialize_unfilled_to(cap);
let mut sub = ReadBuf::new(slice);
match Pin::new(&mut self.inner).poll_read(cx, &mut sub) {
Poll::Pending => Poll::Pending,
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
Poll::Ready(Ok(())) => {
let read = sub.filled().len();
buf.advance(read);
self.bytes_read = self.bytes_read.saturating_add(read as u64);
Poll::Ready(Ok(()))
}
}
}
}
/// Result of a single delete operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteResult {
@@ -216,6 +355,16 @@ fn parse_object_path(path: &str) -> SwiftResult<(String, String)> {
///
/// Deletes multiple objects specified in the request body
pub async fn handle_bulk_delete(account: &str, body: String, credentials: &Credentials) -> SwiftResult<Response<Body>> {
handle_bulk_delete_with_limits(account, body, credentials, BulkDeleteLimits::default()).await
}
/// Handle bulk delete request with explicit resource limits.
pub async fn handle_bulk_delete_with_limits(
account: &str,
body: String,
credentials: &Credentials,
limits: BulkDeleteLimits,
) -> SwiftResult<Response<Body>> {
debug!(
event = EVENT_SWIFT_BULK_DELETE_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -225,13 +374,28 @@ pub async fn handle_bulk_delete(account: &str, body: String, credentials: &Crede
"swift bulk delete state changed"
);
let mut response = BulkDeleteResponse::default();
let mut delete_results = Vec::new();
if body.len() > limits.max_body_bytes {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Bulk delete request body exceeds maximum size of {} bytes",
limits.max_body_bytes
)));
}
// Parse paths from body (newline-separated)
let paths: Vec<&str> = body.lines().filter(|line| !line.trim().is_empty()).collect();
account::validate_account_access(account, credentials)?;
if paths.is_empty() {
// Count non-empty paths lazily without materializing an unbounded Vec.
let mut path_count = 0usize;
for _ in body.lines().map(str::trim).filter(|line| !line.is_empty()) {
path_count += 1;
if path_count > limits.max_paths {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Bulk delete request exceeds maximum of {} paths",
limits.max_paths
)));
}
}
if path_count == 0 {
return Err(SwiftError::BadRequest("No paths provided for bulk delete".to_string()));
}
@@ -241,52 +405,41 @@ pub async fn handle_bulk_delete(account: &str, body: String, credentials: &Crede
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
state = "processing",
account = %account,
path_count = paths.len(),
path_count,
"swift bulk delete state changed"
);
// Process each path
for path in paths {
let result = match parse_object_path(path) {
Ok((container, object_key)) => {
// Attempt to delete the object
match object::delete_object(account, &container, &object_key, credentials).await {
Ok(_) => {
response.number_deleted += 1;
DeleteResult {
path: path.to_string(),
status: 204,
error: None,
}
}
Err(SwiftError::NotFound(_)) => {
response.number_not_found += 1;
DeleteResult {
path: path.to_string(),
status: 404,
error: Some("Not Found".to_string()),
}
}
Err(e) => {
error!(
event = EVENT_SWIFT_BULK_DELETE_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
result = "delete_failed",
account = %account,
path = %path,
error = %e,
"swift bulk delete state changed"
);
response.errors.push(vec![path.to_string(), e.to_string()]);
DeleteResult {
path: path.to_string(),
status: 500,
error: Some(e.to_string()),
}
}
let mut response = BulkDeleteResponse::default();
// Process each path lazily while capping retained error entries.
for path in body.lines().map(str::trim).filter(|line| !line.is_empty()) {
if response.errors.len() >= limits.max_errors {
response.response_body = format!("Maximum number of errors ({}) exceeded", limits.max_errors);
break;
}
match parse_object_path(path) {
Ok((container, object_key)) => match object::delete_object(account, &container, &object_key, credentials).await {
Ok(_) => {
response.number_deleted += 1;
}
}
Err(SwiftError::NotFound(_)) => {
response.number_not_found += 1;
}
Err(e) => {
error!(
event = EVENT_SWIFT_BULK_DELETE_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
result = "delete_failed",
account = %account,
path = %path,
error = %e,
"swift bulk delete state changed"
);
response.errors.push(vec![path.to_string(), e.to_string()]);
}
},
Err(e) => {
error!(
event = EVENT_SWIFT_BULK_DELETE_STATE,
@@ -299,15 +452,8 @@ pub async fn handle_bulk_delete(account: &str, body: String, credentials: &Crede
"swift bulk delete state changed"
);
response.errors.push(vec![path.to_string(), e.to_string()]);
DeleteResult {
path: path.to_string(),
status: 400,
error: Some(e.to_string()),
}
}
};
delete_results.push(result);
}
}
// Determine overall status
@@ -358,13 +504,27 @@ impl ArchiveFormat {
/// Handle bulk extract request
///
/// Extracts files from an uploaded archive into the specified container
/// Extracts files from an uploaded archive into the specified container, streaming
/// one entry at a time under strict compressed, decompressed, entry-count, and
/// container-quota limits.
pub async fn handle_bulk_extract(
account: &str,
container: &str,
format: ArchiveFormat,
body: Vec<u8>,
credentials: &Credentials,
) -> SwiftResult<Response<Body>> {
handle_bulk_extract_with_limits(account, container, format, body, credentials, BulkExtractLimits::default()).await
}
/// Handle bulk extract request with explicit archive expansion limits.
pub async fn handle_bulk_extract_with_limits(
account: &str,
container: &str,
format: ArchiveFormat,
body: Vec<u8>,
credentials: &Credentials,
limits: BulkExtractLimits,
) -> SwiftResult<Response<Body>> {
debug!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
@@ -377,59 +537,26 @@ pub async fn handle_bulk_extract(
"swift bulk extract state changed"
);
if body.len() > limits.max_archive_bytes {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Bulk extract archive exceeds maximum size of {} bytes",
limits.max_archive_bytes
)));
}
// Verify account access and container existence without requiring a usage snapshot
// (quotas are enforced per extracted object inside `object::put_object`).
container::get_container_custom_metadata(account, container, credentials).await?;
let mut response = BulkExtractResponse::default();
// Verify container exists
if container::get_container_metadata(account, container, credentials)
.await
.is_err()
{
return Err(SwiftError::NotFound(format!("Container not found: {}", container)));
}
// Parse archive and collect all entries into memory (entire archive and file contents are buffered)
let entries = extract_tar_entries(format, body).await?;
// Now upload each entry (async operations)
for (path_str, contents) in entries {
// Upload file to container
match object::put_object(
account,
container,
&path_str,
credentials,
std::io::Cursor::new(contents),
&http::HeaderMap::new(),
)
.await
{
Ok(_) => {
response.number_files_created += 1;
debug!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
state = "file_created",
container = %container,
object = %path_str,
"swift bulk extract state changed"
);
}
Err(e) => {
error!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
result = "upload_failed",
container = %container,
object = %path_str,
error = %e,
"swift bulk extract state changed"
);
response.errors.push(vec![path_str.clone(), e.to_string()]);
}
}
}
let mut consumer = TarEntryConsumer::Upload {
account,
container,
credentials,
max_errors: limits.max_errors,
response: &mut response,
};
stream_tar_entries(format, body, limits, &mut consumer).await?;
// Determine overall status
if response.number_files_created == 0 {
@@ -459,10 +586,13 @@ pub async fn handle_bulk_extract(
.map_err(|e| SwiftError::InternalServerError(format!("Failed to build response: {}", e)))
}
/// Extract tar entries using async I/O and return them as in-memory buffers
async fn extract_tar_entries(format: ArchiveFormat, body: Vec<u8>) -> SwiftResult<Vec<(String, Vec<u8>)>> {
// Create appropriate reader based on format
let reader: Box<dyn tokio::io::AsyncRead + Unpin + Send> = match format {
fn build_bounded_archive_reader(
format: ArchiveFormat,
body: Vec<u8>,
max_total_decompressed_bytes: u64,
decompressed_exceeded: Arc<AtomicBool>,
) -> Box<dyn AsyncRead + Unpin + Send> {
let raw_reader: Box<dyn AsyncRead + Unpin + Send> = match format {
ArchiveFormat::Tar => Box::new(std::io::Cursor::new(body)),
ArchiveFormat::TarGz => {
let cursor = std::io::Cursor::new(body);
@@ -473,27 +603,149 @@ async fn extract_tar_entries(format: ArchiveFormat, body: Vec<u8>) -> SwiftResul
Box::new(async_compression::tokio::bufread::BzDecoder::new(tokio::io::BufReader::new(cursor)))
}
};
Box::new(LimitedDecompressReader::new(
raw_reader,
max_total_decompressed_bytes,
decompressed_exceeded,
))
}
enum TarEntryConsumer<'a> {
Upload {
account: &'a str,
container: &'a str,
credentials: &'a Credentials,
max_errors: usize,
response: &'a mut BulkExtractResponse,
},
#[cfg(test)]
Collect(&'a mut Vec<(String, Vec<u8>)>),
}
impl TarEntryConsumer<'_> {
async fn handle_file(&mut self, path_str: String, contents: Vec<u8>) -> SwiftResult<()> {
match self {
Self::Upload {
account,
container,
credentials,
max_errors,
response,
} => {
let mut upload_headers = HeaderMap::new();
if let Ok(len_header) = HeaderValue::from_str(&contents.len().to_string()) {
upload_headers.insert("content-length", len_header);
}
match Box::pin(object::put_object(
account,
container,
&path_str,
credentials,
std::io::Cursor::new(contents),
&upload_headers,
))
.await
{
Ok(_) => {
response.number_files_created += 1;
debug!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
state = "file_created",
container = %container,
object = %path_str,
"swift bulk extract state changed"
);
}
Err(e) => {
error!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
result = "upload_failed",
container = %container,
object = %path_str,
error = %e,
"swift bulk extract state changed"
);
if response.errors.len() < *max_errors {
response.errors.push(vec![path_str, e.to_string()]);
} else if response.response_body.is_empty() {
response.response_body = format!("Maximum number of errors ({}) exceeded", *max_errors);
}
}
}
Ok(())
}
#[cfg(test)]
Self::Collect(entries) => {
entries.push((path_str, contents));
Ok(())
}
}
}
}
/// Stream tar entries one at a time under strict compressed, decompressed, per-entry,
/// and entry-count limits so neither a compression bomb nor a high-cardinality archive
/// can exhaust server memory.
async fn stream_tar_entries(
format: ArchiveFormat,
body: Vec<u8>,
limits: BulkExtractLimits,
consumer: &mut TarEntryConsumer<'_>,
) -> SwiftResult<()> {
if body.len() > limits.max_archive_bytes {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Bulk extract archive exceeds maximum size of {} bytes",
limits.max_archive_bytes
)));
}
let decompressed_exceeded = Arc::new(AtomicBool::new(false));
let reader =
build_bounded_archive_reader(format, body, limits.max_total_decompressed_bytes, Arc::clone(&decompressed_exceeded));
// Parse tar archive
let mut archive = tokio_tar::Archive::new(reader);
let mut entries = Vec::new();
let mut entries_iter = archive
.entries()
.map_err(|e| SwiftError::BadRequest(format!("Failed to read tar archive: {}", e)))?;
// Extract each entry
while let Some(entry) = entries_iter.next().await {
let mut entry = entry.map_err(|e| SwiftError::BadRequest(format!("Failed to read tar entry: {}", e)))?;
let mut total_entries = 0usize;
let mut regular_files = 0usize;
let mut total_payload_bytes = 0u64;
while let Some(entry_result) = entries_iter.next().await {
let mut entry = match entry_result {
Ok(entry) => entry,
Err(e) => {
if decompressed_exceeded.load(Ordering::Acquire) {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Decompressed archive exceeds maximum size of {} bytes",
limits.max_total_decompressed_bytes
)));
}
return Err(SwiftError::BadRequest(format!("Failed to read tar entry: {}", e)));
}
};
total_entries += 1;
if total_entries > limits.max_total_entries {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Archive exceeds maximum of {} entries",
limits.max_total_entries
)));
}
// Get entry path
let path = entry
.path()
.map_err(|e| SwiftError::BadRequest(format!("Invalid path in tar entry: {}", e)))?;
let path_str = path.to_string_lossy().to_string();
// Skip directories
if entry.header().entry_type().is_dir() {
let entry_type = entry.header().entry_type();
if entry_type.is_dir() {
debug!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
@@ -505,24 +757,81 @@ async fn extract_tar_entries(format: ArchiveFormat, body: Vec<u8>) -> SwiftResul
continue;
}
// Read file contents
let mut contents = Vec::new();
if let Err(e) = tokio::io::AsyncReadExt::read_to_end(&mut entry, &mut contents).await {
error!(
event = EVENT_SWIFT_BULK_EXTRACT_STATE,
component = LOG_COMPONENT_PROTOCOLS,
subsystem = LOG_SUBSYSTEM_SWIFT_BULK,
result = "tar_entry_read_failed",
path = %path_str,
error = %e,
"swift bulk extract state changed"
);
if !entry_type.is_file() {
continue;
}
entries.push((path_str, contents));
regular_files += 1;
if regular_files > limits.max_files {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Archive exceeds maximum of {} extracted files",
limits.max_files
)));
}
let remaining_budget = limits.max_total_decompressed_bytes.saturating_sub(total_payload_bytes);
let entry_cap = limits.max_entry_bytes.min(remaining_budget);
if let Ok(declared_size) = entry.header().raw_file_size()
&& declared_size > entry_cap
{
return Err(SwiftError::RequestEntityTooLarge(format!(
"Archive entry '{}' size {} exceeds allowed limit of {} bytes",
path_str, declared_size, entry_cap
)));
}
let mut contents = Vec::new();
if let Err(e) = (&mut entry)
.take(entry_cap.saturating_add(1))
.read_to_end(&mut contents)
.await
{
if decompressed_exceeded.load(Ordering::Acquire) {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Decompressed archive exceeds maximum size of {} bytes",
limits.max_total_decompressed_bytes
)));
}
return Err(SwiftError::BadRequest(format!("Failed to read tar entry '{}': {}", path_str, e)));
}
if decompressed_exceeded.load(Ordering::Acquire) || (contents.len() as u64) > entry_cap {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Archive entry '{}' exceeds allowed size limit of {} bytes",
path_str, entry_cap
)));
}
total_payload_bytes = total_payload_bytes.saturating_add(contents.len() as u64);
consumer.handle_file(path_str, contents).await?;
}
if decompressed_exceeded.load(Ordering::Acquire) {
return Err(SwiftError::RequestEntityTooLarge(format!(
"Decompressed archive exceeds maximum size of {} bytes",
limits.max_total_decompressed_bytes
)));
}
Ok(())
}
/// Extract tar entries under explicit limits (used by tests to inspect extracted entries).
#[cfg(test)]
async fn extract_tar_entries(format: ArchiveFormat, body: Vec<u8>) -> SwiftResult<Vec<(String, Vec<u8>)>> {
extract_tar_entries_with_limits(format, body, BulkExtractLimits::default()).await
}
#[cfg(test)]
async fn extract_tar_entries_with_limits(
format: ArchiveFormat,
body: Vec<u8>,
limits: BulkExtractLimits,
) -> SwiftResult<Vec<(String, Vec<u8>)>> {
let mut entries = Vec::new();
let mut consumer = TarEntryConsumer::Collect(&mut entries);
stream_tar_entries(format, body, limits, &mut consumer).await?;
Ok(entries)
}
@@ -741,5 +1050,188 @@ mod tests {
let entries = extract_tar_entries(ArchiveFormat::Tar, tar_bytes).await.unwrap();
assert!(entries.is_empty());
}
#[tokio::test]
async fn test_extract_tar_gz_compression_bomb_rejected_at_limit() {
// 2 MiB of zeroes inside a tar compresses to a few KiB with gzip (>500:1 expansion).
let payload = vec![0u8; 2 * 1024 * 1024];
let tar_bytes = make_tar(&[("bomb.bin", &payload)], &[]).await;
let cursor = std::io::Cursor::new(Vec::new());
let mut encoder = async_compression::tokio::write::GzipEncoder::new(cursor);
encoder.write_all(&tar_bytes).await.unwrap();
encoder.shutdown().await.unwrap();
let gz_bytes = encoder.into_inner().into_inner();
assert!(gz_bytes.len() < 16 * 1024, "fixture should be tiny compressed");
let limits = BulkExtractLimits {
max_archive_bytes: 1024 * 1024,
max_total_decompressed_bytes: 64 * 1024,
max_entry_bytes: 64 * 1024,
max_files: 10,
max_total_entries: 20,
max_errors: 10,
};
let err = extract_tar_entries_with_limits(ArchiveFormat::TarGz, gz_bytes, limits)
.await
.expect_err("gzip bomb must be rejected");
assert!(
matches!(err, SwiftError::RequestEntityTooLarge(_)),
"expected RequestEntityTooLarge, got {err:?}"
);
}
#[tokio::test]
async fn test_extract_tar_bz2_compression_bomb_rejected_at_limit() {
let payload = vec![0u8; 2 * 1024 * 1024];
let tar_bytes = make_tar(&[("bomb.bin", &payload)], &[]).await;
let cursor = std::io::Cursor::new(Vec::new());
let mut encoder = async_compression::tokio::write::BzEncoder::new(cursor);
encoder.write_all(&tar_bytes).await.unwrap();
encoder.shutdown().await.unwrap();
let bz2_bytes = encoder.into_inner().into_inner();
assert!(bz2_bytes.len() < 16 * 1024, "fixture should be tiny compressed");
let limits = BulkExtractLimits {
max_archive_bytes: 1024 * 1024,
max_total_decompressed_bytes: 64 * 1024,
max_entry_bytes: 64 * 1024,
max_files: 10,
max_total_entries: 20,
max_errors: 10,
};
let err = extract_tar_entries_with_limits(ArchiveFormat::TarBz2, bz2_bytes, limits)
.await
.expect_err("bzip2 bomb must be rejected");
assert!(
matches!(err, SwiftError::RequestEntityTooLarge(_)),
"expected RequestEntityTooLarge, got {err:?}"
);
}
#[tokio::test]
async fn test_extract_tar_enforces_archive_entry_file_and_dir_limits() {
let tar_bytes = make_tar(&[("a.bin", &[b'a'; 2048])], &[]).await;
// Compressed/raw archive size cap.
let err = extract_tar_entries_with_limits(
ArchiveFormat::Tar,
tar_bytes.clone(),
BulkExtractLimits {
max_archive_bytes: 512,
..BulkExtractLimits::default()
},
)
.await
.expect_err("oversized raw archive must be rejected");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
// Single entry cap.
let err = extract_tar_entries_with_limits(
ArchiveFormat::Tar,
tar_bytes,
BulkExtractLimits {
max_entry_bytes: 1024,
max_total_decompressed_bytes: 64 * 1024,
..BulkExtractLimits::default()
},
)
.await
.expect_err("oversized entry must be rejected");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
// Regular file count cap.
let many_files = make_tar(&[("f1", b"1"), ("f2", b"2"), ("f3", b"3"), ("f4", b"4")], &[]).await;
let err = extract_tar_entries_with_limits(
ArchiveFormat::Tar,
many_files,
BulkExtractLimits {
max_files: 3,
..BulkExtractLimits::default()
},
)
.await
.expect_err("too many regular files must be rejected");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
// Directory entry flood cap (non-file entries still count toward max_total_entries).
let dir_flood = make_tar(&[], &["d1/", "d2/", "d3/", "d4/", "d5/", "d6/"]).await;
let err = extract_tar_entries_with_limits(
ArchiveFormat::Tar,
dir_flood,
BulkExtractLimits {
max_files: 100,
max_total_entries: 5,
..BulkExtractLimits::default()
},
)
.await
.expect_err("directory flood must be rejected");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
}
#[tokio::test]
async fn test_bulk_delete_enforces_body_path_and_error_limits() {
use http_body_util::BodyExt;
let mut claims = std::collections::HashMap::new();
claims.insert("keystone_project_id".to_string(), serde_json::json!("proj1"));
let creds = Credentials {
access_key: "keystone:test".to_string(),
claims: Some(claims),
..Default::default()
};
// Oversized body fails closed with 413.
let err = handle_bulk_delete_with_limits(
"AUTH_proj1",
"/c/a\n/c/b\n/c/c\n".to_string(),
&creds,
BulkDeleteLimits {
max_body_bytes: 8,
max_paths: 10,
max_errors: 10,
},
)
.await
.expect_err("oversized bulk-delete body must fail closed");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
// Too many paths fails closed with 413.
let err = handle_bulk_delete_with_limits(
"AUTH_proj1",
"/c/1\n/c/2\n/c/3\n/c/4\n".to_string(),
&creds,
BulkDeleteLimits {
max_body_bytes: 1024,
max_paths: 3,
max_errors: 10,
},
)
.await
.expect_err("too many bulk-delete paths must fail closed");
assert!(matches!(err, SwiftError::RequestEntityTooLarge(_)));
// Error flood caps retained error entries at max_errors.
let invalid_paths = "bad1\nbad2\nbad3\nbad4\nbad5\nbad6\n".to_string();
let resp = handle_bulk_delete_with_limits(
"AUTH_proj1",
invalid_paths,
&creds,
BulkDeleteLimits {
max_body_bytes: 1024,
max_paths: 100,
max_errors: 3,
},
)
.await
.expect("capped bulk-delete error response should succeed");
let body_bytes = resp.into_body().collect().await.expect("response body").to_bytes();
let parsed: BulkDeleteResponse = serde_json::from_slice(&body_bytes).expect("valid JSON");
assert_eq!(parsed.errors.len(), 3, "errors must be capped at max_errors");
assert_eq!(parsed.response_status, "400 Bad Request");
assert!(parsed.response_body.contains("Maximum number of errors"));
}
}
}
+2 -1
View File
@@ -665,10 +665,11 @@ pub async fn list_objects(
String::new()
};
let bytes = obj_info.get_actual_size().unwrap_or(obj_info.size).max(0) as u64;
swift_objects.push(Object {
name: obj_info.name,
hash: obj_info.etag.unwrap_or_default(),
bytes: obj_info.size as u64,
bytes,
content_type: obj_info
.content_type
.unwrap_or_else(|| "application/octet-stream".to_string()),
+31 -10
View File
@@ -34,6 +34,10 @@ pub struct ObjectInfo {
pub etag: Option<String>,
}
fn segment_size_u64(segment: &ObjectInfo) -> u64 {
u64::try_from(segment.size).unwrap_or(0)
}
/// Check if object is a DLO by checking for manifest metadata
pub async fn is_dlo_object(
account: &str,
@@ -175,7 +179,7 @@ fn calculate_dlo_segments_for_range(
let mut current_offset = 0u64;
for (idx, segment) in segments.iter().enumerate() {
let seg_size = segment.size as u64;
let seg_size = segment_size_u64(segment);
// Empty segments contribute no bytes; skip them so the `seg_size - 1`
// arithmetic below cannot underflow.
@@ -230,8 +234,8 @@ pub async fn handle_dlo_get(
return Err(SwiftError::NotFound("No DLO segments found".to_string()));
}
// 3. Calculate total size
let total_size: u64 = segments.iter().map(|s| s.size as u64).sum();
// 3. Calculate total logical plaintext size
let total_size: u64 = segments.iter().map(segment_size_u64).sum();
// 4. Parse range header if present
let range = headers
@@ -299,9 +303,11 @@ async fn create_dlo_stream(
segments
.iter()
.enumerate()
// Skip empty segments so `s.size - 1` cannot underflow; they carry no bytes.
.filter(|(_, s)| s.size as u64 > 0)
.map(|(i, s)| (i, 0, s.size as u64 - 1, s.clone()))
// Skip empty segments so `seg_size - 1` cannot underflow; they carry no bytes.
.filter_map(|(i, s)| {
let seg_size = segment_size_u64(s);
(seg_size > 0).then(|| (i, 0, seg_size - 1, s.clone()))
})
.collect()
};
@@ -316,7 +322,8 @@ async fn create_dlo_stream(
let creds = creds.clone();
async move {
let range_spec = if byte_start > 0 || byte_end < segment.size as u64 - 1 {
let seg_size = segment_size_u64(&segment);
let range_spec = if byte_start > 0 || byte_end < seg_size.saturating_sub(1) {
Some(HTTPRangeSpec {
is_suffix_length: false,
start: byte_start as i64,
@@ -347,6 +354,11 @@ pub async fn handle_dlo_register(
manifest_value: &str,
credentials: &Option<Credentials>,
) -> Result<Response<Body>, SwiftError> {
// Require credentials for DLO write operations (consistent with handle_slo_put)
if credentials.is_none() {
return Err(SwiftError::Unauthorized("Credentials required for DLO operations".to_string()));
}
// Validate manifest format
let _ = parse_dlo_manifest(manifest_value)?;
@@ -355,9 +367,18 @@ pub async fn handle_dlo_register(
let mut metadata = HashMap::new();
metadata.insert("x-object-manifest".to_string(), manifest_value.to_string());
// Use put_object_with_metadata to store the marker
object::put_object_with_metadata(account, container, object, credentials, std::io::Cursor::new(Vec::new()), &metadata)
.await?;
// Use put_object_with_metadata_and_size so quota and default bucket SSE apply cleanly
object::put_object_with_metadata_and_size(
account,
container,
object,
credentials,
std::io::Cursor::new(Vec::new()),
&metadata,
Some(0),
None,
)
.await?;
let trans_id = generate_trans_id();
Response::builder()

Some files were not shown because too many files have changed in this diff Show More