mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-22 12:26:37 +00:00
Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a0dcbcda9b | |||
| 76e7d979d2 | |||
| 1a3be70d98 | |||
| 8679570c2a | |||
| 7143697a5f | |||
| a34310a58f | |||
| 2e60029079 | |||
| 2c3e68ad89 | |||
| 2f0918f60b | |||
| 5b951de2b7 | |||
| 98c4675617 | |||
| eec34331de | |||
| 5d820df79c | |||
| 37c5ce1399 | |||
| 61b5edf16e | |||
| ab5d433fe1 | |||
| bc07cfd115 | |||
| bce5922aef | |||
| adb90fc6e1 | |||
| cdfac5d7e3 | |||
| ca4adea0c9 | |||
| 23a0f6324c | |||
| cdd9ab1124 | |||
| 122a69df65 | |||
| dfeb732ac8 | |||
| 1aae680373 | |||
| 1b4f62d501 | |||
| 4283591838 | |||
| f2957a680d | |||
| d22cb5d07a | |||
| 762919b1ba | |||
| cee0d5cf9b | |||
| 35af688cd9 | |||
| 205337151a | |||
| 105b6fbfde | |||
| b2e573c48b | |||
| 114bf5148c | |||
| 830e553a3c |
@@ -1,277 +1,45 @@
|
|||||||
---
|
---
|
||||||
name: adversarial-validation
|
name: adversarial-validation
|
||||||
description: Execute the Adversarial Validation policy from the root AGENTS.md — run the applicable reviewer roles with RustFS-specific attack probes. Use on every behavior-affecting code change, bug fix, design proposal, or agent-instruction change that alters execution before declaring it done.
|
description: Review a final RustFS diff adversarially when the user requests adversarial review, the root AGENTS.md classifies the change as high risk, or a substantial PR is being reviewed. Do not use for ordinary questions, diagnosis, planning, status, documentation-only work, or routine low-risk implementation.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Adversarial Validation Playbooks
|
# RustFS Adversarial Validation
|
||||||
|
|
||||||
The policy — risk tiers, role list, protocol, exit criteria — lives in the
|
Use the risk tier and review shape defined in the root `AGENTS.md`. This skill
|
||||||
root `AGENTS.md` under "Adversarial Validation (Default On)". Read it first;
|
routes a review to RustFS-specific probes without loading unrelated domains.
|
||||||
this skill does not restate it. This file adds the RustFS-specific probe
|
|
||||||
playbook for each role: concrete attacks, where they apply, and the real
|
|
||||||
shipped bug or rule that earns each probe its place.
|
|
||||||
|
|
||||||
## How to run a role
|
## Select Lenses
|
||||||
|
|
||||||
1. Pick the tier and the applicable roles per the root `AGENTS.md`.
|
Read only the references required by the diff:
|
||||||
2. Run each role as an independent pass over the final diff — a parallel
|
|
||||||
reviewer agent where the tooling supports it, otherwise a fresh
|
|
||||||
sequential pass that starts from the diff and the nearest scoped
|
|
||||||
`AGENTS.md`, discarding the writing session's assumptions.
|
|
||||||
3. Within a role, execute the probes whose domain the diff touches, plus any
|
|
||||||
attack the diff obviously invites that no probe lists — the playbook is a
|
|
||||||
floor, not a ceiling.
|
|
||||||
4. Report findings (concrete failure scenario or named missing test, with
|
|
||||||
file:line) or the role's null report: "attacked X, Y, Z — no break
|
|
||||||
found". A bare pass is not a result.
|
|
||||||
|
|
||||||
## Role playbooks
|
| Lens | When to read |
|
||||||
|
|---|---|
|
||||||
|
| [Correctness](references/correctness.md) | Every non-exempt adversarial review |
|
||||||
|
| [Simplicity](references/simplicity.md) | Mechanical/standard changes and production growth |
|
||||||
|
| [Test coverage](references/test-coverage.md) | Behavior or test changes |
|
||||||
|
| [Security](references/security.md) | Authn/authz, IAM, RPC trust, paths, secrets, parsing, browser, encryption |
|
||||||
|
| [Concurrency/durability](references/concurrency-durability.md) | Async shared state, locks, storage commit, cancellation, persisted queues |
|
||||||
|
| [Compatibility](references/compatibility.md) | S3 surface, MinIO interop, metadata, wire/disk formats, mixed versions |
|
||||||
|
| [Performance](references/performance.md) | Request/object hot paths, allocation, blocking work, fsync, fan-out |
|
||||||
|
|
||||||
### Correctness adversary
|
Do not read all references as a precaution. A path name alone is insufficient;
|
||||||
|
the changed behavior must touch the lens's domain.
|
||||||
|
|
||||||
- For any change touching error aggregation or quorum decisions, build the exact disk-error slice at the quorum boundary: N disks where successes == quorum, then flip one success to an error (quorum-1) and separately inject None/nil placeholder entries into the slice. Trace whether reduce_errs (or the new equivalent) picks the placeholder as the dominant error or lets quorum-1 pass as success. Also check heal/write paths: does a per-target failure at quorum-1 return an explicit error, or silently degrade to success?
|
For a dedicated security audit or advisory analysis, use
|
||||||
- Where: crates/ecstore/src/disk/error_reduce.rs; crates/ecstore/src/set_disk/{core,ops}; crates/heal
|
`security-advisory-lessons` instead of loading it automatically during every
|
||||||
- Evidence: Commit 20d61c73b 'stop reduce_errs leaking nil placeholder as dominant error' (#4551) and 47c1e730c 'make erasure heal write quorum best-effort per target' (#4545); crates/ecstore/AGENTS.md: 'Do not weaken quorum checks... Prefer explicit failure over silent data corruption or implicit success.'
|
adversarial review.
|
||||||
- For any change in EC read/reconstruct/streaming code, trace the mid-stream error path: the first K shards read fine, then a shard turns out bitrot-corrupt or inconsistent after N bytes have already been sent to the client. Verify the error propagates as a stream error (client sees failure), not a clean end-of-body — a silently truncated GET body is data corruption. Also re-check byte accounting: sum of per-part bytes vs object size, and partNumber-to-offset routing for the first and last part.
|
|
||||||
- Where: crates/ecstore/src/set_disk/read.rs (reconstruct-read, inconsistent_source_indexes handling ~line 3827); codec streaming paths in crates/ecstore/src/erasure_coding
|
|
||||||
- Evidence: Known live bug: EC reconstruct-read failing on inconsistent shards mid-stream silently truncates GET body → client 'unexpected EOF'; commit 15808254d 'correct codec-streaming byte accounting and partNumber routing' (#4535).
|
|
||||||
- For any listing/pagination change, construct the exact-boundary inputs: (a) exactly max_keys/max_uploads matching entries — assert the response contains max and is_truncated=false, then max+1 entries — assert exactly max returned with is_truncated=true and a correct continuation marker; (b) a delimiter listing where folding into CommonPrefixes re-fills a full page; (c) an object 'a' coexisting with prefix dir 'a/'. Off-by-one and dropped-truncation bugs live exactly at these boundaries.
|
|
||||||
- Where: crates/ecstore listing/merge paths (metacache, list_objects, list_multipart_uploads); rustfs/src/storage
|
|
||||||
- Evidence: Three recent real bugs: fefa70b31 'stop ListMultipartUploads from returning one upload past max-uploads' (#4447), d91f4d455 'report truncation when delimiter list re-folds a full page' (#4538), 7e1f7f242 'preserve CommonPrefixes when an object and same-named prefix dir coexist' (#4563).
|
|
||||||
- Run the diff's logic with a directory object key (trailing slash, e.g. 'pre/dir/') as input. Check which layer encodes/decodes __XLDIR__ — set_disk never sees the trailing slash, so any trailing-slash branch added below the store layer is dead code and a wrong-layer bug. For delete paths, check whether options force a nil versionId onto directory keys: the resulting miss surfaces as version-not-found, not object-not-found, so callers matching only ObjectNotFound leak ghost directory entries.
|
|
||||||
- Where: crates/ecstore/src/store*.rs (store layer) vs crates/ecstore/src/set_disk/*; delete option construction (del_opts) and its callers
|
|
||||||
- Evidence: trailing-slash branches must live at store layer; del_opts injects nil version for dir keys, PR#4220 ghost-directory cleanup never fired on the real path (rustfs#4307, backlog#798 still OPEN).
|
|
||||||
- Feed every new binary-UUID metadata read the three degenerate values: key absent, zero-length bytes, and 16 zero bytes (nil UUID). All three must mean 'no value' — any path that produces Uuid::nil() and then acts on it (e.g. sends it as a versionId) is a finding. For tier code specifically: with remote-tier version None or "", assert the tier GET/DELETE request carries no versionId parameter at all — sending versionId="" or nil yields NoSuchVersion against unversioned tier buckets.
|
|
||||||
- Where: crates/filemeta/src/filemeta/version.rs; crates/ecstore/src/bucket/lifecycle/; crates/ecstore/src/services/tier/; any new consumer of crates/utils/src/http/metadata_compat.rs
|
|
||||||
- Evidence: AGENTS.md Cross-Cutting Domain Invariants (defensive Uuid read pattern + unversioned-tier rule); docs/operations/tier-ilm-debugging.md ('nil transition_ver_id = corrupt legacy write-back, readers must filter'); commit 726f3dc18 'accept empty remote version_id in tier recovery paths' (#4552).
|
|
||||||
- For each match/if-let on an error or algorithm enum touched by the diff, enumerate what the wildcard/else arm swallows. Inject the variants the author didn't think of — DiskNotFound during listing, an unsupported checksum algorithm, an Err from a cleanup rename/delete — and trace whether they degrade into 'not found', a wrong-but-plausible value, or silent success. Any error path that converges with the success path without logging and propagating is a finding.
|
|
||||||
- Where: crates/ecstore (listing, delete/rename cleanup); crates/checksums; error-mapping layers in rustfs/src/storage
|
|
||||||
- Evidence: Three recent real bugs of this exact shape: e0619e355 'stop treating DiskNotFound as object not-found in listing' (#4536), afaf8c681 'reject md5 instead of silently returning crc32' (#4513), f7d2b2563 'propagate disk delete/rename failures instead of swallowing them' (#4546).
|
|
||||||
- For any change to version ordering, index lookup, or shard/part indexing: (a) call the accessor with index == len() and len()-1 — a get_idx-style bound must reject, not panic or wrap; (b) construct two versions with identical mod-times and check the sort tie-break is total and deterministic (equal keys must not compare as both before each other); (c) for EC shard math, compute shard size for object sizes 0, 1, blockSize-1, blockSize, blockSize+1 and cross-check total reconstructed length against the object size.
|
|
||||||
- Where: crates/filemeta/src/filemeta/*.rs (version sort, get_idx); crates/ecstore/src/erasure_coding shard-size math
|
|
||||||
- Evidence: Commit 8bfb00bc0 'guard get_idx bound and fix sorts_before tie-break' (#4509) — both bug classes shipped before; ecstore AGENTS.md high-risk designation for read/write/repair correctness.
|
|
||||||
- Exercise the zero/empty end of every new size or count parameter: zero-length object PUT then GET (body must be empty, not error), part count 0, empty Vec of disks/entries into aggregation functions, and env/config values of 0 (must clamp or reject, never divide-by-zero or 'scan nothing and report zero usage'). Anywhere the diff computes a ratio, capacity, or progress percentage, plug in 0 and the max value.
|
|
||||||
- Where: crates/ecstore aggregation and scanner paths; crates/object-capacity; config/env parsing in touched crates
|
|
||||||
- Evidence: Commits 787cc77a7 'clamp zero capacity env values to safe defaults' (#4559) and 32b1094ec 'resolve a symlinked scan root instead of silently counting zero' (#4564) — zero-as-silent-wrong-answer is a recurring repo bug class.
|
|
||||||
- For any diff touching multipart or object commit paths, order the operations on paper and attack the failure point between them: kill the process (or return Err) after the commit rename but before cleanup, and after cleanup but before commit. Verify the earlier-failure case leaves the object readable and the later-failure case leaves no half-visible object; part meta files must never be deleted before the commit is durable.
|
|
||||||
- Where: crates/ecstore multipart commit/cleanup (set_disk/ops); rustfs/src/storage multipart handlers
|
|
||||||
- Evidence: Commit c77c5f047 'defer multipart part.N.meta cleanup until after commit' (#4548) — cleanup-before-commit ordering already caused a real data-loss window; the #4221 durability work shows fsync/ordering bugs are endemic here.
|
|
||||||
|
|
||||||
Null report example: "Attacked quorum-1 error reduction, exact max-keys listing boundary, trailing-slash dir keys, nil-UUID tier versionId, and mid-stream reconstruct error propagation — no break found."
|
## Review Protocol
|
||||||
|
|
||||||
### Simplicity adversary
|
1. Freeze the exact final diff/head and list the selected lenses.
|
||||||
|
2. Run the review shape required by root `AGENTS.md`.
|
||||||
|
3. For each selected lens, either report a concrete finding or a null verdict
|
||||||
|
naming the attacks performed.
|
||||||
|
4. A finding needs `file:line`, a triggering input/state/interleaving, the wrong
|
||||||
|
outcome, and a focused fix or missing regression check.
|
||||||
|
5. Fix or rebut every finding with code-path, test, or invariant evidence.
|
||||||
|
6. After a non-trivial edit, rerun only lenses affected by that edit against the
|
||||||
|
new exact diff.
|
||||||
|
|
||||||
- Smaller-diff attack: inspect production growth separately from tests, fixtures, generated code, and documentation; test additions have no growth budget. Rewrite the production diff mentally (or in scratch) as the minimal equivalent edit. Report a finding only with a concrete smaller design that preserves correctness, compatibility, readability, and real boundaries; fewer lines alone are not evidence.
|
Do not turn a null verdict into a long checklist. Record concise evidence that
|
||||||
- Where: Any diff; extra scrutiny for crates/ecstore, crates/lock, rustfs/src/storage where 'preserve the existing control-flow shape' is an explicit rule
|
the relevant failure classes were attacked.
|
||||||
- Evidence: AGENTS.md 'Change Style for Existing Logic' (conditional extraction rule, preserve sensitive control flow, canonical modules) and 'Reuse Before You Write'; the Adversarial Validation roles list charters this attack.
|
|
||||||
- Reuse-and-necessity attack: for each new helper, search `crates/utils`, `crates/common`, the touched crate, the likely domain owner, and relevant direct dependencies. A reimplementation is a finding, but forced reuse with mismatched normalization, error, backoff, or durability semantics is also a finding. Demand a nameable trigger for new defensive branches. Tests remain subject to validity and near-duplicate coverage review, never a size limit.
|
|
||||||
- Where: Any diff adding helpers, branches on decoded/peer data, or tests
|
|
||||||
- Evidence: AGENTS.md 'Reuse Before You Write' and 'Necessary Code Only'; GHSA-f4vq-9ffr-m8m3 (normalization-asymmetry traversal — why forced reuse of normalizing helpers on raw keys is itself an attack); docs/operations/tier-ilm-debugging.md nil-versionId incident (why boundary re-checks are load-bearing).
|
|
||||||
- Replacement-and-comment attack: when the diff introduces a replacement path or representation, trace all callers and flag a superseded in-scope path left behind without a compatibility requirement. Keep one canonical core behind compatibility adapters. Comments must state non-obvious invariants completely without narration or change history. Never demand unrelated deletion or trade away correctness, compatibility, or readability to reduce the diff.
|
|
||||||
|
|
||||||
Null report example: "Separated production growth from tests/docs, tested a smaller equivalent, checked helper reuse and superseded paths, and found no break."
|
|
||||||
|
|
||||||
### Security reviewer
|
|
||||||
|
|
||||||
- For every admin handler in the diff, grep the exact AdminAction constant it passes to validate_admin_request and confirm it names the operation the handler actually performs. Construct the escalation: a low-privileged user whose policy grants the wrong-but-adjacent action (e.g. Export while the handler Imports, or Update while it Lists) — if the mismatched constant lets them through, that is the bug. Also confirm read-only endpoints (metrics, list, server-info, diagnostics) still call an operation-specific admin authz path and not a mere 'credentials exist' check.
|
|
||||||
- Where: rustfs/src/admin/handlers/**, rustfs/src/admin/router registration; check_permissions / validate_admin_request / AdminAction::* call sites
|
|
||||||
- Evidence: GHSA-vcwh-pff9-64cc (ImportIam checked ExportIAMAction), GHSA-mm2q-qcmx-gw4w (ListServiceAccount used UpdateServiceAccountAdminAction), GHSA-f5cv-v44x-2xgf (/admin/v3/metrics accepted any authenticated IAM user). advisory-patterns.md 'Admin authorization and route exposure'; rustfs/src/admin/AGENTS.md 'route registration, whitelist, handler authz must agree'.
|
|
||||||
- If the diff touches service-account or IAM import/update, treat parent, claims, accessKey, secretKey, status, policy names, and groups as attacker-controlled. Construct an ImportIam/create payload where parent points at root (or another user) and prove the code writes credentials without proving caller ownership or root authority. Separately, set deny_only=true (or 'no explicit deny') on a restricted account and check it does not skip the required allow check, letting it mint an unrestricted child.
|
|
||||||
- Where: crates/iam/, rustfs/src/admin/handlers (service account / import IAM), rustfs/src/auth.rs
|
|
||||||
- Evidence: GHSA-566f-q62r-wcr8 (attacker-controlled parent/claims/accessKey/secretKey → persistent backdoor under root), GHSA-xgr5-qc6w-vcg9 (deny_only=true skipped allow checks → privilege creation). crates/iam/AGENTS.md security boundaries; advisory-patterns.md 'IAM import, service accounts'.
|
|
||||||
- For a changed protocol-frontend handler (FTP/FTPS/SFTP/WebDAV/gateway), enumerate ALL sibling command handlers in the same driver — not just the changed one. For each, confirm it calls the per-operation IAM authorize hook mapped to the correct S3 action (RETR→GetObject, SIZE/MDTM→HeadObject, MKD→CreateBucket, bucket probe→ListBucket/HeadBucket) BEFORE touching storage. Construct a denied-authz case and prove the storage backend is never reached.
|
|
||||||
- Where: crates/protocols/ (FtpsDriver, SftpDriver, WebDAV), authorize_operation call sites
|
|
||||||
- Evidence: GHSA-3g29-xff2-92vp (FTP RETR/SIZE/MDTM authenticated but skipped IAM), GHSA-g3vq-vv42-f647 (FTPS MKD called create_bucket without s3:CreateBucket). advisory-patterns.md: 'RustFS advisories show mixed guarded and unguarded siblings in the same driver.'
|
|
||||||
- For any secret/token/signature/password comparison in the diff, check it uses a constant-time compare (e.g. subtle/constant_time_eq), not == or early-return byte loops. Then check the failure-response paths: construct an invalid-user request and an invalid-secret request and confirm they are indistinguishable (same error, no early length short-circuit) so an attacker cannot enumerate valid users or time-side-channel the secret.
|
|
||||||
- Where: crates/protocols/ (FTPS/WebDAV/FormPost auth), crates/credentials/, rustfs/src/auth.rs, RPC signature verification
|
|
||||||
- Evidence: GHSA-3p3x-734c-h5vx (FTPS/WebDAV early-return string equality + distinguishable invalid-user vs invalid-password). Fix commits 3c3113619 (constant-time FTPS/WebDAV) and c41062f27 (constant-time FormPost signature). 3p3x was fixed by PR #4403.
|
|
||||||
- If the diff parses or transports secret-bearing config (env vars, key files, connection strings), grep every error-construction and format site on that value's path (`format!` feeding `Error::other`/`configuration_error`/`panic!`/`expect`) for interpolation of the raw value or of variables named like secret material. Construct the likeliest misconfiguration: the operator supplies the bare secret without the expected `<name>:` prefix (or with a stray newline) — if the parse-failure hint echoes the input, the secret lands in startup logs. Error strings are log content; the hint may name the env var and expected format, never the value. If the diff re-implements an existing parse helper, diff the two error paths — the duplicate is where the leak hides.
|
|
||||||
- Where: rustfs/src/init.rs (env plumbing), crates/kms/src/config.rs, crates/credentials/, any from_env/parse on secret values; mechanical backstop in scripts/check_logging_guardrails.sh (secret-interpolation check)
|
|
||||||
- Evidence: PR #5222 introduced `got: {secret_str}` in build_static_kms_config's format-hint error — a bare base64 key (the secret itself) would have been echoed into startup logs; fixed by PR #5243. The parallel parse in KmsConfig::from_env already omitted the value: the leak lived only in the duplicated copy (AGENTS.md 'Reuse Before You Write').
|
|
||||||
- If the diff touches internode/RPC auth secret handling, trace whether the RPC HMAC secret can fall back to a public default (e.g. 'rustfsadmin', 'rustfs rpc') or be derived deterministically from the S3 root credentials. Construct the case where RUSTFS_RPC_SECRET is unset and confirm the code fails closed rather than silently using a default or a root-derived key. Verify RPC signing keys are independent random secrets, not reused across S3-root/RPC-HMAC/STS-JWT roles.
|
|
||||||
- Where: crates/credentials/, crates/ecstore/src/rpc/, internode auth setup
|
|
||||||
- Evidence: GHSA-r5qv-rc46-hv8q (fell back to 'rustfsadmin'), GHSA-75fx/68cw (RPC secret derivable from root creds → forgeable signatures), GHSA-h956 (hard-coded 'rustfs rpc'), GHSA-m77q (STS JWT reused root secret). Fix commit 7b2055405 (fail closed when deriving RPC secret from default credentials, PR#4402).
|
|
||||||
- If the diff touches RPC/NodeService authentication, verify the HMAC payload binds the EXACT concrete gRPC method path (not a service prefix), the HTTP method surrogate, and a fresh timestamp. Construct captured valid metadata for method A and replay it to method B within the timestamp window — if it authorizes, the signature is under-bound. Also test stale timestamp, wrong path, wrong method, wrong secret.
|
|
||||||
- Where: crates/ecstore/src/rpc/, verify_rpc_signature / NodeServiceServer, x-rustfs-signature handling
|
|
||||||
- Evidence: GHSA-c667-rgrv-99vj (signed service prefix instead of concrete method path → cross-method replay in timestamp window). advisory-patterns.md 'RPC input validation and panic safety'; Minimum Regression Test Expectations lists replay across two methods.
|
|
||||||
- For any RPC/gRPC handler or deserialization touched, feed empty bytes, truncated MessagePack/protobuf, invalid enum discriminants, and stale timestamps. Grep the deserialization path for unwrap()/expect()/panic-prone decode and prove malformed attacker payloads return a typed error, not a panic (remote DoS). Weak internode auth makes reachability worse, so combine with the RPC-secret probe.
|
|
||||||
- Where: crates/ecstore/src/rpc/, any #[derive(Deserialize)] decoded from wire bytes, RPC handler bodies
|
|
||||||
- Evidence: GHSA-gw2x-q739-qhcr (malformed GetMetrics reached unwrap() → remote DoS). advisory-patterns.md 'Treat all RPC payload bytes as attacker-controlled.' rust-code-quality skill: unwrap abuse.
|
|
||||||
- Take any object key, RPC disk path, or archive/tar/zip entry name introduced or handled in the diff and construct traversal payloads: '../', URL-encoded '%2e%2e%2f', absolute paths, platform separators, empty components. Trace the value through parse → authz check → final storage path and prove (a) authz and storage normalize the SAME way, and (b) the canonicalized path cannot escape the bucket/prefix root. Attack the case where authz sees the raw attacker bucket but storage cleaning crosses into a victim bucket.
|
|
||||||
- Where: crates/ecstore (path join/canonicalize), rustfs/src/storage/, Snowball auto-extract / normalize_extract_entry_key, rpc read_file_stream
|
|
||||||
- Evidence: GHSA-pq29-69jg-9mxc (read_file_stream joined untrusted paths, no canonical boundary check), GHSA-8r6f-hmq2-28rg (traversal object keys bypassed authz), GHSA-f4vq-9ffr-m8m3 (Snowball '../victim-bucket/object' authorized raw path then storage crossed boundary). Note __XLDIR__ trailing-slash encoding is store-layer only.
|
|
||||||
- If the diff touches multipart/copy or presigned POST, verify UploadPartCopy enforces source GetObject AND destination PutObject semantics equivalent to CopyObject, including copy-source policy conditions (not just independent source-read + dest-write). Construct a cross-bucket UploadPartCopy from a bucket the caller cannot read. For presigned POST, submit an upload that violates content-length-range, key prefix, or exact content-type and prove the server rejects it.
|
|
||||||
- Where: rustfs/src/storage / S3 API handlers: upload_part_copy, CompleteMultipartUpload, PostObject policy enforcement
|
|
||||||
- Evidence: GHSA-mx42-j6wv-px98 (UploadPartCopy missed source authz → cross-bucket exfil), GHSA-wfxj-ph3v-7mjf (missed destination copy-source policy constraint), GHSA-w5fh-f8xh-5x3p (presigned POST didn't enforce signed policy conditions). advisory-patterns.md 'S3 copy, multipart, and upload policy validation'.
|
|
||||||
- Grep the diff for debug!/trace!/info!/error! and any ?value / {:?} on structs or response bodies that can carry secret_key, session_token, JWT claims, HMAC secrets, expected signatures, access keys beyond safe identifiers, or raw credential-bearing responses. Check custom Debug impls and merged-config dumps too. Construct the error path (invalid signature, failed auth) and confirm it does not log the secret or the derived authenticator. Verify audit/notify entries redact credential request headers.
|
|
||||||
- Where: rustfs/src/**, crates/iam/, crates/audit/, crates/notify/, crates/targets/, RPC signature error paths
|
|
||||||
- Evidence: GHSA-r54g (STS creds logged at info), GHSA-8cm2 (debug logs leaked tokens/secrets/JWT claims/raw STS bodies), GHSA-333v (invalid RPC signature log included HMAC secret + expected signature). Fix commit ee6f79110 (redact credential request headers from audit/notify, backlog#963). rustfs-logging-governance skill.
|
|
||||||
- For any struct in the diff deserialized from untrusted input (S3 XML/JSON, lifecycle rules, bucket policy, replication config, RPC payload), check for #[serde(deny_unknown_fields)]. Construct a payload with a typo'd field (e.g. 'NoncurentDays') or an extra field and prove it is rejected, not silently ignored. Flag #[serde(default)] on security-critical fields (retention days, limits, permissions) lacking explicit post-deserialize validation, and any user-controlled integer cast with `as` (i32 as u32) — feed a negative value and check it doesn't wrap to a huge positive.
|
|
||||||
- Where: crates/policy/ (bucket policy), crates/ecstore lifecycle/ILM config, replication config structs, crates/protocols XML parsing
|
|
||||||
- Evidence: AGENTS.md 'Serde Safety'; advisory-patterns.md 'Serde deserialization' (no deny_unknown_fields found repo-wide; 'NoncurentDays' typo silently accepted; i32 as u32 wrap). Fix commit 1acd47f15 (SSE crash-loop DoS + credential reserved-char bypass, backlog#806).
|
|
||||||
- If the diff touches SSE / encryption reader-writer composition, do not trust API metadata claiming encryption. Trace the reader wrapper order (HashReader / EncryptReader / compression / warp) and confirm EncryptReader is actually in the chain that writes to disk — construct the case where a helper unwraps a nested reader and bypasses encryption, storing plaintext. Require a regression test that inspects the ACTUAL stored bytes on disk, not just read-back. Also check encrypted-object checksums are not exposed.
|
|
||||||
- Where: rustfs/src/storage/ecfs.rs, crates/rio/ (reader wrappers), crates/kms/, SSE-C replication
|
|
||||||
- Evidence: GHSA-xrrf-67jm-3c2r (SSE metadata reported encryption while composition bypassed EncryptReader, stored plaintext). Fix commits a7b9659e7 (hide encrypted object checksums, #4529), 80cc3b1fc (preserve SSE-C checksum state, #4410). advisory-patterns.md 'SSE and on-disk storage invariants'.
|
|
||||||
- If the diff touches CORS or the console/browser/object-preview surface: confirm default CORS does not reflect an arbitrary Origin while also sending Access-Control-Allow-Credentials: true — construct a request with a spoofed Origin and check the response. For preview, confirm attacker-controlled object content is origin-isolated (not rendered in a same-origin iframe with console creds), served with nosniff/CSP, and that preview trust derives from validated content-type + sandboxing, NOT from object name/extension (.pdf, .html). Separately, if aws:SourceIp is evaluated, spoof X-Forwarded-For / X-Real-IP as a direct (non-trusted-proxy) client and confirm the socket peer IP is used instead.
|
|
||||||
- Where: rustfs/src/server/layer.rs (CORS), console preview/auth code, aws:SourceIp / policy condition evaluation, X-Forwarded-For handling
|
|
||||||
- Evidence: GHSA-x5xv-223c-8vm7 (default CORS reflected arbitrary origins with credentials), GHSA-v9fg-3cr2-277j (preview rendered attacker HTML same-origin, exposed localStorage creds), GHSA-7gcx-wg4x-q9x6 (extension-based PDF detection bypassed sandbox), GHSA-fc6g-2gcp-2qrq (aws:SourceIp trusted client XFF). advisory-patterns.md 'Browser, CORS' + 'Trusted proxy'.
|
|
||||||
|
|
||||||
Null report example: "Attacked admin action-constant matching in the two changed handlers (both call validate_admin_request with the exact AdminAction), the FTPS RETR/SIZE authz parity, and the new lifecycle struct's serde surface (has deny_unknown_fields) — no break found."
|
|
||||||
|
|
||||||
### Concurrency/durability reviewer
|
|
||||||
|
|
||||||
- For every new or moved lock acquisition, enumerate all other code paths that take any overlapping subset of those locks and construct the concrete ABBA interleaving (thread 1 holds A wants B, thread 2 holds B wants A). If the diff acquires 2+ locks without a comment documenting acquisition order, that alone is a finding.
|
|
||||||
- Where: crates/ecstore/** (namespace locks, set_disk, disk registry), crates/audit/**, crates/lock/**, any Mutex/RwLock pair in a diff
|
|
||||||
- Evidence: crates/ecstore/AGENTS.md 'Lock Ordering' (document order; same set in different orders = deadlock); real ABBA deadlock fixed in c0d5f938f (#4421, audit registry vs stream_cancellers)
|
|
||||||
- If the diff touches the object write/commit path or a lock guard's lifetime, construct the timeline where the distributed lock is lost (heartbeat refresh fails / expiry) after shard writes but before the xl.meta rename commit — verify the commit is fenced on guard.is_lock_lost() (set_disk/ops/object.rs:874-880) and the diff does not move the commit outside the fenced region or drop the guard early.
|
|
||||||
- Where: crates/ecstore/src/set_disk/ops/object.rs, ops/multipart.rs, crates/lock/**
|
|
||||||
- Evidence: 1e6207c08 (#4406) fence write commit on lock loss; ddf197ba5 (#4388) heartbeat lock refresh; backlog#899 fencing comment in object.rs
|
|
||||||
- For any change to file creation or write-then-rename: write out the exact syscall order (write tmp -> fdatasync tmp -> rename -> fsync parent dir -> fsync ancestor dirs on first object under a prefix) and simulate a power cut after each step. Flag any dropped/reordered sync, and check the change honors the durability gate (RUSTFS_DRIVE_SYNC_ENABLE, strict/relaxed/none modes, per-bucket overrides) instead of hardcoding one mode. The 'skip tmp parent fsync' optimization is only sound when the file is renamed out of tmp — verify that precondition still holds.
|
|
||||||
- Where: crates/ecstore/src/disk/local.rs, disk/os.rs, disk/fs.rs, crates/ecstore/src/bucket/durability.rs, set_disk/core/io_primitives.rs
|
|
||||||
- Evidence: PR #4221 (the repo previously had no fsync anywhere); 2df315baf/c081586e7 (#4493) fsync ancestor dirs; 062a68d15 (#4387) tmp-parent-fsync skip is rename-conditional; eaff17cad (#4397) durability modes; 54872d52d (#4478) rename_data crash harness exists — extend it for the diff
|
|
||||||
- If the diff touches quorum counting or per-disk error aggregation, construct adversarial error vectors for reduce_errs: nil/placeholder entries, DiskNotFound mixed with FileNotFound, exactly quorum-1 agreeing errors — and show which dominant error wins. Specifically attack the case where offline-disk errors get counted as 'object does not exist', flipping a read/heal decision into data loss. Also check quorum monotonicity: a retry or heal pass must never conclude with a LOWER quorum than the original write.
|
|
||||||
- Where: crates/ecstore/src/disk/error_reduce.rs, crates/ecstore/src/api/mod.rs, set_disk read/heal paths
|
|
||||||
- Evidence: 20d61c73b (#4551) reduce_errs leaked nil placeholder as dominant error; e0619e355 (#4536) DiskNotFound treated as object-not-found in listing; quorum monotonicity flagged as open follow-up to #4221 (#4221 follow-up list); crates/ecstore/AGENTS.md 'Do not weaken quorum checks'
|
|
||||||
- For any multi-disk fan-out (delete, rename, heal write, cleanup), trace each per-disk Result: find any `let _ =`, `.ok()`, or best-effort collapse that keeps a failed disk out of the quorum math. Construct the run where exactly write_quorum-1 disks succeed and prove the op still returns success — that is the bug. Conversely, for heal writes, check one bad target cannot fail the whole heal (best-effort per target).
|
|
||||||
- Where: crates/ecstore/src/set_disk/ops/*.rs, disk/disk_store.rs, crates/heal/**
|
|
||||||
- Evidence: f7d2b2563 (#4546) disk delete/rename failures were swallowed; 47c1e730c (#4545) heal write quorum made best-effort per target; 2b063b0c4 (#4400) disk-replacement heal missed versions
|
|
||||||
- For every new .await placed between a state mutation and its cleanup/commit (or inside select!/timeout/spawned task that can be aborted), construct the cancellation point: client disconnects and the future is dropped exactly there. Enumerate what is left behind — tmp files, incremented counters never decremented, half-written xl.meta, a held permit/waiter — and verify cleanup runs in Drop or the state is re-entrant. Background loops the diff adds must have a hard outer timeout so a wedged awaitee cannot pin them forever.
|
|
||||||
- Where: crates/ecstore/** write paths, crates/object-capacity/** scanners, crates/audit/**, anything using tokio::select! or spawn+abort
|
|
||||||
- Evidence: d608e320f io_uring cancel-safety spike (cancellation known-hard here); 5a372557e (#4533) wedged scans needed hard outer timeout; 7b87d4d13 (#4520) waiter-count leak; e44bece00 (#4497) audit start race + paused drops
|
|
||||||
- If the diff touches metacache/list producers or cursor resume, construct the interleaving where the producer task completes (or errors) while a reader with a saved cursor comes back for the next page — verify a completed producer is tolerated (no error, no hang) and that a re-folded/full page reports truncation instead of silently ending the listing early. Also feed a corrupt/oversized length prefix into any metacache decode the diff touches.
|
|
||||||
- Where: crates/ecstore/src/cache_value/metacache_set.rs, crates/ecstore/src/store/list_objects.rs, crates/filemeta/**
|
|
||||||
- Evidence: 91a23361e (#4531) tolerate completed metacache producers; d91f4d455 (#4538) delimiter re-fold dropped truncation flag; d2c100fd3 (#4226) corrupt length-prefix guard
|
|
||||||
- For multipart changes, construct concurrent operations on the SAME uploadId: put_object_part racing put_object_part (same part number), abort racing complete between the parts listing and the commit rename, and list-parts racing cleanup. Verify every metadata read/list/abort holds the per-uploadId lock, and that part.N.meta cleanup is deferred until AFTER the commit rename — cleanup before commit loses parts on a crash between the two.
|
|
||||||
- Where: crates/ecstore/src/set_disk/ops/multipart.rs, rustfs/src/storage/
|
|
||||||
- Evidence: 3bc8d79fe (#4329) serialize put_object_part per uploadId; 7fb95d4fc (#4428) unlocked upload metadata reads/aborts; 93ffbdb9b (#4437) unlocked part listings; c77c5f047 (#4548) part.N.meta cleanup moved after commit
|
|
||||||
- Any cleanup/rollback logic added near a commit: verify it runs strictly AFTER the commit is durable, is best-effort (its failure must not fail an already-committed write), and is safe under retry — i.e., re-running it after a partial first attempt must never delete the newly-committed data dir or the last surviving copy.
|
|
||||||
- Where: crates/ecstore/src/set_disk/ops/object.rs (rename_data tail), ops/multipart.rs, disk cleanup helpers
|
|
||||||
- Evidence: afc7f1d6f/d908243e6 (#4386, backlog#898) post-commit old-data-dir cleanup had to be made best-effort; e7cc719c1 (#4389) speculative tmp cleanup moved off hot path
|
|
||||||
- If the diff does read-modify-write on any persisted shared state (bucket metadata, notify/target config, queue store), construct two concurrent writers: show whether the second write silently discards the first (lost update) — RMW must be serialized or CAS-guarded. For persisted queues/replay, construct crash-mid-replay and prove entries are neither lost nor delivered twice without an idempotency key.
|
|
||||||
- Where: crates/notify/**, crates/targets/** (queue store, SQL backends), crates/ecstore/src/bucket/metadata_sys.rs
|
|
||||||
- Evidence: 2490d4ee2 (#4425) persisted config RMW lost updates; 08e44b95f (#4505) queue store crash-safety + replay lifecycle; e008cc5da (#4500) SQL backend idempotency
|
|
||||||
- If the diff touches erasure decode/reconstruct or streaming GET, construct the failure mid-stream: shards become inconsistent (or a disk read fails) after N bytes of the body have already been sent — verify the stream surfaces an error to the client instead of ending cleanly at a truncated length. Silent truncation on a 200 response is the known failure mode.
|
|
||||||
- Where: crates/ecstore/src/set_disk/read.rs (reconstruct-read validation, historically ~line 3117), crates/ecstore/src/erasure/coding/decode.rs
|
|
||||||
- Evidence: Known open bug: EC reconstruct-read 'inconsistent shards' mid-GET silently truncates body -> client unexpected EOF; crates/ecstore/AGENTS.md 'explicit failure over silent corruption'
|
|
||||||
|
|
||||||
Null report example: "Attacked lock ordering on the new disk-registry mutex pair, lock-loss fencing across the moved commit, power-cut points around the added rename, and cancellation at the two new awaits — no break found; quorum math and metacache paths untouched by this diff."
|
|
||||||
|
|
||||||
### Compatibility reviewer
|
|
||||||
|
|
||||||
- Grep the diff for raw 'x-rustfs-internal-' or 'x-minio-internal-' string literals used with map.insert/remove/get instead of the metadata_compat helpers. If found, construct the MinIO-written object case: a metadata map containing ONLY 'X-Minio-Internal-<suffix>' (mixed case, no RustFS key) and trace the diff's read path — does it miss the value? Then construct the removal case: does remove leave the twin key behind so a stale MinIO-key value resurrects on next read? Also check the value-type trap: get_bytes has NO case-insensitive fallback (unlike get_str), so a diff that moves a suffix from FileInfo.metadata (String) to meta_sys (Vec<u8>) silently loses mixed-case MinIO keys.
|
|
||||||
- Where: Any code touching FileInfo.metadata / user_defined / meta_sys: crates/ecstore/, crates/filemeta/, rustfs/src/storage/, crates/utils/src/http/metadata_compat.rs
|
|
||||||
- Evidence: Repo-wide invariant in AGENTS.md 'Cross-Cutting Domain Invariants' and CLAUDE.md; helpers and the asymmetry are pinned by tests test_str_lookup_accepts_minio_metadata_case and test_get_bytes_no_case_insensitive_fallback in crates/utils/src/http/metadata_compat.rs
|
|
||||||
- For any diff reading a binary UUID from internal metadata (transitioned-versionID, tier-free-versionID, data_dir), trace the three degenerate inputs — key absent, value empty (b""), value nil UUID — through to the outgoing tier/S3 request. The bug shape to hunt: unwrap_or_default() or Uuid::from_slice(..).unwrap_or(Uuid::nil()) turning 'no value' into Uuid::nil(), which then gets serialized as ?versionId=00000000-... and the remote tier returns NoSuchVersion. The required pattern is .and_then(|v| Uuid::from_slice(&v).ok()).filter(|u| !u.is_nil()).
|
|
||||||
- Where: crates/ecstore/src/bucket/lifecycle/ (bucket_lifecycle_ops.rs, tier_sweeper.rs), crates/ecstore/src/services/tier/warm_backend_*.rs, crates/filemeta/src/filemeta/version.rs
|
|
||||||
- Evidence: Historical production bug documented in docs/operations/tier-ilm-debugging.md ('Nil-UUID versionId sent to tier'); regression tests live in crates/filemeta/src/filemeta/version.rs; follow-up fix 726f3dc18 'accept empty remote version_id in tier recovery paths' (#4552)
|
|
||||||
- For any diff touching tier or replication GET/DELETE against a remote S3 target, enumerate BOTH directions of the versionId contract and trace each: (a) remote version None/"" means the tier bucket is unversioned — the request must carry NO versionId parameter at all (not an empty one, not nil); (b) remote version Some(v) on a versioned target — the versionId MUST be sent, especially on version-purge deletes, or the delete lands on the wrong version / creates a delete marker instead of purging. Check whether the diff collapses these cases through a single Option/String conversion that loses the distinction.
|
|
||||||
- Where: crates/ecstore/src/services/tier/warm_backend*.rs, crates/ecstore/src/bucket/lifecycle/tier_sweeper.rs, replication code under crates/ecstore/src/bucket/
|
|
||||||
- Evidence: Invariant in AGENTS.md and docs/operations/tier-ilm-debugging.md; real bug fixed by 0fad35645 'send versionId on version-purge deletes to generic S3 targets' (#4401) — the versioned direction, and #4552 — the unversioned direction
|
|
||||||
- If the diff changes xl.meta encoding (adds/reorders msgpack header fields, touches FileMeta::marshal_msg or codec.rs encode paths), attack downgrade and cross-vendor parse: encode an object with the new code and decode it with (a) the meta_ver<=3 read path and (b) the real-MinIO fixture tests from #4377. Then check the header signature: is it recomputed over the new bytes, or copied/hardcoded? MinIO validates it; a stale or zero signature makes MinIO reject the file. Finally verify XL_META_VERSION was not silently bumped — old RustFS/MinIO nodes reject meta_ver > 3 during a rolling upgrade.
|
|
||||||
- Where: crates/filemeta/src/filemeta.rs (XL_HEADER_VERSION/XL_META_VERSION, lines ~46-54), crates/filemeta/src/filemeta/codec.rs (check_xl2_v1, decode_xl_headers)
|
|
||||||
- Evidence: Real bug 073bc9675 'compute header signature instead of hardcoding zero' (#4343); format contract pinned in docs/architecture/minio-file-format-compat.md (write meta_ver 3, read <=3, XL2 magic); parity fixtures from a91d9cefc (#4377)
|
|
||||||
- If the diff touches xl.meta / FileInfo decode (into_fileinfo, version parsing, part arrays), construct hostile foreign input: a MinIO- or corruption-shaped msgpack with a parts-count that disagrees with the etags/sizes array lengths, missing optional fields, and a meta_ver 2 object with legacy checksum. Trace whether the new code indexes past an array, panics, or fabricates default values instead of returning a decode error. Run the pinned legacy fixtures (test_issue_2265_legacy_meta_v2_object_compatibility, test_issue_2288) plus the #4377 real-MinIO xl.meta parse tests against the diff.
|
|
||||||
- Where: crates/filemeta/src/ (fileinfo.rs, filemeta.rs, filemeta/codec.rs, filemeta/version.rs)
|
|
||||||
- Evidence: Real bug 7efacbdf9 'validate part array lengths in into_fileinfo' (#4382); legacy meta_ver 2 regression fixtures at crates/filemeta/src/filemeta.rs (~:1130-:1174) cited by docs/architecture/minio-file-format-compat.md
|
|
||||||
- If the diff 'corrects' a formula, constant, or layout that is a byte-for-byte MinIO port (shard-size math, bitrot hash interleaving, erasure distribution, inline-data prefix), treat the correction itself as the bug: verify against legacy on-disk data before accepting. Concretely: run crates/ecstore/tests/legacy_bitrot_read_test.rs and the ECA-18 pinning tests; check whether existing objects written by old RustFS or MinIO still verify byte-for-byte. Known trap examples: bitrot_shard_file_size's bare return for non-streaming algorithms is CORRECT MinIO whole-file behavior, and the 32-byte prefix on inline data is the HighwayHash256 bitrot hash, not corruption.
|
|
||||||
- Where: crates/ecstore/src/erasure/coding/bitrot.rs, crates/ecstore/src/io_support/bitrot.rs, crates/filemeta/src/fileinfo.rs
|
|
||||||
- Evidence: f96314a1d 'pin streaming-only bitrot layout invariant (ECA-18)' (#4553) — audit explicitly decided NOT to change the formula because it breaks legacy interop; #4377 proved the inline-data prefix is the bitrot hash
|
|
||||||
- For any diff that copies object metadata into an S3-client-visible surface (GET/HEAD response headers, notification event userMetadata, ListObjects/replication payloads, copy-object metadata directives), construct an object carrying internal keys under BOTH prefixes and in non-canonical casing ('X-Minio-Internal-Compression') and confirm every one is stripped via is_internal_key (which is case-insensitive) — not by an exact-match filter on one prefix. Leaked internal keys are an API-semantics break and an information leak.
|
|
||||||
- Where: rustfs/src/storage/, crates/notify/, replication and copy_object paths in crates/ecstore/
|
|
||||||
- Evidence: Real bug cf8929189 'strip rustfs/minio internal metadata from event userMetadata' (#4419); is_internal_key contract in crates/utils/src/http/metadata_compat.rs
|
|
||||||
- If the diff touches crates/protos (node.proto, models.fbs) or internode RPC request/response structs, attack the rolling-upgrade interleaving: an old node sends a message without the new field to a new node, and a new node sends the extended message to an old node. Verify proto field numbers are only appended (never reused/renumbered), FlatBuffers tables are only extended at the end, and that an absent new field decodes to a safe default on the receiving side — 'safe' meaning it must not be interpreted as success/authorization (RPC errors fail closed) and must not flip a quorum decision.
|
|
||||||
- Where: crates/protos/ (node.proto, models.fbs, generated/), gRPC transport and dispatch in the internode layer
|
|
||||||
- Evidence: 6f613317f 'optimize gRPC transport' (#4337) shows the wire layer churns; security advisory 68cw fixed by PR#4402 established RPC fail-closed as a repo rule (see .agents/skills/security-advisory-lessons)
|
|
||||||
- For S3 handler diffs, replay the request shapes real clients actually send, not just the canonical one: mc and aws-sdk differ on path normalization (root '//' ListBuckets), virtual-host vs path style, and header casing. Then attack every pagination boundary the diff touches: request exactly max-keys/max-uploads/max-parts items and verify the response returns exactly N (not N+1), sets IsTruncated correctly, and yields a NextMarker/KeyMarker that resumes without skipping or duplicating — construct the N+1st-item case explicitly.
|
|
||||||
- Where: rustfs/src/storage/ S3 handlers, listing paths in crates/ecstore/src/store/ and set_disk/
|
|
||||||
- Evidence: Real bugs 511ad31ba 'normalize root double-slash ListBuckets requests' (#4336) and fefa70b31 'stop ListMultipartUploads from returning one upload past max-uploads' (#4447); docs/architecture/s3-compatibility-matrix.md is the compat source of truth
|
|
||||||
- If the diff changes bucket-metadata (.metadata.bin) or IAM/config parsing structs, run it against the real MinIO RELEASE.2025-07-23 fixtures: the msgpack blob uses PascalCase field names, so any serde rename, field-type change, or derive tweak silently drops MinIO-written fields instead of erroring. Verify parse_all_configs still loads all ten config types from the fixture without loss, and that drop-in migration still decrypts MinIO-encrypted IAM/server config rather than treating ciphertext as corrupt.
|
|
||||||
- Where: crates/ecstore/src/bucket/metadata*, crates/ecstore/src/bucket/migration.rs, IAM/config load paths in crates/iam/ and crates/config/
|
|
||||||
- Evidence: Fixture parity test parses_real_minio_bucket_metadata_blob_without_loss from a91d9cefc (#4377); real bug 717cdd2ab 'decrypt MinIO IAM & server config on drop-in migration' (#4358); format matrix in docs/architecture/minio-file-format-compat.md
|
|
||||||
- If the diff adds a compatibility shim, legacy fallback, wrapper, or old-endpoint alias (grep the diff for 'legacy', 'fallback', 'compat', 'deprecated'), verify two things: (1) it carries a RUSTFS_COMPAT_TODO(<task-id>) marker with an exact removal condition and a matching entry in the register — an unmarked shim becomes permanent dead weight; (2) the fallback's default direction is safe for old data: e.g. a new decode path must fall back to the legacy decode for old objects by default, not gate legacy reads behind an opt-in flag that makes existing data unreadable after upgrade.
|
|
||||||
- Where: Anywhere in the diff; register at docs/architecture/compat-cleanup-register.md; recent example: allow_inplace_legacy_fallback flag in the ecstore erasure codec streaming path
|
|
||||||
- Evidence: docs/architecture/compat-cleanup-register.md review checklist; d232a46b4 wired legacy decode prefetch behind a default-OFF gate while keeping legacy reads working (#4542), with arity fallout fixed in 05890d6e2 (#4573)
|
|
||||||
|
|
||||||
Null report example: "Attacked dual-key metadata writes/removals against MinIO-only-key objects, nil/empty transitioned-versionID paths to the tier, xl.meta encode against meta_ver<=3 decoders and the #4377 real-MinIO fixtures, and proto field-number evolution for old-node/new-node RPC — no compatibility break found."
|
|
||||||
|
|
||||||
### Performance reviewer
|
|
||||||
|
|
||||||
- For each `.clone()` or allocation added to a per-request/per-object path, identify the copied data and execution frequency. Report a finding only for a concrete repeated cost or benchmark regression. Recommend borrowing, moving, `Bytes`/`Arc`, `Cow`, or capacity reservation only when it reduces that cost without obscuring ownership or APIs.
|
|
||||||
- Where: crates/ecstore/src/set_disk/**, crates/ecstore/src/store*.rs, rustfs/src/storage/, crates/filemeta/, request handlers in rustfs/src/
|
|
||||||
- Evidence: crates/ecstore/AGENTS.md 'Allocation Discipline in Hot Paths'; .agents/skills/rust-code-quality/SKILL.md requires a concrete hot-path cost rather than a proxy metric
|
|
||||||
- For every new sync_all/sync_data/fdatasync/flush/File::sync call in the diff, trace the call chain to DurabilityMode / RUSTFS_DRIVE_SYNC_ENABLE resolution (crates/ecstore/src/disk/local.rs:291 DurabilityMode, :347 resolve_durability_mode) and to per-bucket durability overrides. Construct the run where the operator sets mode=none (or legacy RUSTFS_DRIVE_SYNC_ENABLE=false) and the new fsync still fires — that is an ungated durability cost and a regression on 4KiB writes.
|
|
||||||
- Where: crates/ecstore/src/disk/local.rs, crates/ecstore/src/bucket/durability.rs, crates/ecstore/src/set_disk/** (rename_data/commit paths), any crate doing tokio::fs or std::fs writes
|
|
||||||
- Evidence: #4221 fsync work caused a measured -10% 4KiB write regression (#814 investigation), later gated; durability modes added in eaff17cad (#4397), per-bucket tier overrides in 13e48d93a (#4407); 2df315baf (#4493) shows even ancestor-dir fsyncs are routed through the gate
|
|
||||||
- Attack blocking-work placement from both directions: (a) find new synchronous fs calls, hashing, or EC encode/decode executed directly on an async runtime thread without spawn_blocking/block_in_place — construct the stall (a slow disk blocks a worker thread and every task queued on it); (b) find new code that splits one logical disk operation into multiple spawn_blocking hops per object — each hop is a threadpool round-trip, so K hops x N objects multiplies latency. Demand the author justify the placement with the size of the work, not habit.
|
|
||||||
- Where: crates/ecstore/src/disk/local.rs, crates/ecstore/src/erasure_coding/, crates/ecstore/src/bitrot/, crates/rio/
|
|
||||||
- Evidence: 608ab14d7 (#4554, HP-12) folded metadata open+fstat+read into a single spawn_blocking because per-op hops were measurably slow; 8fc637fb1 (#4484) moved the short EC encode inline because block_in_place cost exceeded the work — direction depends on measured work size
|
|
||||||
- For each lock acquisition the diff adds or relocates, mark the guard's live range and list every .await and disk/RPC call inside it. Construct the contention interleaving: N concurrent requests serialize on the guard while the holder waits on IO; for namespace/multipart commit locks, compute worst-case hold time (fsync + rename per disk) against the lock's timeout. Also diff the acquisition order against other paths taking the same locks (ABBA).
|
|
||||||
- Where: crates/ecstore/src/set_disk/** (commit/rename paths), crates/lock/, crates/audit/ registry, any RwLock/Mutex in per-request paths
|
|
||||||
- Evidence: crates/ecstore/AGENTS.md 'Lock Ordering'; c0d5f938f (#4421) fixed a real ABBA deadlock between registry and stream_cancellers; #4370 history: fsync-heavy serial cross-disk commits held a lock long enough to blow test timeouts (#4370)
|
|
||||||
- Trace exactly what executes inside the PUT commit critical section (under the object write lock, between tmp write and rename_data completion) before vs after the diff. Any newly added work there — cleanup, extra stat, additional rename, O_DIRECT write, logging — is an attack target: construct the per-PUT latency delta and demand it be moved off the critical section or parallelized across disks.
|
|
||||||
- Where: crates/ecstore/src/set_disk/ops/*, crates/ecstore/src/disk/local.rs rename_data path
|
|
||||||
- Evidence: Three real optimizations removed exactly this class of regression: e7cc719c1 (#4389) moved speculative PUT-tail tmp cleanup off the hot path, 92c8c6db7 (#4411) moved O_DIRECT shard-writes off the commit critical section, 651ccac13 (#4487) parallelized tmp xl.meta write and shard fdatasync on commit
|
|
||||||
- Find any new loop in a batch API that performs a per-item stat/read/RPC sequentially. Construct the concrete blowup: a 1000-key DeleteObjects or a full listing page -> 1000 serial round-trips added by the diff. Demand either a gate (skip when not needed) or bounded parallelism; for startup/load paths, check for accidental O(n^2) (re-scanning the full list per item).
|
|
||||||
- Where: crates/ecstore/src/store_delete*.rs / batch object APIs, listing/metacache paths, crates/iam/ store loading, crates/heal/
|
|
||||||
- Evidence: a413729b1 (#4398) had to gate and parallelize the DeleteObjects per-object stat fanout after it shipped serial; 16a91c35e (#4537) fixed O(n^2) IAM startup load by chunking — both were diff-introduced fanouts of this exact shape
|
|
||||||
- For every buffer the diff allocates on the encode/decode/shard path, check: is it sized with with_capacity to the EC-expanded block (not the logical size, not default-grown)? Does it copy into a fresh Vec where Bytes::slice/clone (refcount) or the io-core buffer pool would avoid the copy? Does the diff read hash and data in separate passes where one pass suffices? Construct the per-block byte-copy count before vs after. If the diff touches the io-core pool, verify gauge accounting still balances.
|
|
||||||
- Where: crates/ecstore/src/erasure_coding/, crates/ecstore/src/bitrot/, crates/io-core/src/pool.rs, crates/rio/
|
|
||||||
- Evidence: 92bf55ce6 (#4396) fixed a real regression by right-sizing BytesMut encode ingest capacity to the EC-expanded block; 47bee8b31 (#4475) merged bitrot hash+data into one read pass; 7fa3d0d4b (#4534) shows pool gauge accounting is easy to drift when touching buffer reuse
|
|
||||||
- For every logging or instrumentation statement the diff adds, classify the call site frequency: per-request, per-object, per-shard, or per-block. Anything info!/warn!/error! at per-object frequency or higher is a finding — construct the flood (one listing under client cancellation, one 10k-object heal) and count emitted lines. New metrics/timers on the data path must be feature-gated, not always-on. Run scripts/check_logging_guardrails.sh on the diff.
|
|
||||||
- Where: any per-request/per-object code, especially crates/ecstore listing and heal loops, rustfs/src/storage/ handlers; scripts/check_logging_guardrails.sh
|
|
||||||
- Evidence: .agents/skills/rustfs-logging-governance/SKILL.md (trace level for hot-path/repetitive success events); d25ddb0e1 (#4372) fixed real listing-cancellation error-log noise; hotpath instrumentation is deliberately feature-gated (3f13d098b #4394, f262fcfce #4541 HP-14)
|
|
||||||
- Count how many times the diff's request path parses or fetches the same metadata: xl.meta/FileMeta decoded more than once per object, bucket metadata (metadata_sys) re-fetched inside a per-object loop, or the dual x-rustfs-internal/x-minio-internal key lookup re-run repeatedly on the same map. Construct the per-request parse count before vs after; a second full FileMeta decode per GET is a finding.
|
|
||||||
- Where: crates/filemeta/, crates/ecstore/src/set_disk/** read paths, crates/ecstore/src/bucket/metadata_sys.rs, crates/utils/src/http/metadata_compat.rs
|
|
||||||
- Evidence: 608ab14d7 (#4554) exists because redundant metadata-read syscall sequences per object were measurable; CLAUDE.md dual-key metadata convention makes repeated get_bytes lookups an easy hidden double-parse
|
|
||||||
- If the diff touches PUT/GET/commit/erasure paths and claims 'no perf impact', demand numbers, not assertion: run the criterion benches (cargo bench -p ecstore — comparison_benchmark, erasure_benchmark, rename_data_meta_benchmark, single_block_non_inline_benchmark per crates/ecstore/benches/) against origin/main, and for end-to-end paths the warp A/B relative-budget gate (scripts/run_hotpath_warp_ab.sh --baseline-ref origin/main, as .github/workflows/performance-ab.yml runs it). Probe specifically at 4KiB object size — that is where the last real regression hid.
|
|
||||||
- Where: crates/ecstore/benches/, .github/workflows/performance-ab.yml, scripts/run_hotpath_warp_ab.sh
|
|
||||||
- Evidence: crates/ecstore/AGENTS.md: 'Benchmark-sensitive changes should include measurable rationale'; performance-ab.yml (215747022 #4480) is the repo's own relative-budget gate; the #4221 regression was only visible at 4KiB writes (#814 bisect)
|
|
||||||
|
|
||||||
Null report example: "Attacked the new rename_data commit-section work, durability-gate routing of the added fdatasync, guard live-range across the shard-write awaits, and per-object clone count in the PUT path; ran comparison_benchmark + rename_data_meta_benchmark vs origin/main (4KiB delta within noise) — no break found."
|
|
||||||
|
|
||||||
### Test-coverage skeptic
|
|
||||||
|
|
||||||
- For every testable behavior claim in the PR description, revert that hunk and name the focused test or executable check that detects the revert. If no reasonable check exists, require the reason and residual risk from the validation floor. Especially verify the check exercises the real production path, not a lookalike helper.
|
|
||||||
- Where: All crates; highest value in crates/ecstore, rustfs/src/storage, crates/heal
|
|
||||||
- Evidence: AGENTS.md testable-behavior exit criterion. Real bug: PR #4220 (ghost-directory cleanup) merged with green tests but its fix never executed on the real delete path — required follow-up rustfs#4307, backlog#798 stayed OPEN. The tests exercised a path the production flow never took.
|
|
||||||
- Read each added/modified test and confirm it asserts the real outcome (returned value, stored bytes, error variant), not merely 'call succeeded' or 'no panic'. Flag any test whose only observable is that the function returned, and any `assert!(result.is_err())` that never checks WHICH error. Then check: does the test prove the exploit/failure form is denied, or only that the intended form still works?
|
|
||||||
- Where: crates/e2e_test (security_boundary_test.rs pattern), and every #[cfg(test)] module in the diff
|
|
||||||
- Evidence: Commit dee8e4e63 (#4466) had to rewrite 277 lines of crates/e2e_test/src/security_boundary_test.rs because 'security boundary tests' passed without asserting real outcomes. .agents/skills/rust-code-quality/SKILL.md requires an observable failure criterion; .agents/skills/security-advisory-lessons/SKILL.md asks whether the exploit form is denied.
|
|
||||||
- When the diff adds a boolean/mode parameter or config flag, find the test that fails if the flag's effect is INVERTED inside the changed function. Tests that were mechanically updated to pass `false`/default at every call site assert nothing about the new behavior. Execute the check: flip the flag's branch in the source and confirm at least one test goes red for each branch.
|
|
||||||
- Where: crates/ecstore/src/set_disk/ (e.g. build_codec_streaming_part_reader), any function gaining a parameter
|
|
||||||
- Evidence: Commit 05890d6e2 (#4573): PR #4560 added a 15th param allow_inplace_legacy_fallback; the arity tests were fixed by passing `false` everywhere — they assert Err outcomes independent of the flag, so the fallback behavior itself has no revert-detecting test at those sites.
|
|
||||||
- Mutation spot-check on error propagation: for each newly added `?`, `return Err`, or error-mapping line, mentally replace it with `Ok(default)`/ignore and ask which test fails. The swallowed-error bug class recurs in this repo and always ships with green tests — a fix that propagates errors needs a test that injects the failure (faulty disk, failed rename, dispatch error) and asserts the caller sees Err.
|
|
||||||
- Where: crates/ecstore (disk delete/rename, reduce_errs), crates/audit, crates/notify, crates/targets
|
|
||||||
- Evidence: Three recent fixes for the same class: f7d2b2563 (#4546, disk delete/rename failures swallowed), dbc628f16 (#4424, audit dispatch failures swallowed), 20d61c73b (#4551, reduce_errs leaking nil placeholder as dominant error). All existed while tests were green.
|
|
||||||
- Any test touching GET/read/reconstruct/stream paths must assert the FULL body content and exact length against a known value, not status-ok or first-bytes. Construct the degraded-read case (missing/inconsistent shards forcing EC reconstruction) and assert byte-for-byte equality; a mid-stream failure that truncates the body passes every test that only checks headers or the first chunk.
|
|
||||||
- Where: crates/ecstore/src/set_disk/read.rs and ops/, crates/rio, crates/e2e_test GET scenarios
|
|
||||||
- Evidence: Known live bug: EC reconstruct-read verification failure mid-GET at set_disk read path silently truncates the body → client 'unexpected EOF'; version-independent, undetected by existing suites because none assert full-body integrity under shard inconsistency.
|
|
||||||
- For on-disk / on-wire format changes (xl.meta, .metadata.bin, bitrot framing), reject round-trip-only tests: a struct serialized and deserialized by the same code under test cannot catch format drift. Demand the test parse a REAL captured fixture from crates/filemeta/tests/fixtures, crates/ecstore/tests/fixtures, or crates/rio-v2/tests/minio_fixture_lab — or capture a new one from a single-disk MinIO instance (RELEASE.2025-07-23 procedure from #4377).
|
|
||||||
- Where: crates/filemeta, crates/ecstore (headers, msgpack bucket metadata), crates/rio-v2, migration code
|
|
||||||
- Evidence: Commit 073bc9675 (#4343): filemeta header signature was hardcoded to zero — round-trip tests passed for months. Commit a91d9cefc (#4377) established the real-MinIO fixture convention (inline/versioned/multipart xl.meta, HighwayHash256-prefixed inline bodies) precisely because synthetic fixtures proved nothing about interop.
|
|
||||||
- Attack new concurrency tests for flakiness-by-construction: grep the added tests for `sleep(`, fixed timeouts under ~30s on lock acquisition, and use of shared global state (disk registry, lock client, GLOBAL_*). Serialized cross-disk commits exceed small lock timeouts under full-suite CI disk load. If the test shares global state or saturates IO, it must join the `ecstore-serial-flaky` nextest test-group in .config/nextest.toml (note: serial_test's #[serial] does NOT work — nextest runs each test in its own process). Require readiness polling, never fixed sleeps.
|
|
||||||
- Where: crates/ecstore tests, crates/e2e_test, .config/nextest.toml
|
|
||||||
- Evidence: Commit 2dfa3d3c3 (#4370): concurrent_resend test flaked with Lock(Timeout 5s) on CI — six legitimate serialized cross-disk commits under IO pressure needed 30s. Commit 7c701d9f2 (#4558) created the nextest test-group after bucket_delete_* raced make_bucket into InsufficientWriteQuorum. 65849740f (#4213) deflaked global-state contamination. crates/e2e_test/AGENTS.md: 'readiness checks and explicit polling over fixed sleep-based timing'.
|
|
||||||
- If the diff writes internal object metadata, run the dual-key mutation: delete the `x-minio-internal-<suffix>` write (keeping only `x-rustfs-internal-`) and check whether any test fails. Because `get_bytes` prefers the RustFS key, every read-back test stays green while MinIO interop is silently broken — coverage must include an assertion that BOTH keys are present in the stored metadata map.
|
|
||||||
- Where: crates/utils/src/http/metadata_compat.rs and all its callers in crates/ecstore and rustfs/src/storage
|
|
||||||
- Evidence: CLAUDE.md domain convention: metadata must be written under both x-rustfs-internal- and x-minio-internal- keys for MinIO interop; get_bytes prefers the RustFS key, making the MinIO-key half of the invariant invisible to read-back tests.
|
|
||||||
- For changed quorum/version/UUID logic, name the tests covering the specific poison values: quorum−1 disks, nil UUID, absent vs empty vs nil-serialized UUID bytes, remote-tier version_id of None/"" (unversioned tier bucket → no versionId sent), and the same metadata read on both MetaObject and MetaDeleteMarker version types. Mutation check: remove a `.filter(|u| !u.is_nil())` guard from the diff and confirm a test fails; if none does, the nil-UUID class is uncovered.
|
|
||||||
- Where: crates/ecstore (tier recovery, heal, quorum paths), crates/filemeta, code reading UUIDs from xl.meta metadata
|
|
||||||
- Evidence: Commit 726f3dc18 (#4552) fixed rejection of empty remote version_id in tier recovery. CLAUDE.md invariant: absent/empty/nil UUID all mean 'no value', not Uuid::nil(). docs/operations/tier-ilm-debugging.md: None/"" tier version means unversioned bucket. df9cbc4ed (#4427): unvalidated distribution values caused shuffle index panic — edge values reached production untested.
|
|
||||||
- For any pagination/limit/truncation change, construct the exact-boundary test: result count == max (page exactly full), max+1, and a delimiter re-fold that lands precisely on the page boundary — assert both the item count AND the is_truncated/continuation marker. Off-by-one at the page boundary is a recurring shipped bug here.
|
|
||||||
- Where: crates/ecstore listing paths (list_objects, ListMultipartUploads, metacache), S3 handlers in rustfs/src/storage
|
|
||||||
- Evidence: Two shipped boundary bugs: fefa70b31 (#4447) ListMultipartUploads returned one upload past max-uploads; d91f4d455 (#4538) delimiter re-fold of a full page lost the truncation flag. Both survived existing tests because no test pinned n == max exactly.
|
|
||||||
- A green focused test is evidence only for the targets it builds. Follow the `AGENTS.md` validation tier: add package-scoped Clippy or broader test-target compilation only when changed targets, features, or dependents remain uncovered; do not require a workspace-wide build by default.
|
|
||||||
- Where: All crates; especially concurrent-branch merges into crates/ecstore
|
|
||||||
- Evidence: #4322 broke main because only cargo test ran (field_reassign_with_default is clippy-only). b06f3df6b (#4441) and 05890d6e2 (#4573): test code broke the workspace test build (E0061) on main after textually-clean merges, failing CI for every open PR.
|
|
||||||
|
|
||||||
Null report example: "Attacked revert-detection for all 3 claimed behaviors (each has a named test that fails on revert), flag-inversion on the new fallback parameter (both branches covered in codec_streaming tests), full-body assertions on the changed GET path, and n==max pagination boundary — no coverage gap found."
|
|
||||||
|
|
||||||
## Sources and maintenance
|
|
||||||
|
|
||||||
Probes are distilled from shipped bugs in git history (commit/PR references
|
|
||||||
above), GitHub security advisories (see the security-advisory-lessons
|
|
||||||
skill), scoped `AGENTS.md` rules, and invariants under `docs/architecture/`
|
|
||||||
and `docs/operations/`. Line numbers drift; re-locate the invariant. Merge
|
|
||||||
new incidents into an existing probe when they share a failure class; add a
|
|
||||||
new probe only for a distinct attack, rather than growing the root policy.
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Compatibility Lens
|
||||||
|
|
||||||
|
- Internal metadata uses `metadata_compat` helpers for dual RustFS/MinIO keys,
|
||||||
|
including mixed casing and removal of both twins.
|
||||||
|
- Binary UUID metadata treats absent, empty, and nil as no value. Unversioned
|
||||||
|
remote tiers receive no `versionId`; versioned purge requests retain the real
|
||||||
|
version ID.
|
||||||
|
- `xl.meta` changes preserve supported header/meta versions, recompute
|
||||||
|
signatures, decode legacy fixtures, and remain readable by old RustFS/MinIO.
|
||||||
|
- Foreign/corrupt metadata validates parallel array lengths and missing fields;
|
||||||
|
it returns a decode error rather than indexing, panicking, or fabricating data.
|
||||||
|
- Do not “correct” byte-for-byte MinIO ports without legacy fixture evidence.
|
||||||
|
Bitrot framing, shard math, distribution, and inline prefixes are contracts.
|
||||||
|
- Client-visible metadata/events strip both internal prefixes
|
||||||
|
case-insensitively.
|
||||||
|
- Proto fields are appended, never reused/renumbered; FlatBuffers tables extend
|
||||||
|
compatibly and absent new fields fail closed where authorization/quorum is
|
||||||
|
involved.
|
||||||
|
- Replay real client request shapes and exact pagination boundaries for S3
|
||||||
|
handler changes.
|
||||||
|
- Bucket metadata/IAM/config parsing remains compatible with pinned real MinIO
|
||||||
|
fixtures and encrypted migration data.
|
||||||
|
- Compatibility shims use `RUSTFS_COMPAT_TODO(<task-id>)`, have a removal
|
||||||
|
condition, and default toward reading old data safely.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Concurrency and Durability Lens
|
||||||
|
|
||||||
|
- For every changed lock, enumerate overlapping lock sets and construct the
|
||||||
|
ABBA interleaving. Multiple-lock order must be documented and consistent.
|
||||||
|
- Mark guard lifetimes and every `.await`, disk, and RPC call inside them.
|
||||||
|
Estimate contention and timeout behavior under concurrent requests.
|
||||||
|
- Object commits remain fenced if the distributed lock is lost after shard
|
||||||
|
writes and before metadata rename.
|
||||||
|
- For write/rename changes, trace `write tmp -> sync tmp -> rename -> sync parent
|
||||||
|
-> sync required ancestors`; simulate a crash after each step and honor the
|
||||||
|
configured durability gate.
|
||||||
|
- Multi-disk fan-out counts every result. Quorum-minus-one cannot become success;
|
||||||
|
heal remains best-effort per target where that is the established contract.
|
||||||
|
- At every new cancellable await between mutation and cleanup/commit, drop the
|
||||||
|
future and inspect leftover files, counters, permits, and replay state.
|
||||||
|
- Multipart operations on the same upload ID are serialized where required;
|
||||||
|
abort/complete/list races cannot delete parts before durable commit.
|
||||||
|
- Post-commit cleanup is best-effort, retry-safe, and cannot fail an already
|
||||||
|
committed write or delete the last surviving copy.
|
||||||
|
- Persisted read-modify-write uses serialization/CAS. Queue replay is crash-safe
|
||||||
|
and duplicate delivery has an idempotency contract.
|
||||||
|
- Streaming reconstruction failures after partial output surface as errors, not
|
||||||
|
successful EOF.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Correctness Lens
|
||||||
|
|
||||||
|
Attack the changed behavior, not every subsystem in the repository.
|
||||||
|
|
||||||
|
- Trace new error paths to the caller. Inject the ignored/wildcard variants and
|
||||||
|
verify they cannot become success, not-found, or a plausible default.
|
||||||
|
- Exercise zero/empty/missing, maximum, and exact-boundary inputs for every
|
||||||
|
changed count, size, index, page limit, or optional value.
|
||||||
|
- For aggregation/quorum changes, test exactly quorum and quorum-minus-one with
|
||||||
|
mixed disk errors and nil/placeholder entries.
|
||||||
|
- For listing/pagination, test `n == max`, `n == max + 1`, delimiter folding,
|
||||||
|
continuation markers, and object/prefix name collisions.
|
||||||
|
- For EC/read/streaming changes, inject failure after partial output and verify
|
||||||
|
the client receives an error rather than a clean truncated body. Assert exact
|
||||||
|
bytes and length.
|
||||||
|
- For multipart/object commits, fail before/after rename and cleanup; committed
|
||||||
|
data must remain readable and pre-commit cleanup must not destroy parts.
|
||||||
|
- For version/index ordering, test `len - 1`, `len`, equal timestamps, missing
|
||||||
|
versions, and deterministic tie-breaking.
|
||||||
|
- For directory-object behavior, trace `__XLDIR__` at the store layer; branches
|
||||||
|
below the layer that sees trailing slashes are dead.
|
||||||
|
- For binary UUID metadata, absent, empty, and nil all mean no value. Never send
|
||||||
|
nil/empty `versionId` to an unversioned tier.
|
||||||
|
- For agent rules/skill routers, test a trigger matrix covering ordinary
|
||||||
|
inquiry, low-risk implementation, explicit review, high-risk code, PR
|
||||||
|
creation, release, and post-PR monitoring. Each case must select only the
|
||||||
|
intended workflow and retain required safety/authorization boundaries.
|
||||||
|
|
||||||
|
Null verdicts name only the probes relevant to the diff.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Performance Lens
|
||||||
|
|
||||||
|
- For added clones/allocations on request/object/block paths, quantify copied
|
||||||
|
data and frequency. Recommend borrowing, move, `Bytes`/`Arc`, `Cow`, or
|
||||||
|
capacity reservation only for a concrete repeated cost.
|
||||||
|
- Route every new sync/flush through the durability-mode and bucket override
|
||||||
|
gates; mode `none` must not pay the new fsync.
|
||||||
|
- Keep blocking filesystem/CPU work off async runtime threads, but do not split
|
||||||
|
one small operation into many `spawn_blocking` round trips.
|
||||||
|
- Measure lock hold time across I/O and compare acquisition order for ABBA.
|
||||||
|
- Keep cleanup, extra stat/rename, and diagnostics out of the PUT commit critical
|
||||||
|
section when they need not be there.
|
||||||
|
- Detect per-item serial I/O/RPC in batch APIs and accidental quadratic scans;
|
||||||
|
use a gate or bounded concurrency when the concrete fan-out warrants it.
|
||||||
|
- Count buffer growth and byte copies in EC/bitrot paths; preserve pool gauge
|
||||||
|
balance and avoid repeated metadata decode/fetch per object.
|
||||||
|
- Repetitive success logs stay at `trace`; metrics/instrumentation on hot paths
|
||||||
|
require an existing gate.
|
||||||
|
- Claims of no impact on PUT/GET/commit/erasure paths need relevant benchmark or
|
||||||
|
A/B evidence, especially for 4 KiB objects.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Security Lens
|
||||||
|
|
||||||
|
Use `security-advisory-lessons` only for a dedicated advisory/security audit.
|
||||||
|
For an ordinary matched diff, attack these boundaries:
|
||||||
|
|
||||||
|
- Admin routes: route registration, whitelist, handler authn, and the exact
|
||||||
|
`AdminAction` must agree. Read-only diagnostics still require admin authz.
|
||||||
|
- IAM/service accounts: treat parent, claims, keys, groups, status, and policy
|
||||||
|
names as attacker-controlled; prove ownership/root authority before writes.
|
||||||
|
- Protocol frontends: every changed/sibling command authorizes the matching S3
|
||||||
|
action before reaching storage.
|
||||||
|
- Secrets/signatures: use constant-time comparison, normalize public failures,
|
||||||
|
keep RPC/root/STS keys independent, and fail closed when secrets are absent.
|
||||||
|
- RPC: bind signatures to the exact method/path and timestamp; reject replay,
|
||||||
|
stale, malformed, truncated, and invalid-enum payloads without panic.
|
||||||
|
- Paths/object/archive entries: reject traversal, absolute/platform escapes,
|
||||||
|
and normalization differences between authz and storage.
|
||||||
|
- Copy/multipart/presigned POST: enforce source, destination, version-aware
|
||||||
|
actions, copy-source conditions, and every signed policy condition.
|
||||||
|
- Logging/errors: never expose credentials, tokens, expected signatures, raw
|
||||||
|
secret-bearing input, or merged configs—including via `Debug` and parse errors.
|
||||||
|
- Untrusted serde: reject unknown fields where compatible and validate
|
||||||
|
security-critical defaults/ranges before numeric conversion.
|
||||||
|
- SSE/browser/CORS/trusted proxy: inspect stored ciphertext and wrapper order;
|
||||||
|
isolate user content; never reflect credentialed arbitrary origins or trust
|
||||||
|
forwarded identity from direct clients.
|
||||||
|
- Object Lock: unreadable/fabricated/unparsable metadata fails closed across
|
||||||
|
foreground, lifecycle, scanner, and force-delete paths.
|
||||||
|
|
||||||
|
Security findings distinguish unauthenticated compromise from a
|
||||||
|
low-privileged authenticated bypass.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Simplicity Lens
|
||||||
|
|
||||||
|
- Compare the production diff with the smallest equivalent local edit. Fewer
|
||||||
|
lines alone are not evidence; the replacement must preserve correctness,
|
||||||
|
compatibility, readability, and real boundaries.
|
||||||
|
- Search the touched crate, domain owner, `crates/utils`, `crates/common`, and
|
||||||
|
relevant dependencies for each new helper, constant, wrapper, or fixture.
|
||||||
|
- Reject forced reuse when normalization, error, deadline, or durability
|
||||||
|
semantics differ.
|
||||||
|
- Require a concrete trigger for every new defensive branch. Keep boundary
|
||||||
|
checks for disk/RPC/version data and checks immediately before destructive
|
||||||
|
actions.
|
||||||
|
- Flag one-caller helpers only when they merely forward or split a short linear
|
||||||
|
flow without adding domain naming, invariant isolation, or useful context.
|
||||||
|
- Ensure a replacement removes the superseded in-scope path or keeps one
|
||||||
|
canonical core behind a documented compatibility adapter.
|
||||||
|
- Remove narration/change-history comments; preserve concise safety, lock,
|
||||||
|
durability, and compatibility invariants.
|
||||||
|
- Treat tests, fixtures, generated code, and documentation separately from
|
||||||
|
production growth. Do not optimize away meaningful regression coverage.
|
||||||
|
|
||||||
|
A finding must include a concrete smaller design, not a style preference.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Test-Coverage Lens
|
||||||
|
|
||||||
|
- For every behavior claim, name the focused test/check that fails if the
|
||||||
|
changed hunk is reverted. If none is practical, require the reason and
|
||||||
|
residual risk.
|
||||||
|
- Confirm tests exercise the real production path and assert returned values,
|
||||||
|
exact bytes, stored state, or the specific error variant—not only success,
|
||||||
|
`is_err()`, or no panic.
|
||||||
|
- For new flags/modes, verify each branch and ask which test fails if the branch
|
||||||
|
is inverted.
|
||||||
|
- For new error propagation, inject the failure and assert the caller observes
|
||||||
|
it; mentally replacing `?`/`return Err` with success must break a test.
|
||||||
|
- Streaming GET tests assert the complete body and length under degraded reads.
|
||||||
|
- Disk/wire-format tests use pinned foreign/legacy fixtures; same-code
|
||||||
|
round-trips are insufficient for compatibility.
|
||||||
|
- Concurrency tests use readiness polling, isolate global state, and avoid fixed
|
||||||
|
sleeps or unrealistically short timeouts. Use nextest groups when process-level
|
||||||
|
serialization is required.
|
||||||
|
- Internal metadata tests assert both RustFS and MinIO keys, not only read-back
|
||||||
|
through a helper that prefers one key.
|
||||||
|
- Boundary companions are distinct coverage: `n == max` vs `max + 1`, and
|
||||||
|
absent vs empty vs nil UUID.
|
||||||
|
- A focused test proves only the targets/features it builds. Add compilation or
|
||||||
|
Clippy only for uncovered changed targets.
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
---
|
---
|
||||||
name: code-change-verification
|
name: code-change-verification
|
||||||
description: Verify code changes by identifying correctness, regression, security, and performance risks from diffs or patches, then produce prioritized findings with file/line evidence and concrete fixes. Use when reviewing commits, PRs, and merged patches before/after release.
|
description: Review a commit, PR, or merged patch when the user requests ordinary code-change verification. Do not combine with adversarial-validation; use that skill instead for explicitly adversarial, substantial, or high-risk RustFS reviews.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Code Change Verification
|
# Code Change Verification
|
||||||
|
|
||||||
Use this skill to review code changes consistently before merge, before release, and during incident follow-up.
|
Use this skill for an ordinary requested review. If the root policy or user calls
|
||||||
|
for adversarial validation, use `adversarial-validation` instead of running both.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@@ -79,4 +80,3 @@ Run the full checklist in [rust-code-quality](../rust-code-quality/SKILL.md) —
|
|||||||
- Impact: ...
|
- Impact: ...
|
||||||
- Fix suggestion: ...
|
- Fix suggestion: ...
|
||||||
- Validation: ...
|
- Validation: ...
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
interface:
|
interface:
|
||||||
display_name: "Code Change Verification"
|
display_name: "Code Change Verification"
|
||||||
short_description: "Prioritize risks and verify code changes before merge."
|
short_description: "Prioritize risks and verify code changes before merge."
|
||||||
default_prompt: "Inspect a patch or diff, identify correctness/security/regression risks, and return prioritized findings with file/line evidence and fixes."
|
default_prompt: "Use $code-change-verification for an ordinary requested diff review with prioritized findings."
|
||||||
|
|||||||
@@ -1,97 +1,46 @@
|
|||||||
---
|
---
|
||||||
name: pr-creation-checker
|
name: pr-creation-checker
|
||||||
description: Prepare PR-ready diffs by validating scope, checking required verification steps, drafting a compliant English PR title/body, and surfacing blockers before opening or updating a pull request in RustFS.
|
description: Perform the final RustFS PR preflight and draft compliant English title/body metadata immediately before creating or updating a PR. Do not use during implementation or as a second general code review.
|
||||||
---
|
---
|
||||||
|
|
||||||
# PR Creation Checker
|
# PR Creation Checker
|
||||||
|
|
||||||
Use this skill before `gh pr create`, before `gh pr edit`, or when reviewing whether a branch is ready for PR.
|
Use this skill only at the PR boundary. Reuse completed diff review and
|
||||||
|
verification evidence; do not reread the repository or rerun equivalent checks.
|
||||||
|
|
||||||
## Read sources of truth first
|
## Preflight
|
||||||
|
|
||||||
- Read `AGENTS.md`.
|
1. Confirm the branch is based on current `origin/main` and contains only the
|
||||||
- Read `.github/pull_request_template.md`.
|
intended task diff.
|
||||||
- Use `Makefile` and `.config/make/` for local quality commands.
|
2. Inspect `git diff --stat`, `git diff --check`, and changed file names for
|
||||||
- Use `.github/workflows/ci.yml` for CI expectations.
|
secrets, logs, generated artifacts, or unrelated edits.
|
||||||
- Do not restate long command matrices or template sections from memory when the files exist.
|
3. Confirm the checks selected by root `AGENTS.md` passed on the final diff.
|
||||||
|
Do not replace focused behavioral tests with a generic gate or rerun checks
|
||||||
|
already covered by an unchanged umbrella run.
|
||||||
|
4. Read `.github/pull_request_template.md`. Consult `Makefile`, `.config/make/`,
|
||||||
|
or CI only when the required command/current gate is uncertain.
|
||||||
|
5. Return `BLOCKED` for an unclean scope, missing required evidence, failed
|
||||||
|
required checks, or non-compliant metadata.
|
||||||
|
|
||||||
## Workflow
|
## Metadata
|
||||||
|
|
||||||
1. Collect PR context
|
- Title: English Conventional Commit, at most 72 characters, with no tool
|
||||||
- Confirm base branch, current branch, change goal, and scope.
|
prefix.
|
||||||
- Confirm whether the task is: draft a new PR, update an existing PR, or preflight-check readiness.
|
- Body: English, exact template headings, `N/A` where needed, concise rationale,
|
||||||
- Confirm whether the branch includes only intended changes.
|
actual verification commands, and material risks/rollback notes.
|
||||||
|
- Use repository-relative paths; never include local absolute paths.
|
||||||
|
- Keep prose paragraphs on one logical line and never include the literal
|
||||||
|
sequence `\n`.
|
||||||
|
- Use a temporary body file with `gh pr create --body-file` or
|
||||||
|
`gh pr edit --body-file`; never pass multiline Markdown inline.
|
||||||
|
|
||||||
2. Inspect change scope
|
## Output
|
||||||
- Review the diff and summarize what changed.
|
|
||||||
- Inspect `git diff --stat` and `git diff --numstat`; assess production-code growth separately. Tests, fixtures, generated code, and documentation have no growth budget. Treat line counts as signals, not quotas.
|
|
||||||
- Call out unrelated edits, generated artifacts, logs, or secrets as blockers.
|
|
||||||
- Mark risky areas explicitly: auth, storage, config, network, migrations, breaking changes.
|
|
||||||
- Use the simplicity-adversary verdict instead of producing a per-symbol inventory. Block growth only when the review identifies duplication or gives a concrete smaller design that preserves correctness, compatibility, readability, and real boundaries.
|
|
||||||
- Confirm replacement implementations remove the superseded in-scope path or adapt compatibility at the boundary to one canonical core.
|
|
||||||
- Scan the diff for newly added string literals and confirm whether they duplicate values already defined as constants/enums/typed wrappers in the same module or shared modules.
|
|
||||||
- Treat introducing a new hardcoded literal where a project constant already exists as a likely regression risk; require either a refactor to reuse the constant or an explicit exception explanation in the PR body.
|
|
||||||
|
|
||||||
3. Verify readiness requirements
|
- Status: `READY` or `BLOCKED`.
|
||||||
- Select checks from `AGENTS.md` "Verification Before PR" based on the final diff's risk tier. Do not replace a focused behavioral test with `make pre-commit`, or a required high-risk `make pre-pr` with a narrower gate.
|
- Title.
|
||||||
- For focused verification, state why the selected tier is sufficient and list the scope-specific commands in the PR body.
|
- Complete PR body.
|
||||||
- If `make` is unavailable, use the equivalent commands from `.config/make/`.
|
- Verification commands and results.
|
||||||
- Add scope-specific verification commands when the changed area needs more than the baseline.
|
- Risks or `N/A`.
|
||||||
- If required checks fail, stop and return `BLOCKED`.
|
|
||||||
|
|
||||||
4. Draft PR metadata
|
Immediately before the GitHub write, repeat only the five preflight checks above
|
||||||
- Write the PR title in English using Conventional Commits and keep it within 72 characters.
|
against the final head.
|
||||||
- If a generic PR workflow suggests a different title format, ignore it and follow the repository rule instead.
|
|
||||||
- In RustFS, do not use tool-specific prefixes such as `[codex]` when the repository requires Conventional Commits.
|
|
||||||
- Keep the PR body in English.
|
|
||||||
- Use the exact section headings from `.github/pull_request_template.md`.
|
|
||||||
- Fill non-applicable sections with `N/A`.
|
|
||||||
- Include verification commands in the PR description.
|
|
||||||
- Do not include local filesystem paths in the PR body unless the user explicitly asks for them.
|
|
||||||
- Prefer repo-relative paths, command names, and concise summaries over machine-specific paths such as `/Users/...`.
|
|
||||||
|
|
||||||
5. Prepare reviewer context
|
|
||||||
- Summarize why the change exists.
|
|
||||||
- Summarize what was verified.
|
|
||||||
- Call out risks, rollout notes, config impact, and rollback notes when applicable.
|
|
||||||
- Mention assumptions or missing context instead of guessing.
|
|
||||||
|
|
||||||
6. Prepare CLI-safe output
|
|
||||||
- When proposing `gh pr create` or `gh pr edit`, use `--body-file`, never inline `--body` for multiline markdown.
|
|
||||||
- Return a ready-to-save PR body plus a short title.
|
|
||||||
- If not ready, return blockers first and list the minimum steps needed to unblock.
|
|
||||||
|
|
||||||
## Output format
|
|
||||||
|
|
||||||
### Status
|
|
||||||
- `READY` or `BLOCKED`
|
|
||||||
|
|
||||||
### Title
|
|
||||||
- `<type>(<scope>): <summary>`
|
|
||||||
|
|
||||||
### PR Body
|
|
||||||
- Reproduce the repository template headings exactly.
|
|
||||||
- Fill every section.
|
|
||||||
- Omit local absolute paths unless explicitly required.
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
- List each command run.
|
|
||||||
- State pass/fail.
|
|
||||||
|
|
||||||
### Risks
|
|
||||||
- List breaking changes, config changes, migration impact, or `N/A`.
|
|
||||||
|
|
||||||
## Blocker rules
|
|
||||||
|
|
||||||
- Return `BLOCKED` if the checks required by the `AGENTS.md` validation tier have not passed.
|
|
||||||
- Return `BLOCKED` if a documentation-only, agent-instruction-only, or local developer-tooling-only change lacks focused verification for the changed surface.
|
|
||||||
- Return `BLOCKED` if the diff contains unrelated changes that are not acknowledged.
|
|
||||||
- Return `BLOCKED` if required template sections are missing.
|
|
||||||
- Return `BLOCKED` if the title/body is not in English.
|
|
||||||
- Return `BLOCKED` if the title does not follow the repository's Conventional Commit rule.
|
|
||||||
- Return `BLOCKED` if the diff introduces string literals that should use existing constants but did not.
|
|
||||||
- Return `BLOCKED` for production-code growth only when the review identifies a duplicated or superseded implementation, or supplies a concrete smaller design with equivalent semantics. Fewer lines alone are not evidence.
|
|
||||||
|
|
||||||
## Reference
|
|
||||||
|
|
||||||
- Use [pr-readiness-checklist.md](references/pr-readiness-checklist.md) for a short final pass before opening or editing the PR.
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
interface:
|
interface:
|
||||||
display_name: "PR Creation Checker"
|
display_name: "PR Creation Checker"
|
||||||
short_description: "Draft RustFS-ready PRs with checks, template, and blockers."
|
short_description: "Draft RustFS-ready PRs with checks, template, and blockers."
|
||||||
default_prompt: "Inspect a branch or diff, verify required PR checks, and produce a compliant English PR title/body plus blockers or readiness status."
|
default_prompt: "Use $pr-creation-checker for final PR preflight and compliant English title/body metadata."
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
# PR Readiness Checklist
|
|
||||||
|
|
||||||
- Confirm the branch is based on current `main`.
|
|
||||||
- Confirm the diff matches the stated scope.
|
|
||||||
- Confirm no secrets, logs, temp files, or unrelated refactors are included.
|
|
||||||
- Confirm the checks required by the `AGENTS.md` validation tier passed.
|
|
||||||
- For focused verification, confirm it covered the changed surface and the PR body explains why the selected tier is sufficient.
|
|
||||||
- Confirm extra verification commands are listed for risky changes.
|
|
||||||
- Confirm the PR title uses Conventional Commits and stays within 72 characters.
|
|
||||||
- Confirm the PR title does not use tool-specific prefixes such as `[codex]`.
|
|
||||||
- Confirm the PR body is in English.
|
|
||||||
- Confirm the PR body keeps the exact headings from `.github/pull_request_template.md`.
|
|
||||||
- Confirm non-applicable sections are filled with `N/A`.
|
|
||||||
- Confirm the PR body does not include local absolute paths unless explicitly required.
|
|
||||||
- Confirm multiline GitHub CLI commands use `--body-file`.
|
|
||||||
- Confirm new hardcoded string literals were not introduced for values already represented by existing constants/enums (including protocol labels, error identifiers, headers, and metric names), or record a justified exception.
|
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
---
|
---
|
||||||
name: rust-code-quality
|
name: rust-code-quality
|
||||||
description: Enforce Rust-specific code quality rules on every Rust change. Use before merge to catch unwrap abuse, silent truncation, unnecessary cloning, lock ordering violations, recursion risks, and error type anti-patterns.
|
description: Run a focused Rust quality review when the user requests one, when reviewing a Rust PR/commit, or when another selected review workflow delegates Rust-specific checks. Do not auto-load for every implementation edit.
|
||||||
---
|
---
|
||||||
|
|
||||||
# Rust Code Quality Gate
|
# Rust Code Quality Gate
|
||||||
|
|
||||||
Use this skill on every Rust code change to enforce quality rules that `cargo clippy` does not catch.
|
Use this skill for a dedicated Rust review to cover rules that `cargo clippy`
|
||||||
|
does not catch.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ rg -n 'unwrap_or_default\(\)|unwrap_or\(' <changed-files>
|
|||||||
|
|
||||||
## Manual Review Checklist
|
## Manual Review Checklist
|
||||||
|
|
||||||
For every Rust code change, verify:
|
For the Rust diff under review, verify:
|
||||||
|
|
||||||
### Error Handling
|
### Error Handling
|
||||||
- [ ] Every production `unwrap()` or `expect()` is infallible by type or a checked invariant; explain only non-obvious invariants, using an existing type, a useful `expect` message, or a concise comment
|
- [ ] Every production `unwrap()` or `expect()` is infallible by type or a checked invariant; explain only non-obvious invariants, using an existing type, a useful `expect` message, or a concise comment
|
||||||
|
|||||||
@@ -1,107 +1,34 @@
|
|||||||
---
|
---
|
||||||
name: rustfs-logging-governance
|
name: rustfs-logging-governance
|
||||||
description: Standardize and review RustFS logging with structured `tracing` events, lower noise on hot paths, preserve security-sensitive diagnostics, and extend guardrails to prevent legacy logging patterns from returning. Use whenever a change adds or edits any `tracing` macro call (`error!`/`warn!`/`info!`/`debug!`/`trace!`/`#[instrument]`) — including a single log line added in passing while fixing unrelated logic, which is how most new log sites enter the repo — and when reviewing RustFS logs, startup/config diagnostics, cloud metadata logs, request validation logs, or `scripts/check_logging_guardrails.sh`.
|
description: Add or review RustFS `tracing` events with the repository field shape, level policy, privacy boundaries, and guardrails. Use when a change adds or edits a tracing macro/instrumentation site or the logging guardrail script.
|
||||||
---
|
---
|
||||||
|
|
||||||
# RustFS Logging Governance
|
# RustFS Logging Governance
|
||||||
|
|
||||||
Use this skill when RustFS logging needs to be added, cleaned up, reviewed, or protected against regressions.
|
Apply this skill only to changed logging sites; do not turn a local log edit into
|
||||||
|
a broad logging cleanup.
|
||||||
|
|
||||||
## Quick Start
|
## Workflow
|
||||||
|
|
||||||
1. Identify the files whose logs are changing.
|
1. Read the changed function/module context and classify the site as lifecycle,
|
||||||
2. Scan current `tracing` or `log` macros before editing.
|
request/hot path, fallback, external fetch, or summary.
|
||||||
3. Convert sentence-style logs to short event-style logs.
|
2. Match neighboring structured events and reuse existing `EVENT_*`,
|
||||||
4. Demote hot-path success logs unless operators truly need them at `info`.
|
`LOG_COMPONENT_*`, and `LOG_SUBSYSTEM_*` constants.
|
||||||
5. Preserve failure, fallback, and security-relevant diagnostics.
|
3. Put stable fields first (`event`, `component`, `subsystem`, `state`/`result`,
|
||||||
6. Update `scripts/check_logging_guardrails.sh` when a broad cleanup removes a legacy pattern class.
|
then context) and a short label last.
|
||||||
7. Validate with formatting, targeted checks/tests, and the logging guardrail script.
|
4. Select the level by operational meaning:
|
||||||
|
- `error`: behavior/security-affecting failure;
|
||||||
|
- `warn`: degraded/fallback/operator-actionable state;
|
||||||
|
- `info`: low-frequency lifecycle/mode change;
|
||||||
|
- `debug`: targeted diagnostics;
|
||||||
|
- `trace`: repetitive request/object/shard success paths.
|
||||||
|
5. Never log secrets, tokens, auth headers, credential payloads, raw
|
||||||
|
attacker-controlled bodies, or merged config dumps. Error strings and
|
||||||
|
`Debug` output are log surfaces too.
|
||||||
|
6. Prefer one aggregate summary over inventories or startup banners.
|
||||||
|
7. Run `./scripts/check_logging_guardrails.sh` and the checks selected by root
|
||||||
|
`AGENTS.md`.
|
||||||
|
|
||||||
## Core Workflow
|
Read [logging-governance.md](references/logging-governance.md) only for a broad
|
||||||
|
logging audit, event-model migration, or guardrail expansion. Ordinary single-
|
||||||
### 1. Scope the logging surface
|
site edits do not require the full workspace scope map.
|
||||||
|
|
||||||
- Read the changed module in full before touching log lines.
|
|
||||||
- Classify the log site:
|
|
||||||
- lifecycle/startup
|
|
||||||
- request or validation path
|
|
||||||
- background loop or hot path
|
|
||||||
- fallback/degraded behavior
|
|
||||||
- cloud metadata or external fetch path
|
|
||||||
- metrics/config summary
|
|
||||||
- Do not rewrite business logic to make logging easier.
|
|
||||||
|
|
||||||
### 2. Use the RustFS event shape
|
|
||||||
|
|
||||||
- Prefer fields first, message second.
|
|
||||||
- Use short labels, not prose paragraphs.
|
|
||||||
- Default field shape:
|
|
||||||
- `event`
|
|
||||||
- `component`
|
|
||||||
- `subsystem`
|
|
||||||
- `state` or `result`
|
|
||||||
- key context fields
|
|
||||||
- Reuse stable field names and avoid inventing near-duplicates.
|
|
||||||
|
|
||||||
See `references/logging-governance.md` for the event model, level policy, and anti-pattern list.
|
|
||||||
|
|
||||||
### 3. Choose the right level
|
|
||||||
|
|
||||||
- `error`: operation failure that affects behavior or security guarantees.
|
|
||||||
- `warn`: degraded path, fallback, suspicious input, or operator-actionable misconfiguration.
|
|
||||||
- `info`: low-frequency lifecycle or mode selection.
|
|
||||||
- `debug`: targeted diagnostics and low-volume detail.
|
|
||||||
- `trace`: hot-path and repetitive success-path events.
|
|
||||||
|
|
||||||
When in doubt, lower the verbosity of normal success paths and keep structured detail in fields.
|
|
||||||
|
|
||||||
### 4. Preserve security and privacy boundaries
|
|
||||||
|
|
||||||
- Do not log secrets, tokens, auth headers, raw credential payloads, or merged config dumps.
|
|
||||||
- Avoid logging raw forwarded headers or full trusted network inventories above `debug`.
|
|
||||||
- Keep warning/error logs useful without echoing attacker-controlled payloads unnecessarily.
|
|
||||||
|
|
||||||
### 5. Keep summaries aggregated
|
|
||||||
|
|
||||||
- Replace multi-line startup banners or checklist logs with one structured event.
|
|
||||||
- If metrics already express a concept, avoid duplicating it with many `info!` lines.
|
|
||||||
- Prefer counts, modes, and sources over inventories unless debug detail is truly needed.
|
|
||||||
|
|
||||||
### 6. Update guardrails when needed
|
|
||||||
|
|
||||||
- Broad logging cleanup should usually extend `scripts/check_logging_guardrails.sh`.
|
|
||||||
- Add forbidden patterns only for styles the repo has intentionally retired:
|
|
||||||
- sentence-style lifecycle logs
|
|
||||||
- noisy hot-path `info!`
|
|
||||||
- checklist-style summary logs
|
|
||||||
- legacy fallback wording that has been replaced by structured fields
|
|
||||||
- Keep guardrails concrete and grep-friendly.
|
|
||||||
|
|
||||||
### 7. Validate manually
|
|
||||||
|
|
||||||
Use the smallest relevant set:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo fmt --all --check
|
|
||||||
./scripts/check_logging_guardrails.sh
|
|
||||||
cargo check -p <affected-crate>
|
|
||||||
cargo test -p <affected-crate>
|
|
||||||
```
|
|
||||||
|
|
||||||
For broader Rust changes, add:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./scripts/check_unsafe_code_allowances.sh
|
|
||||||
./scripts/check_architecture_migration_rules.sh
|
|
||||||
cargo clippy -p <affected-crates> --all-targets -- -D warnings
|
|
||||||
```
|
|
||||||
|
|
||||||
## RustFS-Specific Notes
|
|
||||||
|
|
||||||
- The durable RustFS logging direction is `event + component + subsystem + state/result + key context fields`.
|
|
||||||
- `crates/concurrency` and `crates/trusted-proxies` are examples of this style for lifecycle, fallback, and cloud metadata logs.
|
|
||||||
- `scripts/check_logging_guardrails.sh` is the enforcement point for preventing removed log styles from returning.
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
- Read `references/logging-governance.md` when you need the detailed field set, anti-pattern examples, or guardrail update checklist.
|
|
||||||
|
|||||||
@@ -1,285 +1,62 @@
|
|||||||
# RustFS Logging Governance Reference
|
# Logging Audit and Migration Reference
|
||||||
|
|
||||||
## Workspace Scope Map
|
Read this reference only for a broad logging audit, an event-model migration,
|
||||||
|
or a change to `scripts/check_logging_guardrails.sh`. Use `Cargo.toml` for the
|
||||||
|
current workspace/crate list instead of maintaining one here.
|
||||||
|
|
||||||
Use `Cargo.toml` `[workspace].members` as the source of truth for crate membership. When doing a broad logging sweep, classify crates by operational role so logs stay consistent within each role.
|
## Audit by Operational Role
|
||||||
|
|
||||||
### Core Server And Request Handling
|
- Server/protocol/admin: lifecycle, authorization failures, request boundaries,
|
||||||
|
and degraded subsystems; avoid normal request success at `info`.
|
||||||
|
- Storage/heal/scanner/capacity: integrity failures and aggregate lifecycle;
|
||||||
|
avoid per-object, per-shard, and folder iteration noise.
|
||||||
|
- IAM/policy/credentials/KMS/crypto: safe identifiers and enforcement results;
|
||||||
|
never emit secrets, claims, payloads, or expected authenticators.
|
||||||
|
- Notify/audit/targets: target lifecycle and batch/backpressure summaries; avoid
|
||||||
|
per-event success logs.
|
||||||
|
- Locking/concurrency/I/O foundations: contention anomalies and state changes;
|
||||||
|
prefer metrics for high-frequency worker/permit signals.
|
||||||
|
- Shared type/schema crates: log at the operational caller boundary unless the
|
||||||
|
crate itself owns the failure context.
|
||||||
|
|
||||||
- `rustfs`
|
## Event Shape
|
||||||
- Role: top-level server, startup, auth, admin wiring, S3 request handling.
|
|
||||||
- Logging focus: startup lifecycle, config summaries, authn/authz failures, protocol entrypoints, degraded subsystems.
|
|
||||||
- `crates/protocols`
|
|
||||||
- Role: protocol integrations such as FTP, SFTP, WebDAV, and related server-side protocol layers.
|
|
||||||
- Logging focus: listener lifecycle, per-protocol enablement/disablement, request bridge failures.
|
|
||||||
- `crates/madmin`
|
|
||||||
- Role: admin API contracts and management interfaces.
|
|
||||||
- Logging focus: admin action boundaries, validation failures, compatibility warnings.
|
|
||||||
- `crates/trusted-proxies`
|
|
||||||
- Role: forwarded IP trust, proxy chain validation, cloud metadata sources.
|
|
||||||
- Logging focus: direct/trusted/fallback decisions, degraded metadata fetches, aggregated config summaries.
|
|
||||||
- `crates/keystone`
|
|
||||||
- Role: Keystone auth integration.
|
|
||||||
- Logging focus: integration enablement, upstream auth failures, config safety without credential leakage.
|
|
||||||
|
|
||||||
### Storage, Healing, And Data Plane
|
Prefer stable fields in this order when available:
|
||||||
|
|
||||||
- `crates/ecstore`
|
1. `event`
|
||||||
- Role: erasure-coded storage implementation and peer/store initialization.
|
2. `component`
|
||||||
- Logging focus: disk/peer lifecycle, storage fallback, object I/O failures, avoid per-object noise.
|
3. `subsystem`
|
||||||
- `crates/heal`
|
4. `state` or `result`
|
||||||
- Role: healing orchestration and repair workflows.
|
5. stable context such as mode, duration, reason, counts, safe identifiers, or
|
||||||
- Logging focus: scheduler lifecycle, repair decisions, backlog or skipped work summaries, avoid repetitive task spam at `info`.
|
capacity/permit values
|
||||||
- `crates/scanner`
|
6. short message label
|
||||||
- Role: data integrity scanning and health monitoring.
|
|
||||||
- Logging focus: scan lifecycle, compaction/deep-heal transitions, lag/backlog, noisy folder iteration should stay at `debug/trace`.
|
|
||||||
- `crates/object-capacity`
|
|
||||||
- Role: capacity scan and refresh core.
|
|
||||||
- Logging focus: refresh lifecycle, degraded capacity sources, aggregate stats rather than per-object chatter.
|
|
||||||
- `crates/filemeta`
|
|
||||||
- Role: file metadata parsing and helpers.
|
|
||||||
- Logging focus: parse failures, schema/format mismatch, avoid dumping raw metadata payloads.
|
|
||||||
- `crates/storage-api`
|
|
||||||
- Role: storage contracts and shared data plane interfaces.
|
|
||||||
- Logging focus: contract mismatch and boundary diagnostics, usually low-volume.
|
|
||||||
- `crates/checksums`
|
|
||||||
- Role: checksum helpers and validation.
|
|
||||||
- Logging focus: integrity failures and compatibility mismatches, not per-chunk success logs.
|
|
||||||
- `crates/zip`
|
|
||||||
- Role: ZIP handling and compression helpers.
|
|
||||||
- Logging focus: parse/extract failures, archive path safety issues, avoid verbose file-by-file success logs.
|
|
||||||
|
|
||||||
### Security, Identity, And Policy
|
Reuse the module's constants and neighboring field names. Do not create aliases
|
||||||
|
for the same concept.
|
||||||
|
|
||||||
- `crates/iam`
|
## Patterns to Retire
|
||||||
- Role: identity and access management.
|
|
||||||
- Logging focus: authz decision boundaries, imported payload safety, do not leak principals, secrets, or claims.
|
|
||||||
- `crates/policy`
|
|
||||||
- Role: policy modeling and evaluation.
|
|
||||||
- Logging focus: deny/allow decision context, parser/validation failures, no raw secret-bearing request dumps.
|
|
||||||
- `crates/credentials`
|
|
||||||
- Role: credential handling.
|
|
||||||
- Logging focus: never log secrets or tokens; only safe identifiers and redacted states.
|
|
||||||
- `crates/kms`
|
|
||||||
- Role: key management service integration.
|
|
||||||
- Logging focus: init/health/fallback, key-source availability, never log key material.
|
|
||||||
- `crates/crypto`
|
|
||||||
- Role: cryptographic helpers and security primitives.
|
|
||||||
- Logging focus: only algorithm or mode state, not plaintext, ciphertext, or secret-derived material.
|
|
||||||
- `crates/security-governance`
|
|
||||||
- Role: security governance contracts.
|
|
||||||
- Logging focus: policy/state transitions and enforcement diagnostics.
|
|
||||||
- `crates/signer`
|
|
||||||
- Role: request signing helpers.
|
|
||||||
- Logging focus: signature validation failures without expected-signature leakage.
|
|
||||||
|
|
||||||
### Notifications, Audit, And Targets
|
- sentence-style lifecycle announcements;
|
||||||
|
- startup banners and checklist lines;
|
||||||
|
- repetitive success logs at `info`/`debug`;
|
||||||
|
- raw inventories when an aggregate count is sufficient;
|
||||||
|
- fallback prose with values embedded in the message;
|
||||||
|
- `?value`/`Debug` output for credential-bearing or attacker-controlled data;
|
||||||
|
- logging a parse input when the malformed input may itself be a secret.
|
||||||
|
|
||||||
- `crates/notify`
|
## Guardrail Changes
|
||||||
- Role: notification dispatch, runtime facade, notifier implementations.
|
|
||||||
- Logging focus: target lifecycle, dispatch summaries, stream lag/backpressure, avoid per-event success spam.
|
|
||||||
- `crates/audit`
|
|
||||||
- Role: audit target fan-out and audit pipeline management.
|
|
||||||
- Logging focus: pipeline lifecycle, target availability, batch dispatch summaries, avoid noisy "started successfully" prose.
|
|
||||||
- `crates/targets`
|
|
||||||
- Role: target-specific configuration and utilities used by fan-out style systems.
|
|
||||||
- Logging focus: target selection, config validation, per-target degraded state.
|
|
||||||
- `crates/s3-types`
|
|
||||||
- Role: S3 event and type definitions.
|
|
||||||
- Logging focus: usually minimal; keep logging at integration boundaries rather than low-level type crates.
|
|
||||||
- `crates/s3-ops`
|
|
||||||
- Role: S3 operation definitions and mapping.
|
|
||||||
- Logging focus: mapping/contract failures, unsupported combinations, not normal-path request spam.
|
|
||||||
|
|
||||||
### Concurrency, Locking, And Runtime Foundations
|
When expanding `scripts/check_logging_guardrails.sh`:
|
||||||
|
|
||||||
- `crates/concurrency`
|
1. Add only files/patterns intentionally migrated in the same change.
|
||||||
- Role: timeout, locking, backpressure, and I/O scheduling facade.
|
2. Keep patterns concrete and grep-friendly.
|
||||||
- Logging focus: lifecycle transitions and degraded states, not high-frequency worker/permit churn at `info`.
|
3. Do not encode a style that remains valid elsewhere as a global ban.
|
||||||
- `crates/lock`
|
4. Run the guardrail script and the root validation tier.
|
||||||
- Role: distributed locking implementation.
|
5. Treat the script as a floor; manually verify level, field shape, and privacy.
|
||||||
- Logging focus: lock lifecycle, contention anomalies, lock ordering or timeout diagnostics.
|
|
||||||
- `crates/tls-runtime`
|
|
||||||
- Role: shared TLS runtime foundation.
|
|
||||||
- Logging focus: certificate lifecycle, reload/fallback, validation failures without sensitive dumps.
|
|
||||||
- `crates/obs`
|
|
||||||
- Role: observability helpers.
|
|
||||||
- Logging focus: this crate shapes other crates' telemetry conventions; avoid recursive or redundant summaries.
|
|
||||||
- `crates/io-core`
|
|
||||||
- Role: zero-copy I/O core primitives.
|
|
||||||
- Logging focus: keep very sparse; prefer metrics unless failures are actionable.
|
|
||||||
- `crates/io-metrics`
|
|
||||||
- Role: I/O metrics collection.
|
|
||||||
- Logging focus: typically minimal; metrics should carry the hot-path signal.
|
|
||||||
- `crates/rio`
|
|
||||||
- Role: Rust I/O utility layer.
|
|
||||||
- Logging focus: compatibility or runtime boundary failures, not fast-path internals.
|
|
||||||
- `crates/rio-v2`
|
|
||||||
- Role: next-generation I/O compatibility layer.
|
|
||||||
- Logging focus: migration/feature-mode differences and degraded fallback between I/O paths.
|
|
||||||
- `crates/utils`
|
|
||||||
- Role: shared helpers.
|
|
||||||
- Logging focus: usually avoid direct logging in generic helpers unless the helper is itself an operational boundary.
|
|
||||||
- `crates/common`
|
|
||||||
- Role: shared data structures and helpers.
|
|
||||||
- Logging focus: same principle as `utils`; prefer callers to log context-rich events.
|
|
||||||
- `crates/config`
|
|
||||||
- Role: configuration management.
|
|
||||||
- Logging focus: config source, fallback, validation, and summary aggregation; avoid dumping merged configs.
|
|
||||||
- `crates/data-usage`
|
|
||||||
- Role: shared data usage models and algorithms.
|
|
||||||
- Logging focus: refresh lifecycle, summary stats, and degraded reads.
|
|
||||||
|
|
||||||
### Schema, Contracts, And API Support
|
Useful search seeds for the changed surface:
|
||||||
|
|
||||||
- `crates/protos`
|
|
||||||
- Role: protobuf definitions.
|
|
||||||
- Logging focus: usually none inside the crate; emit logs at decode/use boundaries.
|
|
||||||
- `crates/extension-schema`
|
|
||||||
- Role: extension schema contracts.
|
|
||||||
- Logging focus: schema validation and compatibility mismatches.
|
|
||||||
- `crates/s3select-api`
|
|
||||||
- Role: S3 Select API interfaces.
|
|
||||||
- Logging focus: request validation and unsupported feature boundaries.
|
|
||||||
- `crates/s3select-query`
|
|
||||||
- Role: S3 Select query engine.
|
|
||||||
- Logging focus: query parse/planning/execution failures, avoid row-level spam.
|
|
||||||
- `crates/protocols`
|
|
||||||
- Role: non-S3 protocol support.
|
|
||||||
- Logging focus: see core server section; keep per-request verbosity below `info`.
|
|
||||||
|
|
||||||
### Testing And Non-Production Crates
|
|
||||||
|
|
||||||
- `crates/e2e_test`
|
|
||||||
- Role: end-to-end tests.
|
|
||||||
- Logging focus: test clarity matters more than production governance, but avoid copying test-only logging style into production crates.
|
|
||||||
|
|
||||||
## Current Guardrail Coverage Map
|
|
||||||
|
|
||||||
`scripts/check_logging_guardrails.sh` currently enforces retired patterns in these high-signal areas:
|
|
||||||
|
|
||||||
- `rustfs/src/main.rs`
|
|
||||||
- `rustfs/src/startup_iam.rs`
|
|
||||||
- `rustfs/src/auth.rs`
|
|
||||||
- `rustfs/src/protocols/client.rs`
|
|
||||||
- `crates/audit/src/pipeline.rs`
|
|
||||||
- `crates/audit/src/system.rs`
|
|
||||||
- `crates/audit/src/global.rs`
|
|
||||||
- `crates/notify/src/config_manager.rs`
|
|
||||||
- `crates/notify/src/runtime_facade.rs`
|
|
||||||
- `crates/notify/src/notifier.rs`
|
|
||||||
- `crates/ecstore/src/store/peer.rs`
|
|
||||||
- `crates/ecstore/src/store/init.rs`
|
|
||||||
- `crates/ecstore/src/tier/tier.rs`
|
|
||||||
- `crates/concurrency/src/workers.rs`
|
|
||||||
- `crates/concurrency/src/manager.rs`
|
|
||||||
- `crates/concurrency/src/lock.rs`
|
|
||||||
- `crates/concurrency/src/deadlock.rs`
|
|
||||||
- `crates/trusted-proxies/src/global.rs`
|
|
||||||
- `crates/trusted-proxies/src/config/loader.rs`
|
|
||||||
- `crates/trusted-proxies/src/proxy/metrics.rs`
|
|
||||||
- `crates/trusted-proxies/src/proxy/validator.rs`
|
|
||||||
- `crates/trusted-proxies/src/proxy/chain.rs`
|
|
||||||
- `crates/trusted-proxies/src/middleware/service.rs`
|
|
||||||
- `crates/trusted-proxies/src/cloud/detector.rs`
|
|
||||||
- `crates/trusted-proxies/src/cloud/ranges.rs`
|
|
||||||
- `crates/trusted-proxies/src/cloud/metadata/aws.rs`
|
|
||||||
- `crates/trusted-proxies/src/cloud/metadata/azure.rs`
|
|
||||||
- `crates/trusted-proxies/src/cloud/metadata/gcp.rs`
|
|
||||||
|
|
||||||
When expanding coverage, prefer crates with:
|
|
||||||
|
|
||||||
- repeated sentence-style lifecycle logs
|
|
||||||
- high-frequency success-path `info!`
|
|
||||||
- startup/config checklist banners
|
|
||||||
- security-sensitive fallback wording
|
|
||||||
- external fetch/retry/fallback flows
|
|
||||||
|
|
||||||
That typically means the next broad candidates are `rustfs`, `crates/notify`, `crates/audit`, `crates/targets`, `crates/heal`, and `crates/scanner`.
|
|
||||||
|
|
||||||
## Event Model
|
|
||||||
|
|
||||||
Prefer this structure when the fields are available:
|
|
||||||
|
|
||||||
- `event`
|
|
||||||
- `component`
|
|
||||||
- `subsystem`
|
|
||||||
- `state` or `result`
|
|
||||||
- stable context fields such as:
|
|
||||||
- `enabled`
|
|
||||||
- `implementation`
|
|
||||||
- `validation_mode`
|
|
||||||
- `peer_ip`
|
|
||||||
- `client_ip`
|
|
||||||
- `proxy_hops`
|
|
||||||
- `duration_ms`
|
|
||||||
- `fallback`
|
|
||||||
- `reason`
|
|
||||||
- `range_count`
|
|
||||||
- `hold_time_ms`
|
|
||||||
- `available_slots`
|
|
||||||
- `total_slots`
|
|
||||||
- `permits_in_use`
|
|
||||||
|
|
||||||
## Level Policy
|
|
||||||
|
|
||||||
- `error`: the operation fails and callers or security guarantees are affected.
|
|
||||||
- `warn`: a degraded path, fallback, suspicious request, or operator-actionable config issue occurs.
|
|
||||||
- `info`: a low-frequency lifecycle or mode transition occurs.
|
|
||||||
- `debug`: useful diagnostics exist but normal operators do not need them all the time.
|
|
||||||
- `trace`: hot-path and repetitive success-path details occur.
|
|
||||||
|
|
||||||
## Preferred Patterns
|
|
||||||
|
|
||||||
- Use a short message label:
|
|
||||||
- `"trusted proxy validation failed"`
|
|
||||||
- `"concurrency manager state changed"`
|
|
||||||
- `"trusted proxy cloud metadata loaded"`
|
|
||||||
- Put key meaning into fields, not only the message text.
|
|
||||||
- Aggregate config or metrics summaries into one log event.
|
|
||||||
|
|
||||||
## Retired Patterns
|
|
||||||
|
|
||||||
These should usually be removed or replaced:
|
|
||||||
|
|
||||||
- Sentence-style lifecycle logs:
|
|
||||||
- `info!("Concurrency manager stopped")`
|
|
||||||
- `info!("Trusted Proxies module initialized")`
|
|
||||||
- Checklist or banner logs:
|
|
||||||
- `info!("=== Application Configuration ===")`
|
|
||||||
- `info!("Available metrics:")`
|
|
||||||
- Hot-path noise:
|
|
||||||
- `info!("worker take, {}", *available)`
|
|
||||||
- `debug!("Proxy validation successful in {:?}", duration)`
|
|
||||||
- Legacy fallback prose:
|
|
||||||
- `"Request from private network but not trusted: ..."`
|
|
||||||
- `"Cloud metadata fetching is disabled"`
|
|
||||||
|
|
||||||
## Guardrail Update Checklist
|
|
||||||
|
|
||||||
When extending `scripts/check_logging_guardrails.sh`:
|
|
||||||
|
|
||||||
1. Add the touched files to `checked_files`.
|
|
||||||
2. Add only legacy patterns that have been intentionally retired.
|
|
||||||
3. Keep patterns literal and grep-friendly.
|
|
||||||
4. Run the guardrail script after changes.
|
|
||||||
5. Avoid adding patterns for logs that are still valid elsewhere in the repo.
|
|
||||||
|
|
||||||
## Validation Checklist
|
|
||||||
|
|
||||||
For logging-only changes:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo fmt --all --check
|
rg -n 'error!|warn!|info!|debug!|trace!|#\[instrument' <changed-paths>
|
||||||
./scripts/check_logging_guardrails.sh
|
rg -n '\?[^,)]|secret|token|credential|authorization|merged_config' <changed-paths>
|
||||||
cargo check -p <affected-crate>
|
|
||||||
cargo test -p <affected-crate>
|
|
||||||
```
|
|
||||||
|
|
||||||
For broader Rust changes:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./scripts/check_unsafe_code_allowances.sh
|
|
||||||
./scripts/check_architecture_migration_rules.sh
|
|
||||||
cargo clippy -p <affected-crates> --all-targets -- -D warnings
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: rustfs-release-publish
|
name: rustfs-release-publish
|
||||||
description: "End-to-end RustFS release pipeline: first publish any merged-but-unreleased rustfs/console changes and wait for its latest Release asset, then bump RustFS version files on main directly to the final target, publish a visible GitHub prerelease from a preview tag without updating latest channels, validate it, and publish the final tag on the SAME commit. Use whenever the user wants to release/publish a RustFS version (发版/发布)."
|
description: "Run the end-to-end RustFS console gate, version bump, preview validation, and final-tag publication pipeline. Use only when the user explicitly asks to release or publish a RustFS version (发版/发布)."
|
||||||
---
|
---
|
||||||
# RustFS Release Publish (preview-validated pipeline)
|
# RustFS Release Publish (preview-validated pipeline)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: rustfs-release-version-bump
|
name: rustfs-release-version-bump
|
||||||
description: "Publish a RustFS alpha/beta/stable release with an auditable flow: confirm target version and scope, update workspace and release assets (including strict rustfs.spec changelog identity/date/version format), run required verification, and finish with commit, push, and GitHub PR creation."
|
description: "Prepare the version-file and release-asset bump for an exact RustFS alpha/beta/stable target, with verification and optional commit/push/PR delivery. Use for an explicit version bump or when invoked by the release-publish workflow."
|
||||||
---
|
---
|
||||||
# RustFS Release Version Bump
|
# RustFS Release Version Bump
|
||||||
|
|
||||||
@@ -81,10 +81,7 @@ Only drop a file when the current repository release process clearly no longer r
|
|||||||
|
|
||||||
4. Verify before shipping
|
4. Verify before shipping
|
||||||
- Run:
|
- Run:
|
||||||
- `cargo fmt --all`
|
|
||||||
- `cargo fmt --all --check`
|
|
||||||
- `make pre-commit`
|
- `make pre-commit`
|
||||||
- If verification passes, run `cargo clean`.
|
|
||||||
- If `make pre-commit` fails, return `BLOCKED` with root cause and do not silently widen scope to fix unrelated issues unless user asks.
|
- If `make pre-commit` fails, return `BLOCKED` with root cause and do not silently widen scope to fix unrelated issues unless user asks.
|
||||||
|
|
||||||
5. Commit strategy
|
5. Commit strategy
|
||||||
@@ -109,10 +106,7 @@ Only drop a file when the current repository release process clearly no longer r
|
|||||||
- `git diff --name-only origin/main...HEAD`
|
- `git diff --name-only origin/main...HEAD`
|
||||||
- `git diff --stat origin/main...HEAD`
|
- `git diff --stat origin/main...HEAD`
|
||||||
- `rg -n "<old_version>|<new_version>" Cargo.toml Cargo.lock README.md README_ZH.md flake.nix helm/rustfs/Chart.yaml rustfs.spec`
|
- `rg -n "<old_version>|<new_version>" Cargo.toml Cargo.lock README.md README_ZH.md flake.nix helm/rustfs/Chart.yaml rustfs.spec`
|
||||||
- `cargo fmt --all`
|
|
||||||
- `cargo fmt --all --check`
|
|
||||||
- `make pre-commit`
|
- `make pre-commit`
|
||||||
- `cargo clean`
|
|
||||||
|
|
||||||
## Output contract
|
## Output contract
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
interface:
|
interface:
|
||||||
display_name: "RustFS Release Bump"
|
display_name: "RustFS Release Bump"
|
||||||
short_description: "Prepare RustFS release branches like PR #2957."
|
short_description: "Prepare RustFS release branches like PR #2957."
|
||||||
default_prompt: "Use $rustfs-release-version-bump to prepare a RustFS release version, ask about any unclear version policy, and finish the commit/push/PR flow."
|
default_prompt: "Use $rustfs-release-version-bump to prepare and verify an exact RustFS release-version bump."
|
||||||
|
|||||||
@@ -1,170 +1,40 @@
|
|||||||
---
|
---
|
||||||
name: security-advisory-lessons
|
name: security-advisory-lessons
|
||||||
description: Apply RustFS security lessons distilled from repository GitHub Security Advisories. Use when making or reviewing RustFS code changes, doing security checks, handling PR review for auth/authz, IAM, storage, RPC, logging, CORS, console/browser, encryption, policy, or endpoint changes, and when deciding which security regression tests are required.
|
description: Perform a dedicated RustFS security/advisory review for authn/authz, IAM, RPC trust, paths, secrets, browser isolation, encryption, Object Lock, or other security boundaries. Use only when the user requests a security/advisory review or an adversarial review explicitly escalates to the full advisory map; do not auto-load solely because code touches a sensitive path.
|
||||||
---
|
---
|
||||||
|
|
||||||
# RustFS Security Advisory Lessons
|
# RustFS Security Advisory Lessons
|
||||||
|
|
||||||
Use this skill as a RustFS-specific security lens before changing or approving code. For the distilled advisory lessons and review patterns, read [advisory-patterns.md](references/advisory-patterns.md).
|
Use this skill as the deep security lens. For a normal adversarial review with a
|
||||||
|
matched security surface, the concise security reference under
|
||||||
|
`adversarial-validation` is sufficient.
|
||||||
|
|
||||||
When currentness matters, fetch the live advisory inventory instead of relying on this skill as a status mirror:
|
## Workflow
|
||||||
|
|
||||||
|
1. Freeze the exact diff/head and identify the changed trust boundaries.
|
||||||
|
2. Read [advisory-patterns.md](references/advisory-patterns.md), then apply only
|
||||||
|
the matching sections. Useful headings are
|
||||||
|
auth/admin, IAM/STS/OIDC, policy/plugins, S3/copy/multipart, protocols, paths,
|
||||||
|
secrets/logging/RPC, browser/CORS/proxy, SSE, Object Lock, and serde.
|
||||||
|
3. Trace unauthenticated, low-privilege, wrong-action/owner/bucket, malformed,
|
||||||
|
and default-config cases. Security decisions must fail closed.
|
||||||
|
4. Require a focused negative regression test for the bypass/exploit form, not
|
||||||
|
only the intended success path. State residual risk when a test is impractical.
|
||||||
|
5. Report proven vulnerabilities separately from defense-in-depth hardening.
|
||||||
|
|
||||||
|
When advisory currentness matters, fetch the live inventory instead of treating
|
||||||
|
the reference as a status mirror:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gh api repos/rustfs/rustfs/security-advisories --paginate \
|
gh api repos/rustfs/rustfs/security-advisories --paginate \
|
||||||
--jq '.[] | {ghsa_id,state,severity,summary,updated_at}'
|
--jq '.[] | {ghsa_id,state,severity,summary,updated_at}'
|
||||||
```
|
```
|
||||||
|
|
||||||
Fetch full advisory details only when the live summary suggests a new or changed lesson:
|
Fetch an individual advisory only when the live summary indicates a new or
|
||||||
|
changed lesson.
|
||||||
|
|
||||||
```bash
|
## Finding Standard
|
||||||
gh api repos/rustfs/rustfs/security-advisories/<GHSA_ID>
|
|
||||||
```
|
|
||||||
|
|
||||||
For the full pattern map, read [advisory-patterns.md](references/advisory-patterns.md).
|
Each finding includes severity, `file:line`, attacker prerequisites, concrete
|
||||||
|
input/path, impact, smallest safe fix, and a regression check. Do not exaggerate
|
||||||
## Workflow
|
unauthenticated impact when the actual issue requires authenticated low privilege.
|
||||||
|
|
||||||
### 1. Scope the change
|
|
||||||
- Identify touched routes, protocol frontends, handlers, storage paths, credentials, logs, browser surfaces, CI/release code, and policy checks.
|
|
||||||
- Treat these paths as security-sensitive by default: `rustfs/src/admin/`, `rustfs/src/storage/`, `rustfs/src/auth.rs`, `rustfs/src/server/layer.rs`, `crates/iam/`, `crates/policy/`, `crates/credentials/`, `crates/ecstore/src/rpc/`, `crates/protocols/`, `crates/rio/`, OIDC/STS federation code, and console preview/auth code.
|
|
||||||
|
|
||||||
### 2. Map to advisory classes
|
|
||||||
- Read [advisory-patterns.md](references/advisory-patterns.md) for matching GHSA lessons.
|
|
||||||
- Do not rely on advisory titles alone. Confirm whether the issue is authentication, authorization, input validation, storage invariant, browser isolation, logging, or operational hardening.
|
|
||||||
|
|
||||||
### 3. Verify fail-closed behavior
|
|
||||||
- Check that unauthenticated, wrong-permission, cross-user, cross-bucket, malformed-input, and default-config cases fail explicitly.
|
|
||||||
- Prefer exact action/permission checks over broad helper calls or inferred ownership.
|
|
||||||
- Confirm lower storage/RPC layers do not bypass checks done in upper layers.
|
|
||||||
|
|
||||||
### 4. Require regression evidence
|
|
||||||
- For behavior changes, add focused negative tests that reproduce the advisory class.
|
|
||||||
- For sensitive fixes, include tests for the bypass form, not only the happy path.
|
|
||||||
- If a test is impractical, explain the residual risk and provide a manual verification command.
|
|
||||||
|
|
||||||
### 5. Report clearly
|
|
||||||
- Lead with concrete findings and file/line evidence.
|
|
||||||
- Separate proven vulnerabilities from hardening risks.
|
|
||||||
- Avoid exaggerating unauthenticated impact when the code actually rejects unauthenticated requests but allows a low-privileged authenticated bypass.
|
|
||||||
|
|
||||||
## Advisory-Derived Guardrails
|
|
||||||
|
|
||||||
### Auth and admin authorization
|
|
||||||
- Every admin or diagnostic route needs an explicit authn and authz story. Route registration, router whitelist, and handler-level authorization must agree.
|
|
||||||
- Match the admin action to the operation exactly. Copy-paste action constants are a known RustFS vulnerability class.
|
|
||||||
- Avoid authentication-only helpers for state-changing admin APIs; use `validate_admin_request` or the established equivalent with the right `AdminAction`.
|
|
||||||
- Read-only admin APIs such as metrics, server info, and diagnostics still require admin authorization; checking only that credentials exist is not enough.
|
|
||||||
- Replication admin reads can expose remote target credentials; list/get target endpoints require replication/admin authorization and must not return secrets to low-privilege callers.
|
|
||||||
- Do not assume admin-action `Resource` scoping constrains blast radius unless the policy engine actually enforces resources for that action.
|
|
||||||
|
|
||||||
### IAM and service accounts
|
|
||||||
- Treat imported IAM payload fields as attacker-controlled: `parent`, `claims`, `accessKey`, `secretKey`, status, policy names, and groups.
|
|
||||||
- For service account create/update/import, prove parent ownership or root/admin authority before writing credentials or claims; an action permission alone must not allow choosing root or another user as `target_user`.
|
|
||||||
- Treat IAM export packages as credential disclosure surfaces; never include plaintext user or service-account secret keys unless the caller is allowed to recover those secrets and the export format is intentionally sealed.
|
|
||||||
- Do not let `deny_only` or "no explicit deny" become an allow decision that skips required allow checks.
|
|
||||||
- Test cross-user list/update/import flows with wrong, correct, self, parent, and root identities.
|
|
||||||
|
|
||||||
### STS, OIDC, and federation flows
|
|
||||||
- Every STS endpoint must have an explicit authentication story: SigV4 where required, OIDC token verification for web identity, and role/session policy validation before issuing credentials.
|
|
||||||
- For web identity, the JWT is the credential; exemption from SigV4 is not itself an authentication bypass. Treat pre-verification claims only as untrusted routing hints, bound token size, normalize public failures, rate-limit discovery, and issue credentials only after signature, issuer, audience, and expiration checks.
|
|
||||||
- JWT session tokens must be signed and verified by a trusted issuer/key path, not by service-account-controlled material or a reused root secret.
|
|
||||||
- JWT verification must enforce required claims and expiration for every bearer token path; "allow missing exp" is never acceptable for user-presented credentials.
|
|
||||||
- Public OIDC bootstrap and callback routes must treat `Host`, `X-Forwarded-Proto`, redirect targets, `state`, and callback parameters as untrusted; credential-bearing redirects require a configured, allowlisted origin.
|
|
||||||
- OIDC discovery and validation URLs are SSRF sinks. Resolve and classify hostnames at connection time, reject rebinding to loopback/private/link-local ranges, and do not rely on literal string checks.
|
|
||||||
|
|
||||||
### IAM policy conditions and plugins
|
|
||||||
- Treat request headers as attacker-controlled even after SigV4; callers sign their own spoofed headers. Do not merge them into server-derived condition keys such as identity, groups, version ID, signature version, JWT, or LDAP claims.
|
|
||||||
- Keep the condition-key namespace explicit. Reserved server-derived keys must reject or ignore colliding headers, while intentional request-header keys such as `s3:x-amz-*` remain available.
|
|
||||||
- Quantified IAM condition tests need partially overlapping multi-value sets. Fully contained and fully disjoint sets cannot distinguish `ForAllValues` from `ForAnyValue` bugs.
|
|
||||||
- External policy plugins must receive the same security context as built-in policy evaluation. If OPA or another plugin depends on existing object tags, load and pass `ExistingObjectTag/*` before the plugin decision.
|
|
||||||
|
|
||||||
### S3 object actions, copy, multipart, and presigned POST
|
|
||||||
- Version-aware object requests need version-aware actions. Explicit `versionId` reads and copy sources must authorize `s3:GetObjectVersion`, not only `s3:GetObject`.
|
|
||||||
- Multipart copy must enforce source `GetObject` and destination `PutObject` semantics equivalent to `CopyObject`, including copy-source and policy conditions.
|
|
||||||
- Do not let `CreateMultipartUpload`, `UploadPartCopy`, `CompleteMultipartUpload`, or `AbortMultipartUpload` return success without authorization.
|
|
||||||
- Fallbacks from version actions to non-version actions must still pass the same public-access-block, anonymous-deny, and post-authorization gates as a direct allow.
|
|
||||||
- Presigned POST policies are server-side contracts. Enforce `content-length-range`, key prefix, exact metadata/content-type, and all signed policy conditions.
|
|
||||||
|
|
||||||
### Protocol frontends and IAM parity
|
|
||||||
- FTP/FTPS, SFTP, gateway, and other protocol drivers must enforce IAM per operation before calling storage backends; authentication to a protocol listener is not authorization.
|
|
||||||
- Match protocol commands to the same S3 actions as HTTP, such as `RETR` to `GetObject`, `SIZE`/`MDTM` to `HeadObject`, `MKD` to `CreateBucket`, and bucket probes to `ListBucket` or `HeadBucket`.
|
|
||||||
- Review every handler in a protocol driver, not only the changed handler, because RustFS advisories show mixed guarded and unguarded siblings in the same driver.
|
|
||||||
- Regression tests for protocol frontends should deny the shared authorization hook and prove the backend is not reached for the denied command.
|
|
||||||
- Compare protocol secrets in constant time, normalize invalid-user and invalid-secret failures where practical, and add rate limiting before exposing password-style protocol endpoints.
|
|
||||||
|
|
||||||
### Paths, object keys, and filesystem access
|
|
||||||
- Never join untrusted bucket/object/RPC path strings onto filesystem roots without normalization and boundary checks.
|
|
||||||
- Reject or safely handle `..`, absolute paths, URL-encoded traversal, platform separators, empty components, and paths that canonicalize outside the intended root.
|
|
||||||
- Validate both S3 object-key paths and internode/RPC disk paths; storage helpers can bypass S3 authorization if they trust already-parsed paths.
|
|
||||||
- Archive auto-extract paths are object keys too. Validate tar/zip entry names before IAM checks and before storage writes, and prove cleaned paths cannot cross bucket or prefix boundaries.
|
|
||||||
|
|
||||||
### Secrets, default credentials, and crypto
|
|
||||||
- Do not ship hard-coded shared tokens, HMAC secrets, private keys, or production test keys.
|
|
||||||
- Defaults for root credentials and internode/RPC auth must fail closed for network-reachable deployments or generate per-install random secrets; warnings alone are not a security boundary.
|
|
||||||
- Keep cryptographic roles separated: root S3 credentials, RPC HMAC keys, and STS/JWT signing keys must not be reused or deterministically derived from each other.
|
|
||||||
- License or token validation must use signatures with embedded public/verifying keys only; do not use private-key decryption as authenticity.
|
|
||||||
- Plan key rotation and key IDs when removing exposed keys.
|
|
||||||
|
|
||||||
### Logging and debug output
|
|
||||||
- Logs must never include access keys beyond safe identifiers, secret keys, session tokens, JWT claims, HMAC secrets, expected signatures, license secrets, or raw response bodies containing credentials.
|
|
||||||
- Treat `Debug` implementations, `?value` tracing, merged config dumps, and dependency-level HTTP body logging as leak surfaces.
|
|
||||||
- Error and panic messages are log content: they propagate through `?` and get printed by `error!`/startup logging far from where they were constructed. Never interpolate a raw config or credential value into an error string.
|
|
||||||
- A value that fails secret-format parsing is usually the secret itself (e.g. a bare base64 key missing its `<name>:` prefix), so a parse-failure hint must name the env var or file and the expected format, never echo the input. Redacting `Debug` impls does not cover this channel.
|
|
||||||
- Add log-capture tests or targeted unit tests for redaction wrappers when changing credential structs or response bodies.
|
|
||||||
|
|
||||||
### RPC, parsing, and panic safety
|
|
||||||
- Treat all RPC payload bytes as attacker-controlled. Replace `unwrap`, `expect`, and panic-prone deserialization with typed errors.
|
|
||||||
- Malformed request tests should cover empty bytes, truncated MessagePack/protobuf, invalid enum values, stale timestamps, and invalid signatures.
|
|
||||||
- RPC authentication must be independently strong; do not depend on S3 admin credentials unless the fallback is explicit and safe.
|
|
||||||
- RPC signatures must bind the exact generated gRPC method path, timestamp, and request method. Service-prefix signatures must not authorize a different concrete NodeService call.
|
|
||||||
|
|
||||||
### Browser, CORS, and console surfaces
|
|
||||||
- Do not reflect arbitrary `Origin` while also allowing credentials. Default CORS should be no CORS unless explicitly configured.
|
|
||||||
- Do not render user-controlled object content in a same-origin iframe with console credentials available to JavaScript.
|
|
||||||
- Prefer origin separation for object preview/download, `nosniff`, CSP, strict content-type handling, and avoiding durable credentials in `localStorage`.
|
|
||||||
- Preview safety must be based on trusted content type and sandboxing, not object names or extensions such as `.pdf`.
|
|
||||||
- Console license/version-like metadata endpoints should expose only coarse public data unless authenticated, especially subject names and expiration timestamps.
|
|
||||||
|
|
||||||
### Profiling, debug, and health endpoints
|
|
||||||
- Profiling and debug endpoints are not health checks. They require admin auth, opt-in enablement, rate limiting, and safe responses.
|
|
||||||
- Do not return absolute filesystem paths or other deployment layout in unauthenticated or low-privilege responses.
|
|
||||||
- Ensure health endpoint allowlists cannot accidentally include expensive diagnostics.
|
|
||||||
|
|
||||||
### Trusted proxy and network identity
|
|
||||||
- Only honor `X-Forwarded-For` or `X-Real-IP` when the request came from a configured trusted proxy.
|
|
||||||
- Apply the same trusted-proxy rule to scheme and host derivation; direct clients must not control security-sensitive redirects through `Host`, `X-Forwarded-Host`, or `X-Forwarded-Proto`.
|
|
||||||
- Direct clients must use the socket peer address for `aws:SourceIp` and policy condition evaluation.
|
|
||||||
- Add tests for direct spoofed headers and trusted-proxy headers.
|
|
||||||
|
|
||||||
### SSE and storage invariants
|
|
||||||
- Encryption metadata is not proof that bytes were encrypted on disk.
|
|
||||||
- When touching reader/writer wrappers such as hashing, encryption, compression, or warp readers, verify wrapper order and inspect stored bytes in regression tests.
|
|
||||||
- Avoid helper shortcuts that unwrap nested readers and accidentally bypass encryption or integrity layers.
|
|
||||||
|
|
||||||
### Object Lock and retention invariants
|
|
||||||
- Object Lock state must fail closed when bucket metadata is unreadable, fabricated, or unparsable. Only a confirmed absence of Object Lock configuration may permit unprotected deletes or writes.
|
|
||||||
- Do not collapse metadata read faults, missing persisted metadata, parse failures, and genuinely absent Object Lock config into one "not configured" result.
|
|
||||||
- Retention enforcement must cover foreground deletes, batch deletes, force-delete helpers, default-retention materialization on PUT, lifecycle expiry, scanner sweeps, and all-versions expiry.
|
|
||||||
|
|
||||||
## Review Prompts
|
|
||||||
|
|
||||||
Use these prompts while reviewing a diff:
|
|
||||||
|
|
||||||
- Could a low-privileged authenticated user reach this path with the wrong action, parent, bucket, or source object?
|
|
||||||
- Does a non-HTTP protocol path call the same authorization boundary as the S3 API before touching storage?
|
|
||||||
- Does a public/default/empty config change security behavior from fail-closed to fail-open?
|
|
||||||
- Is any attacker-controlled value later used as a path, policy condition, credential identity, log field, URL, Origin, or response body?
|
|
||||||
- Does this response contain stored replication, remote target, or service credentials that need redaction or stricter authorization?
|
|
||||||
- Does any error constructor or `format!` interpolate a variable that can hold secret material, including a config parse error that echoes the raw input?
|
|
||||||
- Does an IAM export/import path expose or trust plaintext credential secrets beyond the caller's intended authority?
|
|
||||||
- Can this STS/OIDC path issue credentials without SigV4, trusted issuer validation, allowlisted redirects, or trusted-proxy host/scheme handling?
|
|
||||||
- Can a service-account or STS token omit `exp`, forge `sessionPolicy`, or use a principal-controlled key as signing authority?
|
|
||||||
- Does this outbound validation path resolve attacker-supplied hostnames and reject private, loopback, link-local, and rebound addresses at the actual connection boundary?
|
|
||||||
- Is an archive entry, object key, or policy resource normalized differently between authorization and storage?
|
|
||||||
- Is the same operation implemented in multiple paths, such as `CopyObject` vs `UploadPartCopy`, and do all paths enforce the same security contract?
|
|
||||||
- Does an explicit object version, fallback action, or plugin authorization path pass through the same action and post-authorization gates as the direct S3 path?
|
|
||||||
- Can a caller-controlled header populate a condition key that should be derived only by the server?
|
|
||||||
- Do condition tests include partially overlapping multi-value inputs for quantified operators?
|
|
||||||
- Does unreadable bucket metadata make Object Lock or retention enforcement fail closed rather than disappear?
|
|
||||||
- Does a preview or browser-surface fix preserve the original security invariant when adding alternate viewers or file-type detection?
|
|
||||||
- Does the test prove the exploit form is denied, or only that the intended form still works?
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
interface:
|
interface:
|
||||||
display_name: "Security Advisory Lessons"
|
display_name: "Security Advisory Lessons"
|
||||||
short_description: "Apply advisory lessons in reviews."
|
short_description: "Apply advisory lessons in reviews."
|
||||||
default_prompt: "Review code changes against past RustFS security advisory lessons and report concrete risks, missing tests, and recommended fixes."
|
default_prompt: "Use $security-advisory-lessons for a dedicated RustFS security review grounded in past advisories."
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
sha256-darwin=b4ae71aa894e5c7795ae3eb8116f1777a7601d0f5db3898be2e48faf3329bd9b
|
||||||
|
sha256-linux=433debd9d9defa832986269abdf0f1d131597b2d7a417ce930e17c1fd47d85ba
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
sha256=9b9bc336b43b70d0e06e0adb5455bf035bb18945d85d60936eb6fe4d48e0e680
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
sha256-darwin=55534a97fbd376f64c8f6c341d319017d11ff77cad6da8629a1a7f6a874e0315
|
||||||
|
sha256-linux=c06fb8c19aed6f388b9dc61cb8251b7a44f8561a9bf764ad2b9e635598f8dc17
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
sha256=655a3f3c1d042e694339d15caba7580518320322d1bac0f09450b37e6c09e2e7
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
sha256=ec27cde6ce6400723c4b372bfbd2ac61709c744294e4810af765e8a808d8e31d
|
||||||
@@ -75,6 +75,11 @@ embedded-secrets-check: ## Check no private key material or credential literal i
|
|||||||
@echo "🔑 Checking embedded secret material guard..."
|
@echo "🔑 Checking embedded secret material guard..."
|
||||||
./scripts/check_embedded_secrets.sh
|
./scripts/check_embedded_secrets.sh
|
||||||
|
|
||||||
|
.PHONY: test-wiring-check
|
||||||
|
test-wiring-check: ## Check tests stay registered and selected by their intended runners
|
||||||
|
@echo "🧪 Checking test wiring..."
|
||||||
|
python3 ./scripts/check_test_wiring.py
|
||||||
|
|
||||||
.PHONY: log-analyzer-rules-check
|
.PHONY: log-analyzer-rules-check
|
||||||
log-analyzer-rules-check: core-deps ## Check log-analyzer rule anchors still exist verbatim in source
|
log-analyzer-rules-check: core-deps ## Check log-analyzer rule anchors still exist verbatim in source
|
||||||
@echo "🩺 Checking log-analyzer rule anchors..."
|
@echo "🩺 Checking log-analyzer rule anchors..."
|
||||||
|
|||||||
@@ -19,13 +19,13 @@ planning-docs-check: ## Check that no planning-type documents are committed
|
|||||||
./scripts/check_no_planning_docs.sh
|
./scripts/check_no_planning_docs.sh
|
||||||
|
|
||||||
.PHONY: pre-commit
|
.PHONY: pre-commit
|
||||||
pre-commit: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check doc-paths-check planning-docs-check quick-check ## Run fast pre-commit checks without clippy/full tests
|
pre-commit: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check test-wiring-check doc-paths-check planning-docs-check quick-check ## Run fast pre-commit checks without clippy/full tests
|
||||||
@echo "✅ All pre-commit checks passed!"
|
@echo "✅ All pre-commit checks passed!"
|
||||||
|
|
||||||
.PHONY: pre-pr
|
.PHONY: pre-pr
|
||||||
pre-pr: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check doc-paths-check planning-docs-check log-analyzer-rules-check clippy-check test ## Run full pre-PR checks with clippy and tests
|
pre-pr: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check test-wiring-check doc-paths-check planning-docs-check log-analyzer-rules-check clippy-check test ## Run full pre-PR checks with clippy and tests
|
||||||
@echo "✅ All pre-PR checks passed!"
|
@echo "✅ All pre-PR checks passed!"
|
||||||
|
|
||||||
.PHONY: dev-check
|
.PHONY: dev-check
|
||||||
dev-check: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check doc-paths-check planning-docs-check quick-check ## Run fast local development checks
|
dev-check: fmt-check unsafe-code-check architecture-migration-check logging-guardrails-check tokio-io-uring-check extension-schema-check body-cache-whitelist-check s3s-footprint-check fips-wording-check embedded-secrets-check test-wiring-check doc-paths-check planning-docs-check quick-check ## Run fast local development checks
|
||||||
@echo "✅ Fast development checks passed!"
|
@echo "✅ Fast development checks passed!"
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ script-tests: ## Run shell script tests
|
|||||||
./scripts/test_pinned_paired_abba_bench.sh
|
./scripts/test_pinned_paired_abba_bench.sh
|
||||||
./scripts/test_manual_transition_runbooks.sh
|
./scripts/test_manual_transition_runbooks.sh
|
||||||
./scripts/check_embedded_secrets.sh --self-test
|
./scripts/check_embedded_secrets.sh --self-test
|
||||||
|
python3 ./scripts/check_test_wiring.py --self-test
|
||||||
|
python3 ./scripts/s3-tests/test_report_compat.py
|
||||||
bash -n ./scripts/validate_object_data_cache_cold_stampede.sh
|
bash -n ./scripts/validate_object_data_cache_cold_stampede.sh
|
||||||
python3 ./scripts/check_object_data_cache_follower_samples.py --self-test
|
python3 ./scripts/check_object_data_cache_follower_samples.py --self-test
|
||||||
./scripts/validate_object_data_cache_cold_stampede.sh --self-test
|
./scripts/validate_object_data_cache_cold_stampede.sh --self-test
|
||||||
|
|||||||
+48
-14
@@ -38,10 +38,11 @@ e2e-vault = { max-threads = 1 }
|
|||||||
# replacement_privileged_e2e_test when explicitly run as root on Linux). They
|
# replacement_privileged_e2e_test when explicitly run as root on Linux). They
|
||||||
# are correct in isolation but resource-heavy; serialize them under nextest's
|
# are correct in isolation but resource-heavy; serialize them under nextest's
|
||||||
# process boundary (serial_test's #[serial] does not cross it) so several 4-disk
|
# process boundary (serial_test's #[serial] does not cross it) so several 4-disk
|
||||||
# servers never run at once. ci-7's nightly picks these up via the e2e suite;
|
# servers never run at once. The e2e-full merge/main lane picks these up;
|
||||||
# they are deliberately NOT in the fast PR `e2e-smoke` filter.
|
# they are deliberately NOT in the fast PR `e2e-smoke` filter.
|
||||||
e2e-reliability = { max-threads = 1 }
|
e2e-reliability = { max-threads = 1 }
|
||||||
e2e-inline-boundaries = { max-threads = 1 }
|
e2e-inline-boundaries = { max-threads = 1 }
|
||||||
|
e2e-cluster-nightly = { max-threads = 1 }
|
||||||
|
|
||||||
# --- default profile (local): serialize the flaky groups, never retry --------
|
# --- default profile (local): serialize the flaky groups, never retry --------
|
||||||
[[profile.default.overrides]]
|
[[profile.default.overrides]]
|
||||||
@@ -161,7 +162,7 @@ retries = 2
|
|||||||
# Serialize the 4-disk reliability / degraded-read e2e tests under the ci
|
# Serialize the 4-disk reliability / degraded-read e2e tests under the ci
|
||||||
# profile too (see the e2e-reliability test-group note near the top). Not a
|
# profile too (see the e2e-reliability test-group note near the top). Not a
|
||||||
# quarantine: no retries, just single-threaded so several 4-disk servers never
|
# quarantine: no retries, just single-threaded so several 4-disk servers never
|
||||||
# run concurrently when ci-7's nightly runs the full e2e suite.
|
# run concurrently when e2e-full runs the suite.
|
||||||
[[profile.ci.overrides]]
|
[[profile.ci.overrides]]
|
||||||
filter = 'package(e2e_test) & test(/^(reliability_disk_fault|degraded_read_eof_regression|replacement_privileged_e2e)_test::/)'
|
filter = 'package(e2e_test) & test(/^(reliability_disk_fault|degraded_read_eof_regression|replacement_privileged_e2e)_test::/)'
|
||||||
test-group = 'e2e-reliability'
|
test-group = 'e2e-reliability'
|
||||||
@@ -230,8 +231,8 @@ test-group = 'ecstore-serial-flaky'
|
|||||||
# the nightly profile derives its set as "the replication module MINUS this
|
# the nightly profile derives its set as "the replication module MINUS this
|
||||||
# allowlist", so any new replication test lands in nightly by default (never
|
# allowlist", so any new replication test lands in nightly by default (never
|
||||||
# silently unrun) until it is explicitly blessed as fast here. Keep the two
|
# silently unrun) until it is explicitly blessed as fast here. Keep the two
|
||||||
# regexes byte-identical. Count invariant: 20 here + 49 nightly = 69 total
|
# regexes byte-identical. The committed profile selection digests make changes
|
||||||
# (authority: `cargo nextest list`; docs/testing/e2e-suite-inventory.md).
|
# visible in CI; current counts live in docs/testing/e2e-suite-inventory.md.
|
||||||
# HISTORY (2026-07-11): the 20 fast tests were briefly pulled out of this lane
|
# HISTORY (2026-07-11): the 20 fast tests were briefly pulled out of this lane
|
||||||
# (#4724) because they set a loopback (127.0.0.1) replication target that the
|
# (#4724) because they set a loopback (127.0.0.1) replication target that the
|
||||||
# SSRF egress guard rejected on every PR after repl-1 (#4712). That is fixed —
|
# SSRF egress guard rejected on every PR after repl-1 (#4712). That is fixed —
|
||||||
@@ -327,9 +328,8 @@ slow-timeout = { period = "60s", terminate-after = 2, grace-period = "10s" }
|
|||||||
# the STS dual-node test actually exercises its path (it skips gracefully with
|
# the STS dual-node test actually exercises its path (it skips gracefully with
|
||||||
# a visible log line when awscurl is absent), and routes scheduled failures
|
# a visible log line when awscurl is absent), and routes scheduled failures
|
||||||
# through .github/actions/schedule-failure-issue (ci-8). Explicit division of
|
# through .github/actions/schedule-failure-issue (ci-8). Explicit division of
|
||||||
# labor with ci-5's future e2e-full merge gate: these tests run ONLY here, not
|
# labor with e2e-full: these tests run only in the consolidated nightly
|
||||||
# double-run there. TODO(ci-7): fold this interim repl-owned lane into the ci
|
# workflow, not in the merge/main lane.
|
||||||
# domain's consolidated scheduled e2e workflow once it exists.
|
|
||||||
[profile.e2e-repl-nightly]
|
[profile.e2e-repl-nightly]
|
||||||
default-filter = """
|
default-filter = """
|
||||||
package(e2e_test)
|
package(e2e_test)
|
||||||
@@ -343,26 +343,60 @@ fail-fast = false
|
|||||||
# workflow as the failure-triage artifact.
|
# workflow as the failure-triage artifact.
|
||||||
path = "junit.xml"
|
path = "junit.xml"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# e2e-nightly profile — destructive multi-process cluster fault domains
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# These seven modules are deliberately outside e2e-full's merge budget. Each
|
||||||
|
# starts a real multi-process or multi-disk topology and exercises node/disk
|
||||||
|
# loss, quorum, cleanup, notification fan-in, or admin-timeout behavior. The
|
||||||
|
# consolidated nightly workflow runs them serially to avoid resource
|
||||||
|
# starvation; failures are never retried.
|
||||||
|
[profile.e2e-nightly]
|
||||||
|
default-filter = """
|
||||||
|
package(e2e_test)
|
||||||
|
& test(/^(admin_timeout_regression_test|cluster_concurrency_test|cluster_multidrive_pool_test|heal_erasure_disk_rebuild_test|namespace_lock_quorum_test|object_lambda_test|stale_multipart_cleanup_cluster_test)::/)
|
||||||
|
"""
|
||||||
|
fail-fast = false
|
||||||
|
|
||||||
|
[profile.e2e-nightly.junit]
|
||||||
|
path = "junit.xml"
|
||||||
|
|
||||||
|
[[profile.e2e-nightly.overrides]]
|
||||||
|
filter = 'package(e2e_test)'
|
||||||
|
test-group = 'e2e-cluster-nightly'
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# e2e-protocols profile — serial protocol lane
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# The suite owns fixed ports, so the nightly workflow runs this exact profile
|
||||||
|
# with one nextest worker.
|
||||||
|
[profile.e2e-protocols]
|
||||||
|
default-filter = 'package(e2e_test) & test(/^protocols::/)'
|
||||||
|
fail-fast = false
|
||||||
|
|
||||||
|
[profile.e2e-protocols.junit]
|
||||||
|
path = "junit.xml"
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# e2e-full profile — merge-gate full single-node e2e lane (backlog#1149 ci-5)
|
# e2e-full profile — merge-gate full single-node e2e lane (backlog#1149 ci-5)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# The merge gate (ci.yml `e2e-full` job: push main + merge_group +
|
# The merge gate (ci.yml `e2e-full` job: push main + merge_group +
|
||||||
# workflow_dispatch). Runs the never-automated user-visible suites — KMS (40),
|
# workflow_dispatch). Runs the user-visible KMS, object-lock, multipart-auth,
|
||||||
# object_lock (33), multipart_auth (109), quota, checksum, encryption,
|
# quota, checksum, encryption,
|
||||||
# security-boundary, ... — that the fast PR `e2e-smoke` subset deliberately
|
# security-boundary, ... — that the fast PR `e2e-smoke` subset deliberately
|
||||||
# skips. Budget <= 45 min; authority for the suite count is `cargo nextest list
|
# skips. Budget <= 45 min; authority for the suite count is `cargo nextest list
|
||||||
# --profile e2e-full` (see docs/testing/e2e-suite-inventory.md).
|
# --profile e2e-full` (see docs/testing/e2e-suite-inventory.md).
|
||||||
#
|
#
|
||||||
# The filter is "the whole e2e_test crate MINUS the sets owned by other lanes":
|
# The filter is "the whole e2e_test crate MINUS the sets owned by other lanes":
|
||||||
# * protocols:: — FTPS/SFTP/WebDAV, still pinned to --test-threads=1 by fixed
|
# * protocols:: — FTPS/SFTP/WebDAV, run from the dedicated protocol profile
|
||||||
# ports; they join a scheduled lane once ci-6 randomises the ports (ci-7).
|
# with one worker because the suite owns fixed ports.
|
||||||
# * the 7 cluster suites that spin up a RustFSTestClusterEnvironment
|
# * the 7 cluster suites that spin up a RustFSTestClusterEnvironment
|
||||||
# (cluster_concurrency, cluster_multidrive_pool, stale_multipart_cleanup_cluster,
|
# (cluster_concurrency, cluster_multidrive_pool, stale_multipart_cleanup_cluster,
|
||||||
# namespace_lock_quorum, heal_erasure_disk_rebuild, admin_timeout_regression,
|
# namespace_lock_quorum, heal_erasure_disk_rebuild, admin_timeout_regression,
|
||||||
# object_lambda) — too heavy for the merge budget; they run in ci-7's
|
# object_lambda) — too heavy for the merge budget; they run in the
|
||||||
# nightly 4-node lane.
|
# e2e-nightly serial cluster-fault lane.
|
||||||
# * replication_extension_test — repl-1 already splits it into the PR
|
# * replication_extension_test — repl-1 already splits it into the PR
|
||||||
# `e2e-smoke` (20 fast) and `e2e-repl-nightly` (49 slow) lanes and reserves
|
# `e2e-smoke` (20 fast) and `e2e-repl-nightly` (55 slow) lanes and reserves
|
||||||
# it for those, so e2e-full does not double-run it.
|
# it for those, so e2e-full does not double-run it.
|
||||||
# * #[ignore]d tests — nextest skips them by default (no --run-ignored); the
|
# * #[ignore]d tests — nextest skips them by default (no --run-ignored); the
|
||||||
# manual-localhost:9000 reliant/policy tests are ci-13's migration.
|
# manual-localhost:9000 reliant/policy tests are ci-13's migration.
|
||||||
|
|||||||
@@ -46,10 +46,9 @@ lists when upstream changes.
|
|||||||
the PR.
|
the PR.
|
||||||
- **Weekly + manual**: `.github/workflows/e2e-s3tests.yml` runs the full
|
- **Weekly + manual**: `.github/workflows/e2e-s3tests.yml` runs the full
|
||||||
upstream suite (`TEST_SCOPE=all`) against a Docker deployment (single node
|
upstream suite (`TEST_SCOPE=all`) against a Docker deployment (single node
|
||||||
or a 4-node distributed cluster behind HAProxy). It fails only on
|
or a 4-node distributed cluster behind HAProxy). The canonical gate policy
|
||||||
regressions in the implemented whitelist and publishes a classification
|
and compatibility-report behavior are documented in
|
||||||
report (`compat-report.md`, also shown in the job summary) listing promotion
|
[`scripts/s3-tests/README.md`](../../scripts/s3-tests/README.md).
|
||||||
candidates and unclassified tests.
|
|
||||||
|
|
||||||
## Running Tests Locally
|
## Running Tests Locally
|
||||||
|
|
||||||
|
|||||||
@@ -125,6 +125,9 @@ jobs:
|
|||||||
- name: Check no embedded secret material
|
- name: Check no embedded secret material
|
||||||
run: ./scripts/check_embedded_secrets.sh
|
run: ./scripts/check_embedded_secrets.sh
|
||||||
|
|
||||||
|
- name: Check test wiring
|
||||||
|
run: python3 ./scripts/check_test_wiring.py
|
||||||
|
|
||||||
- name: Check no planning docs committed
|
- name: Check no planning docs committed
|
||||||
run: ./scripts/check_no_planning_docs.sh
|
run: ./scripts/check_no_planning_docs.sh
|
||||||
|
|
||||||
|
|||||||
@@ -160,6 +160,9 @@ jobs:
|
|||||||
- name: Check no embedded secret material
|
- name: Check no embedded secret material
|
||||||
run: ./scripts/check_embedded_secrets.sh
|
run: ./scripts/check_embedded_secrets.sh
|
||||||
|
|
||||||
|
- name: Check test wiring
|
||||||
|
run: python3 ./scripts/check_test_wiring.py
|
||||||
|
|
||||||
- name: Check no planning docs committed
|
- name: Check no planning docs committed
|
||||||
run: ./scripts/check_no_planning_docs.sh
|
run: ./scripts/check_no_planning_docs.sh
|
||||||
|
|
||||||
@@ -397,7 +400,7 @@ jobs:
|
|||||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||||
needs: [ quick-checks ]
|
needs: [ quick-checks ]
|
||||||
runs-on: sm-standard-4
|
runs-on: sm-standard-4
|
||||||
timeout-minutes: 45
|
timeout-minutes: 90
|
||||||
env:
|
env:
|
||||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||||
steps:
|
steps:
|
||||||
@@ -437,7 +440,7 @@ jobs:
|
|||||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||||
needs: [ quick-checks ]
|
needs: [ quick-checks ]
|
||||||
runs-on: sm-standard-4
|
runs-on: sm-standard-4
|
||||||
timeout-minutes: 60
|
timeout-minutes: 90
|
||||||
env:
|
env:
|
||||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||||
steps:
|
steps:
|
||||||
@@ -467,7 +470,7 @@ jobs:
|
|||||||
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
if: github.event_name != 'pull_request' || github.event.action != 'closed'
|
||||||
needs: [ quick-checks ]
|
needs: [ quick-checks ]
|
||||||
runs-on: sm-standard-4
|
runs-on: sm-standard-4
|
||||||
timeout-minutes: 60
|
timeout-minutes: 90
|
||||||
strategy:
|
strategy:
|
||||||
# On a PR, one failing protocol leg is enough to know the PR is not ready,
|
# On a PR, one failing protocol leg is enough to know the PR is not ready,
|
||||||
# so stop the sibling leg instead of paying another ~40 minutes for it.
|
# so stop the sibling leg instead of paying another ~40 minutes for it.
|
||||||
@@ -686,9 +689,9 @@ jobs:
|
|||||||
- name: Make binary executable
|
- name: Make binary executable
|
||||||
run: chmod +x ./target/debug/rustfs
|
run: chmod +x ./target/debug/rustfs
|
||||||
|
|
||||||
# Build the e2e test graph once. The archive is reused by the security
|
# Build the e2e test graph once. The archive is reused by the smoke
|
||||||
# count-floor check and the smoke run below, avoiding a second compile of
|
# selection guard, security exact-count check, and run below, avoiding a
|
||||||
# the same e2e_test target on cold runners (backlog#1645).
|
# second compile of the same e2e_test target on cold runners (backlog#1645).
|
||||||
- name: Archive e2e smoke test binaries
|
- name: Archive e2e smoke test binaries
|
||||||
env:
|
env:
|
||||||
NEXTEST_ARCHIVE: ${{ runner.temp }}/rustfs-e2e-smoke.tar.zst
|
NEXTEST_ARCHIVE: ${{ runner.temp }}/rustfs-e2e-smoke.tar.zst
|
||||||
@@ -696,6 +699,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cargo nextest archive --profile e2e-smoke -p e2e_test --archive-file "${NEXTEST_ARCHIVE}"
|
cargo nextest archive --profile e2e-smoke -p e2e_test --archive-file "${NEXTEST_ARCHIVE}"
|
||||||
cargo nextest list --profile e2e-smoke --archive-file "${NEXTEST_ARCHIVE}" --message-format json > "${NEXTEST_LISTING}"
|
cargo nextest list --profile e2e-smoke --archive-file "${NEXTEST_ARCHIVE}" --message-format json > "${NEXTEST_LISTING}"
|
||||||
|
python3 ./scripts/check_test_wiring.py --check-profile e2e-smoke "${NEXTEST_LISTING}"
|
||||||
./scripts/check_security_smoke_count.sh check "${NEXTEST_LISTING}"
|
./scripts/check_security_smoke_count.sh check "${NEXTEST_LISTING}"
|
||||||
|
|
||||||
# PR smoke subset of the in-repo e2e suite (backlog#1149 ci-4). The
|
# PR smoke subset of the in-repo e2e suite (backlog#1149 ci-4). The
|
||||||
@@ -760,7 +764,7 @@ jobs:
|
|||||||
# suites — KMS, object_lock, multipart_auth, quota, checksum, encryption,
|
# suites — KMS, object_lock, multipart_auth, quota, checksum, encryption,
|
||||||
# security-boundary, ... — via the e2e-full nextest profile. Too heavy for
|
# security-boundary, ... — via the e2e-full nextest profile. Too heavy for
|
||||||
# every PR, so it is gated to main pushes, the merge queue, and manual
|
# every PR, so it is gated to main pushes, the merge queue, and manual
|
||||||
# dispatch. protocols / the 6 cluster suites / replication / #[ignore] are
|
# dispatch. protocols / the 7 cluster suites / replication / #[ignore] are
|
||||||
# owned by other lanes (see .config/nextest.toml profile.e2e-full).
|
# owned by other lanes (see .config/nextest.toml profile.e2e-full).
|
||||||
if: >-
|
if: >-
|
||||||
github.event_name == 'workflow_dispatch' ||
|
github.event_name == 'workflow_dispatch' ||
|
||||||
@@ -820,6 +824,13 @@ jobs:
|
|||||||
- name: Make binary executable
|
- name: Make binary executable
|
||||||
run: chmod +x ./target/debug/rustfs
|
run: chmod +x ./target/debug/rustfs
|
||||||
|
|
||||||
|
- name: Verify e2e full membership
|
||||||
|
env:
|
||||||
|
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-full-list.json
|
||||||
|
run: |
|
||||||
|
cargo nextest list --profile e2e-full -p e2e_test --message-format json > "${NEXTEST_LISTING}"
|
||||||
|
python3 ./scripts/check_test_wiring.py --check-profile e2e-full "${NEXTEST_LISTING}"
|
||||||
|
|
||||||
# Full single-node e2e lane (backlog#1149 ci-5). The e2e-full
|
# Full single-node e2e lane (backlog#1149 ci-5). The e2e-full
|
||||||
# default-filter in .config/nextest.toml is the single wiring mechanism —
|
# default-filter in .config/nextest.toml is the single wiring mechanism —
|
||||||
# extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded
|
# extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded
|
||||||
@@ -832,7 +843,9 @@ jobs:
|
|||||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
with:
|
with:
|
||||||
name: e2e-full-junit-${{ github.run_number }}
|
name: e2e-full-junit-${{ github.run_number }}
|
||||||
path: target/nextest/e2e-full/junit.xml
|
path: |
|
||||||
|
target/nextest/e2e-full/junit.xml
|
||||||
|
${{ runner.temp }}/rustfs-e2e-full-list.json
|
||||||
retention-days: 7
|
retention-days: 7
|
||||||
|
|
||||||
e2e-tests-rio-v2:
|
e2e-tests-rio-v2:
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
# Nightly full replication e2e lane (backlog#1147 repl-1, deps: ci-4).
|
# Consolidated nightly e2e lane for replication, cluster faults, and protocols.
|
||||||
#
|
#
|
||||||
# The per-PR gate (ci.yml `e2e-tests` job, `--profile e2e-smoke`) runs the
|
# The per-PR gate (ci.yml `e2e-tests` job, `--profile e2e-smoke`) runs the
|
||||||
# FAST replication tests. This scheduled lane runs the remaining heavier
|
# FAST replication tests. This scheduled lane runs the remaining heavier
|
||||||
@@ -28,15 +28,12 @@
|
|||||||
# add ad-hoc cargo-test steps here; change the filterset instead. The
|
# add ad-hoc cargo-test steps here; change the filterset instead. The
|
||||||
# authoritative membership and count come from
|
# authoritative membership and count come from
|
||||||
# `cargo nextest list -p e2e_test --profile e2e-repl-nightly`; the PR/nightly
|
# `cargo nextest list -p e2e_test --profile e2e-repl-nightly`; the PR/nightly
|
||||||
# count invariant is maintained next to the filtersets in .config/nextest.toml
|
# selection digest is committed under .config/.
|
||||||
# (deliberately not duplicated here).
|
|
||||||
#
|
#
|
||||||
# Explicit division of labor: the nightly subset runs ONLY here, never double-run
|
# Explicit division of labor: these subsets run only here and never double-run
|
||||||
# in ci-5's future e2e-full merge gate. TODO(ci-7): once the ci domain's
|
# in the e2e-full merge gate.
|
||||||
# consolidated scheduled e2e workflow exists, fold this interim repl-owned lane
|
|
||||||
# into it rather than growing a second scheduled entrypoint.
|
|
||||||
|
|
||||||
name: e2e-replication-nightly
|
name: e2e-nightly
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
@@ -50,6 +47,10 @@ on:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
repl-nightly:
|
repl-nightly:
|
||||||
name: Replication e2e (nightly)
|
name: Replication e2e (nightly)
|
||||||
@@ -97,9 +98,20 @@ jobs:
|
|||||||
# demand otherwise, but a single explicit build avoids several parallel
|
# demand otherwise, but a single explicit build avoids several parallel
|
||||||
# nextest test processes racing to build it at once.
|
# nextest test processes racing to build it at once.
|
||||||
- name: Build rustfs binary
|
- name: Build rustfs binary
|
||||||
run: cargo build -p rustfs --bins
|
run: |
|
||||||
|
cargo build -p rustfs --bins
|
||||||
|
: > target/debug/rustfs.features
|
||||||
|
|
||||||
|
- name: Verify replication e2e membership
|
||||||
|
env:
|
||||||
|
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
|
||||||
|
run: |
|
||||||
|
cargo nextest list --profile e2e-repl-nightly -p e2e_test --message-format json > "${NEXTEST_LISTING}"
|
||||||
|
python3 ./scripts/check_test_wiring.py --check-profile e2e-repl-nightly "${NEXTEST_LISTING}"
|
||||||
|
|
||||||
- name: Run replication e2e nightly suite
|
- name: Run replication e2e nightly suite
|
||||||
|
env:
|
||||||
|
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-repl-nightly-logs
|
||||||
run: cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
run: cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
||||||
|
|
||||||
- name: Upload nextest junit report
|
- name: Upload nextest junit report
|
||||||
@@ -107,13 +119,112 @@ jobs:
|
|||||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
with:
|
with:
|
||||||
name: e2e-replication-nightly-junit-${{ github.run_number }}
|
name: e2e-replication-nightly-junit-${{ github.run_number }}
|
||||||
path: target/nextest/e2e-repl-nightly/junit.xml
|
path: |
|
||||||
|
target/nextest/e2e-repl-nightly/junit.xml
|
||||||
|
${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
|
||||||
|
${{ runner.temp }}/rustfs-e2e-repl-nightly-logs/
|
||||||
retention-days: 7
|
retention-days: 7
|
||||||
if-no-files-found: ignore
|
if-no-files-found: ignore
|
||||||
|
|
||||||
|
cluster-nightly:
|
||||||
|
name: Cluster fault e2e (nightly)
|
||||||
|
runs-on: sm-standard-4
|
||||||
|
timeout-minutes: 90
|
||||||
|
env:
|
||||||
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Setup Rust environment
|
||||||
|
uses: ./.github/actions/setup
|
||||||
|
with:
|
||||||
|
rust-version: stable
|
||||||
|
cache-shared-key: ci-e2e-nightly
|
||||||
|
cache-save-if: 'false'
|
||||||
|
install-build-packaging-tools: 'false'
|
||||||
|
|
||||||
|
- name: Build rustfs binary
|
||||||
|
run: |
|
||||||
|
cargo build -p rustfs --bins --features e2e-test-hooks
|
||||||
|
: > target/debug/rustfs.features
|
||||||
|
|
||||||
|
- name: Verify cluster fault e2e membership
|
||||||
|
env:
|
||||||
|
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-nightly-list.json
|
||||||
|
run: |
|
||||||
|
cargo nextest list --profile e2e-nightly -p e2e_test --message-format json > "${NEXTEST_LISTING}"
|
||||||
|
python3 ./scripts/check_test_wiring.py --check-profile e2e-nightly "${NEXTEST_LISTING}"
|
||||||
|
|
||||||
|
- name: Run cluster fault e2e nightly suite
|
||||||
|
env:
|
||||||
|
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-nightly-logs
|
||||||
|
run: cargo nextest run --profile e2e-nightly -p e2e_test
|
||||||
|
|
||||||
|
- name: Upload cluster fault diagnostics
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
|
with:
|
||||||
|
name: e2e-cluster-nightly-${{ github.run_number }}
|
||||||
|
path: |
|
||||||
|
target/nextest/e2e-nightly/junit.xml
|
||||||
|
${{ runner.temp }}/rustfs-e2e-nightly-list.json
|
||||||
|
${{ runner.temp }}/rustfs-e2e-nightly-logs/
|
||||||
|
retention-days: 7
|
||||||
|
if-no-files-found: warn
|
||||||
|
|
||||||
|
protocols-nightly:
|
||||||
|
name: Protocol e2e (nightly)
|
||||||
|
runs-on: sm-standard-4
|
||||||
|
timeout-minutes: 90
|
||||||
|
env:
|
||||||
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||||
|
RUSTFS_BUILD_FEATURES: ftps,webdav,sftp
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Setup Rust environment
|
||||||
|
uses: ./.github/actions/setup
|
||||||
|
with:
|
||||||
|
rust-version: stable
|
||||||
|
cache-shared-key: ci-e2e-protocols
|
||||||
|
cache-save-if: 'false'
|
||||||
|
install-build-packaging-tools: 'false'
|
||||||
|
|
||||||
|
# The suite owns fixed protocol ports and serializes its internal cases.
|
||||||
|
- name: Verify protocol e2e membership
|
||||||
|
env:
|
||||||
|
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-protocols-list.json
|
||||||
|
run: |
|
||||||
|
cargo nextest list --profile e2e-protocols -p e2e_test --message-format json > "${NEXTEST_LISTING}"
|
||||||
|
python3 ./scripts/check_test_wiring.py --check-profile e2e-protocols "${NEXTEST_LISTING}"
|
||||||
|
|
||||||
|
- name: Run protocol e2e nightly suite
|
||||||
|
env:
|
||||||
|
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-protocol-e2e-logs
|
||||||
|
run: >-
|
||||||
|
cargo nextest run -j 1 --profile e2e-protocols -p e2e_test --no-capture
|
||||||
|
|
||||||
|
- name: Upload protocol diagnostics
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
|
with:
|
||||||
|
name: e2e-protocol-nightly-${{ github.run_number }}
|
||||||
|
path: |
|
||||||
|
target/nextest/e2e-protocols/junit.xml
|
||||||
|
${{ runner.temp }}/rustfs-e2e-protocols-list.json
|
||||||
|
${{ runner.temp }}/rustfs-protocol-e2e-logs/
|
||||||
|
retention-days: 7
|
||||||
|
if-no-files-found: warn
|
||||||
|
|
||||||
alert-on-failure:
|
alert-on-failure:
|
||||||
name: Alert on scheduled failure
|
name: Alert on scheduled failure
|
||||||
needs: [repl-nightly]
|
needs: [repl-nightly, cluster-nightly, protocols-nightly]
|
||||||
# Only scheduled runs open/append the tracking issue (backlog#1149 ci-8);
|
# Only scheduled runs open/append the tracking issue (backlog#1149 ci-8);
|
||||||
# manual workflow_dispatch runs stay quiet so a debugging run never files a
|
# manual workflow_dispatch runs stay quiet so a debugging run never files a
|
||||||
# spurious alert.
|
# spurious alert.
|
||||||
|
|||||||
@@ -18,10 +18,9 @@
|
|||||||
# runs only the implemented_tests.txt whitelist. This workflow complements it:
|
# runs only the implemented_tests.txt whitelist. This workflow complements it:
|
||||||
#
|
#
|
||||||
# - Scheduled weekly full sweep (TEST_SCOPE=all): runs the ENTIRE upstream
|
# - Scheduled weekly full sweep (TEST_SCOPE=all): runs the ENTIRE upstream
|
||||||
# suite and reports promotion candidates (tests that newly pass) and
|
# suite and reports promotion candidates. Regressions, unclassified tests,
|
||||||
# unclassified tests. The job fails only on regressions in the implemented
|
# incomplete execution, and infrastructure errors fail the job; classified
|
||||||
# whitelist or on infrastructure errors — expected failures from
|
# failures for not-yet-implemented features remain informational.
|
||||||
# not-yet-implemented features do not turn the run red.
|
|
||||||
# - Manual runs (workflow_dispatch): same, with configurable mode/scope.
|
# - Manual runs (workflow_dispatch): same, with configurable mode/scope.
|
||||||
#
|
#
|
||||||
# All test execution is delegated to scripts/s3-tests/run.sh (single source of
|
# All test execution is delegated to scripts/s3-tests/run.sh (single source of
|
||||||
@@ -45,13 +44,6 @@
|
|||||||
# The PR gate (ci.yml s3-implemented-tests) is unaffected: it avoids Docker
|
# The PR gate (ci.yml s3-implemented-tests) is unaffected: it avoids Docker
|
||||||
# via DEPLOY_MODE=binary and defers all pip setup to run.sh's self-bootstrap.
|
# via DEPLOY_MODE=binary and defers all pip setup to run.sh's self-bootstrap.
|
||||||
|
|
||||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
|
||||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
|
||||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
|
||||||
# reading this file, which has already misled at least one audit — hence this
|
|
||||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
|
||||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
|
||||||
#
|
|
||||||
name: e2e-s3tests
|
name: e2e-s3tests
|
||||||
|
|
||||||
on:
|
on:
|
||||||
@@ -81,6 +73,19 @@ on:
|
|||||||
description: "Stop after N failures. '0' to run everything."
|
description: "Stop after N failures. '0' to run everything."
|
||||||
required: false
|
required: false
|
||||||
default: "0"
|
default: "0"
|
||||||
|
shard-count:
|
||||||
|
description: "Exact-node-ID shard count for a targeted manual run"
|
||||||
|
required: false
|
||||||
|
default: "1"
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- "1"
|
||||||
|
- "2"
|
||||||
|
- "4"
|
||||||
|
shard-index:
|
||||||
|
description: "Zero-based shard index for a targeted manual run"
|
||||||
|
required: false
|
||||||
|
default: "0"
|
||||||
markexpr:
|
markexpr:
|
||||||
description: "Optional pytest -m expression"
|
description: "Optional pytest -m expression"
|
||||||
required: false
|
required: false
|
||||||
@@ -111,6 +116,8 @@ env:
|
|||||||
XDIST: ${{ github.event.inputs.xdist || '4' }}
|
XDIST: ${{ github.event.inputs.xdist || '4' }}
|
||||||
MAXFAIL: ${{ github.event.inputs.maxfail || '0' }}
|
MAXFAIL: ${{ github.event.inputs.maxfail || '0' }}
|
||||||
MARKEXPR: ${{ github.event.inputs.markexpr || '' }}
|
MARKEXPR: ${{ github.event.inputs.markexpr || '' }}
|
||||||
|
S3_SHARD_COUNT: ${{ github.event_name == 'schedule' && '4' || github.event.inputs.shard-count || '1' }}
|
||||||
|
TEST_TIMEOUT: "300"
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event.inputs['test-mode'] || 'single' }}
|
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event.inputs['test-mode'] || 'single' }}
|
||||||
@@ -127,19 +134,22 @@ defaults:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
s3tests:
|
s3tests:
|
||||||
|
name: s3tests (${{ matrix.test-mode }}, shard ${{ matrix.shard-index }})
|
||||||
# GitHub-hosted: reliably provides Docker + docker compose + python3/pip.
|
# GitHub-hosted: reliably provides Docker + docker compose + python3/pip.
|
||||||
# See the header note (ci-1) for why the self-hosted sm-standard-4 label
|
# See the header note (ci-1) for why the self-hosted sm-standard-4 label
|
||||||
# was abandoned. TODO(ci-8): scheduled-failure alerting (auto-open issue)
|
# was abandoned. Scheduled failures are handled by alert-on-failure below.
|
||||||
# is added by the ci-8 composite action; do not implement it here.
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 180
|
timeout-minutes: 180
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
max-parallel: 2
|
||||||
matrix:
|
matrix:
|
||||||
# Scheduled sweeps cover both topologies; manual runs use the input.
|
# Scheduled sweeps cover both topologies; manual runs use the input.
|
||||||
test-mode: ${{ github.event_name == 'schedule' && fromJSON('["single", "multi"]') || fromJSON(format('["{0}"]', github.event.inputs.test-mode || 'single')) }}
|
test-mode: ${{ github.event_name == 'schedule' && fromJSON('["single", "multi"]') || fromJSON(format('["{0}"]', github.event.inputs.test-mode || 'single')) }}
|
||||||
|
shard-index: ${{ github.event_name == 'schedule' && fromJSON('[0, 1, 2, 3]') || fromJSON(format('[{0}]', github.event.inputs.shard-index || '0')) }}
|
||||||
env:
|
env:
|
||||||
TEST_MODE: ${{ matrix.test-mode }}
|
TEST_MODE: ${{ matrix.test-mode }}
|
||||||
|
S3_SHARD_INDEX: ${{ matrix.shard-index }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||||
with:
|
with:
|
||||||
@@ -181,6 +191,7 @@ jobs:
|
|||||||
- name: Start single RustFS
|
- name: Start single RustFS
|
||||||
if: env.TEST_MODE == 'single'
|
if: env.TEST_MODE == 'single'
|
||||||
run: |
|
run: |
|
||||||
|
SSE_KEY="$(head -c 32 /dev/zero | base64 -w0)"
|
||||||
docker network inspect rustfs-net >/dev/null 2>&1 || docker network create rustfs-net
|
docker network inspect rustfs-net >/dev/null 2>&1 || docker network create rustfs-net
|
||||||
docker rm -f rustfs-single >/dev/null 2>&1 || true
|
docker rm -f rustfs-single >/dev/null 2>&1 || true
|
||||||
# The four disks share one physical device on the runner (a single
|
# The four disks share one physical device on the runner (a single
|
||||||
@@ -193,6 +204,7 @@ jobs:
|
|||||||
-e RUSTFS_ADDRESS=0.0.0.0:9000 \
|
-e RUSTFS_ADDRESS=0.0.0.0:9000 \
|
||||||
-e RUSTFS_ACCESS_KEY="${S3_ACCESS_KEY}" \
|
-e RUSTFS_ACCESS_KEY="${S3_ACCESS_KEY}" \
|
||||||
-e RUSTFS_SECRET_KEY="${S3_SECRET_KEY}" \
|
-e RUSTFS_SECRET_KEY="${S3_SECRET_KEY}" \
|
||||||
|
-e RUSTFS_SSE_S3_MASTER_KEY="${SSE_KEY}" \
|
||||||
-e RUSTFS_VOLUMES="/data/rustfs{0...3}" \
|
-e RUSTFS_VOLUMES="/data/rustfs{0...3}" \
|
||||||
-e RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true \
|
-e RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true \
|
||||||
-v /tmp/rustfs-single:/data \
|
-v /tmp/rustfs-single:/data \
|
||||||
@@ -201,6 +213,7 @@ jobs:
|
|||||||
- name: Start 4-node distributed cluster
|
- name: Start 4-node distributed cluster
|
||||||
if: env.TEST_MODE == 'multi'
|
if: env.TEST_MODE == 'multi'
|
||||||
run: |
|
run: |
|
||||||
|
SSE_KEY="$(head -c 32 /dev/zero | base64 -w0)"
|
||||||
# A real distributed deployment: every node lists all endpoints in
|
# A real distributed deployment: every node lists all endpoints in
|
||||||
# RUSTFS_VOLUMES so data is erasure-coded ACROSS nodes. Do not use
|
# RUSTFS_VOLUMES so data is erasure-coded ACROSS nodes. Do not use
|
||||||
# node-local volume paths here — that would create four independent
|
# node-local volume paths here — that would create four independent
|
||||||
@@ -213,6 +226,7 @@ jobs:
|
|||||||
RUSTFS_ADDRESS: "0.0.0.0:9000"
|
RUSTFS_ADDRESS: "0.0.0.0:9000"
|
||||||
RUSTFS_ACCESS_KEY: ${S3_ACCESS_KEY}
|
RUSTFS_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY}
|
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
RUSTFS_SSE_S3_MASTER_KEY: "${SSE_KEY}"
|
||||||
RUSTFS_VOLUMES: "http://rustfs{1...4}:9000/data/rustfs{0...3}"
|
RUSTFS_VOLUMES: "http://rustfs{1...4}:9000/data/rustfs{0...3}"
|
||||||
# Each node's four disks share one physical device inside its
|
# Each node's four disks share one physical device inside its
|
||||||
# container, so bypass the local physical-disk-independence guard
|
# container, so bypass the local physical-disk-independence guard
|
||||||
@@ -294,7 +308,6 @@ jobs:
|
|||||||
|
|
||||||
- name: Run ceph s3-tests
|
- name: Run ceph s3-tests
|
||||||
run: |
|
run: |
|
||||||
set +e
|
|
||||||
DEPLOY_MODE=existing \
|
DEPLOY_MODE=existing \
|
||||||
TEST_MODE="${TEST_MODE}" \
|
TEST_MODE="${TEST_MODE}" \
|
||||||
TEST_SCOPE="${TEST_SCOPE}" \
|
TEST_SCOPE="${TEST_SCOPE}" \
|
||||||
@@ -302,26 +315,6 @@ jobs:
|
|||||||
MAXFAIL="${MAXFAIL}" \
|
MAXFAIL="${MAXFAIL}" \
|
||||||
MARKEXPR="${MARKEXPR}" \
|
MARKEXPR="${MARKEXPR}" \
|
||||||
./scripts/s3-tests/run.sh
|
./scripts/s3-tests/run.sh
|
||||||
RC=$?
|
|
||||||
set -e
|
|
||||||
|
|
||||||
if [ "${TEST_SCOPE}" = "implemented" ]; then
|
|
||||||
# Whitelist run: every failure is a regression.
|
|
||||||
exit "${RC}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Full sweep: failures outside the implemented whitelist are
|
|
||||||
# inventory (promotion candidates / unimplemented features), not a
|
|
||||||
# gate. Fail only on whitelist regressions or infrastructure errors.
|
|
||||||
JUNIT="artifacts/s3tests-${TEST_MODE}/junit.xml"
|
|
||||||
if [ ! -f "${JUNIT}" ]; then
|
|
||||||
echo "No junit.xml produced — infrastructure failure (exit ${RC})" >&2
|
|
||||||
exit "${RC}"
|
|
||||||
fi
|
|
||||||
python3 scripts/s3-tests/report_compat.py \
|
|
||||||
--junit "${JUNIT}" \
|
|
||||||
--lists-dir scripts/s3-tests \
|
|
||||||
--fail-on-regression
|
|
||||||
|
|
||||||
- name: Publish compatibility report
|
- name: Publish compatibility report
|
||||||
if: always()
|
if: always()
|
||||||
@@ -346,7 +339,7 @@ jobs:
|
|||||||
if: always() && env.ACT != 'true'
|
if: always() && env.ACT != 'true'
|
||||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
with:
|
with:
|
||||||
name: s3tests-${{ env.TEST_MODE }}
|
name: s3tests-${{ env.TEST_MODE }}-shard-${{ matrix.shard-index }}
|
||||||
path: artifacts/**
|
path: artifacts/**
|
||||||
|
|
||||||
alert-on-failure:
|
alert-on-failure:
|
||||||
|
|||||||
+11
-24
@@ -12,27 +12,22 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
# DISABLED. This workflow is switched off in the repository's Actions settings
|
|
||||||
# (state: disabled_manually) and does not run on any trigger, including its cron
|
|
||||||
# and workflow_dispatch. That state lives in GitHub's UI and is invisible when
|
|
||||||
# reading this file, which has already misled at least one audit — hence this
|
|
||||||
# banner. Re-enabling is a UI action; anyone doing so should first check that the
|
|
||||||
# workflow still matches the current CI layout. See rustfs/backlog#1603.
|
|
||||||
#
|
|
||||||
name: Fuzz
|
name: Fuzz
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [ opened, synchronize, reopened, closed ]
|
types: [ opened, synchronize, reopened, closed ]
|
||||||
# PR trigger is intentionally narrow: only changes to the fuzz harness
|
# Run when the harness or any directly fuzzed production crate changes.
|
||||||
# itself gate a PR. Broad crate paths (ecstore/filemeta/utils/policy/…)
|
|
||||||
# are covered by the nightly `schedule` run below, which fuzzes against
|
|
||||||
# whatever landed on main. Widening these paths previously queued a
|
|
||||||
# ~45min fuzz-build on nearly every PR and is why this workflow was
|
|
||||||
# disabled; do not re-add crate paths here.
|
|
||||||
paths:
|
paths:
|
||||||
- "fuzz/**"
|
- "fuzz/**"
|
||||||
- "scripts/fuzz/**"
|
- "scripts/fuzz/**"
|
||||||
|
- "crates/ecstore/**"
|
||||||
|
- "crates/filemeta/**"
|
||||||
|
- "crates/policy/**"
|
||||||
|
- "crates/security-governance/**"
|
||||||
|
- "crates/utils/**"
|
||||||
|
- "Cargo.toml"
|
||||||
|
- "Cargo.lock"
|
||||||
- ".github/workflows/fuzz.yml"
|
- ".github/workflows/fuzz.yml"
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "0 2 * * *"
|
- cron: "0 2 * * *"
|
||||||
@@ -81,7 +76,7 @@ jobs:
|
|||||||
github.event_name == 'schedule' ||
|
github.event_name == 'schedule' ||
|
||||||
github.event_name == 'workflow_dispatch'
|
github.event_name == 'workflow_dispatch'
|
||||||
runs-on: sm-standard-4
|
runs-on: sm-standard-4
|
||||||
timeout-minutes: 45
|
timeout-minutes: 60
|
||||||
env:
|
env:
|
||||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||||
steps:
|
steps:
|
||||||
@@ -121,12 +116,7 @@ jobs:
|
|||||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
|
||||||
with:
|
with:
|
||||||
name: fuzz-prebuilt-binaries-${{ github.run_number }}
|
name: fuzz-prebuilt-binaries-${{ github.run_number }}
|
||||||
path: |
|
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
|
||||||
fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/archive_extract
|
|
||||||
fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/bucket_validation
|
|
||||||
fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/local_metadata
|
|
||||||
fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/path_containment
|
|
||||||
fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/policy_ingress
|
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
compression-level: 0
|
compression-level: 0
|
||||||
@@ -192,10 +182,7 @@ jobs:
|
|||||||
nightly-fuzz-corpus:
|
nightly-fuzz-corpus:
|
||||||
name: "Nightly / ${{ matrix.target }}"
|
name: "Nightly / ${{ matrix.target }}"
|
||||||
needs: fuzz-build
|
needs: fuzz-build
|
||||||
# TODO(ci-8): when the schedule-failure-issue composite action lands,
|
# Scheduled failures are handled by alert-on-failure below.
|
||||||
# add a step here (or a dependent job) that opens/updates a GitHub issue
|
|
||||||
# on nightly failure. ci-8 is the single alerting mechanism for all
|
|
||||||
# scheduled workflows; do not self-roll alerting in this workflow.
|
|
||||||
if: >
|
if: >
|
||||||
github.event_name == 'schedule' ||
|
github.event_name == 'schedule' ||
|
||||||
(github.event_name == 'workflow_dispatch' &&
|
(github.event_name == 'workflow_dispatch' &&
|
||||||
|
|||||||
@@ -189,6 +189,7 @@ jobs:
|
|||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
max-parallel: 1
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- arch: x86_64
|
- arch: x86_64
|
||||||
@@ -510,15 +511,13 @@ jobs:
|
|||||||
|
|
||||||
CHECKSUM_DIR="$(mktemp -d)"
|
CHECKSUM_DIR="$(mktemp -d)"
|
||||||
gh release download "$TAG" -p 'SHA256SUMS' -p 'SHA512SUMS' \
|
gh release download "$TAG" -p 'SHA256SUMS' -p 'SHA512SUMS' \
|
||||||
-D "$CHECKSUM_DIR" --clobber 2>/dev/null || true
|
-D "$CHECKSUM_DIR" --clobber
|
||||||
|
|
||||||
for spec in "SHA256SUMS:sha256sum" "SHA512SUMS:sha512sum"; do
|
for spec in "SHA256SUMS:sha256sum" "SHA512SUMS:sha512sum"; do
|
||||||
asset="${spec%%:*}"
|
asset="${spec%%:*}"
|
||||||
checksum_cmd="${spec##*:}"
|
checksum_cmd="${spec##*:}"
|
||||||
checksum_file="${CHECKSUM_DIR}/${asset}"
|
checksum_file="${CHECKSUM_DIR}/${asset}"
|
||||||
|
|
||||||
touch "$checksum_file"
|
|
||||||
|
|
||||||
for f in "$DEB_FILE" "$RPM_FILE"; do
|
for f in "$DEB_FILE" "$RPM_FILE"; do
|
||||||
if [[ -n "$f" && -f "$f" ]]; then
|
if [[ -n "$f" && -f "$f" ]]; then
|
||||||
base="$(basename "$f")"
|
base="$(basename "$f")"
|
||||||
@@ -531,7 +530,8 @@ jobs:
|
|||||||
grep -Fv -- "$base" "$checksum_file" > "${checksum_file}.tmp" || true
|
grep -Fv -- "$base" "$checksum_file" > "${checksum_file}.tmp" || true
|
||||||
grep -Fv -- "$github_base" "${checksum_file}.tmp" > "${checksum_file}.tmp2" || true
|
grep -Fv -- "$github_base" "${checksum_file}.tmp" > "${checksum_file}.tmp2" || true
|
||||||
mv "${checksum_file}.tmp2" "$checksum_file"
|
mv "${checksum_file}.tmp2" "$checksum_file"
|
||||||
(cd "$(dirname "$f")" && "$checksum_cmd" -- "$github_base") >> "$checksum_file"
|
digest=$("$checksum_cmd" -- "$f" | awk '{print $1}')
|
||||||
|
printf '%s %s\n' "$digest" "$github_base" >> "$checksum_file"
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
|
|||||||
@@ -1,399 +1,255 @@
|
|||||||
# RustFS Agent Instructions (Global)
|
# RustFS Agent Instructions
|
||||||
|
|
||||||
This root file keeps repository-wide rules only.
|
This file contains repository-wide rules. Use the nearest subdirectory
|
||||||
Use the nearest subdirectory `AGENTS.md` for path-specific guidance.
|
`AGENTS.md` for path-specific invariants.
|
||||||
|
|
||||||
## Rule Precedence
|
## Precedence
|
||||||
|
|
||||||
1. System/developer instructions.
|
1. System/developer instructions.
|
||||||
2. Current user/task instructions.
|
2. The current user request.
|
||||||
3. The nearest `AGENTS.md` in the current path.
|
3. The nearest `AGENTS.md`.
|
||||||
4. This file (global defaults).
|
4. This file.
|
||||||
|
|
||||||
If repo-level instructions conflict, follow the nearest file and keep behavior aligned with CI.
|
## Operating Model
|
||||||
|
|
||||||
## Execution Discipline
|
- Inquiry, diagnosis, review, and planning tasks are read-only unless the user
|
||||||
|
explicitly requests changes.
|
||||||
- Read the relevant existing code, tests, and local guidance before changing behavior. For new helpers or test setup, that read includes `crates/utils`, `crates/common`, and the touched crate's own `test_util`/fixtures (see Reuse Before You Write).
|
- For implementation, read the relevant code, tests, and local guidance, then
|
||||||
- State assumptions when they affect the implementation or verification path.
|
make the smallest change that satisfies the request.
|
||||||
- If a task has multiple plausible interpretations, list the options briefly and choose the narrowest reasonable path; ask when the ambiguity would make the change risky.
|
- State assumptions only when they affect behavior or verification. Ask only
|
||||||
- For multi-step work, keep the plan minimal and tied to verifiable outcomes.
|
when a wrong assumption would materially change the result.
|
||||||
- Avoid redundant file reads, repeated commands, and unnecessary exploratory work once enough context is available.
|
- Do not load every skill or inspect unrelated modules preemptively. Select a
|
||||||
- A good result is a minimal diff with clear assumptions, no over-engineering, and independent verification that survives Adversarial Validation (below).
|
skill only when its description directly matches the request or changed
|
||||||
|
surface.
|
||||||
|
- Avoid repeated reads and equivalent verification commands once enough
|
||||||
|
evidence exists.
|
||||||
|
|
||||||
## Worktree and Disk Hygiene
|
## Worktree and Disk Hygiene
|
||||||
|
|
||||||
- Unless the requester explicitly says otherwise, treat every new implementation task as isolated work: fetch the latest `origin/main`, confirm the requested change is not already present there, and create a dedicated feature branch and worktree from that exact upstream commit before editing. Do not implement new work directly in the primary checkout or reuse a worktree from another task.
|
- Start implementation from the latest `origin/main` and confirm the requested
|
||||||
- Check available disk space before creating the worktree or starting dependency downloads, builds, tests, coverage, or other artifact-heavy commands. For long-running or artifact-heavy work, re-check disk usage at natural phase boundaries and before broad validation; if remaining space may not safely accommodate the next command, stop and reclaim task-owned artifacts before continuing.
|
change is not already present.
|
||||||
- Keep cleanup scoped and safe: remove generated build/test/coverage artifacts and temporary files created by the task when they are no longer needed, and never delete another task's worktree or uncommitted files. Prefer shared dependency caches where supported instead of duplicating large artifacts across worktrees.
|
- An existing clean, isolated task worktree is sufficient. Create another
|
||||||
- At handoff, report the disk-space checks, cleanup performed, and any retained worktree or artifacts with the reason they are still needed.
|
worktree only when the current checkout is shared, dirty with unrelated work,
|
||||||
|
or belongs to another task.
|
||||||
|
- Never commit from a shared checkout. Use an `overtrue/` feature branch unless
|
||||||
|
the user requests another name.
|
||||||
|
- Check free space before artifact-heavy builds, tests, coverage, or downloads.
|
||||||
|
Re-check before a broad gate when space is tight.
|
||||||
|
- Remove only task-owned temporary/build artifacts. Never delete another task's
|
||||||
|
worktree or uncommitted data.
|
||||||
|
- At handoff, mention disk or cleanup details only when they affected execution
|
||||||
|
or artifacts/worktrees remain intentionally.
|
||||||
|
|
||||||
## PR Lifecycle Monitoring
|
## Change Style
|
||||||
|
|
||||||
- Creating or updating a PR is not the terminal state. Unless the requester explicitly limits the task to PR creation, monitor the PR through its terminal state: merged, closed, or explicitly handed off because progress requires user or maintainer action.
|
- Preserve existing control flow unless changing it is required for correctness.
|
||||||
- While the task is active, monitor CI/check runs, review decisions and unresolved threads, mergeability and conflicts, and unexpected head/base changes. Prefer event-driven or bounded waits provided by the current environment over frequent polling; report only state changes, actionable failures, or meaningful prolonged delays.
|
- Prefer a direct local edit over new files, wrappers, managers, or speculative
|
||||||
- Investigate every failing check and review comment before changing code. Fix failures attributable to the task, run the verification required for the new diff, push the update, respond to or resolve the corresponding review threads, and resume monitoring. Do not weaken checks, dismiss valid feedback, or retry flaky failures merely to obtain a green result.
|
abstractions.
|
||||||
- Treat opening, green CI, approval, and mergeability as intermediate states. Never merge without the required reviewer approval or explicit authority. If progress depends on credentials, infrastructure, a maintainer decision, or another external action, report the exact blocker and the evidence already collected.
|
- Add a helper only when it removes current duplication, names a real domain
|
||||||
- If the current execution environment cannot remain active until the next PR event, use a supported automation, monitor, or thread wakeup when available and within scope. Otherwise leave an explicit handoff containing the PR, current state, next event to observe, and pending cleanup; do not imply that background monitoring exists when none is scheduled.
|
boundary, or isolates a non-trivial invariant.
|
||||||
- After observing a merge, verify the commits are preserved on the upstream base, ensure the worktree is clean, remove the dedicated worktree, prune stale worktree metadata, and delete the local task branch when it is no longer in use. For a closed or abandoned PR, preserve any unmerged work unless deletion was explicitly authorized. Do not delete remote branches unless explicitly requested or repository automation owns that cleanup.
|
- Remove an in-scope path superseded by the change. If compatibility requires it,
|
||||||
|
adapt at the boundary to one canonical core and use the repository's
|
||||||
|
`RUSTFS_COMPAT_TODO` policy.
|
||||||
|
- Comments explain non-obvious invariants or reasons. Do not narrate code or
|
||||||
|
record change history.
|
||||||
|
- Mention unrelated problems when useful; do not fix them in a narrow task.
|
||||||
|
|
||||||
## Autonomy and Approval Boundaries
|
## Reuse and Boundary Rules
|
||||||
|
|
||||||
- Inquiry tasks (answer, explain, review, diagnose, plan): report findings; do not change files unless a fix is explicitly requested.
|
- Before adding helpers, constants, fixtures, or wrappers, search the touched
|
||||||
- Action tasks (change, build, fix): make in-scope local changes without asking for approval.
|
crate, the domain-owning crate, `crates/utils`, `crates/common`, and relevant
|
||||||
- Ask for confirmation before destructive or hard-to-reverse operations (force-pushes, history rewrites, deleting data or branches), merging a PR (reviewer approval required), or any material expansion of the requested scope.
|
direct dependencies.
|
||||||
|
- Reuse requires matching semantics: normalization, error types, deadlines,
|
||||||
## Communication and Language
|
durability, and compatibility must fit the call site. A narrowly named local
|
||||||
|
helper is better than forced reuse with different semantics.
|
||||||
- Respond in the same language used by the requester.
|
- Validate untrusted input at its trust boundary, then trust the validated type.
|
||||||
- Keep source code, comments, commit messages, and PR title/body in English.
|
Values crossing disk, RPC, persistence, or version boundaries remain
|
||||||
- Be concise. Avoid sycophantic openers, closing fluff, and verbose status reporting.
|
untrusted at every consumer.
|
||||||
|
- Re-check boundary values immediately before destructive actions such as
|
||||||
## Change Style for Existing Logic
|
delete, overwrite, or quorum decisions.
|
||||||
|
- Every new branch needs a concrete triggering input/state. For decoded or peer
|
||||||
- Start with the smallest direct, local edit. Add production files, types, traits, helpers, wrappers, or abstraction layers only when current behavior requires them. Extraction must remove present duplication, enforce a real boundary, or materially clarify a non-trivial flow; anticipated reuse is not enough.
|
data, corruption and mixed-version input are valid triggers.
|
||||||
- Use Rust's default module file layout (`mod foo;` with `foo.rs` or `foo/mod.rs`/`foo/*.rs`).
|
- Required values must return a typed error when absent or corrupt; do not use a
|
||||||
Avoid `#[path = "..."]` for module inclusion; move files into the canonical module tree instead.
|
default that converts corruption into a plausible result.
|
||||||
If an unavoidable generated-code, FFI, or test-fixture exception remains, keep it local and document why the canonical layout cannot work.
|
- Attach error context once where it is actionable. Do not erase typed errors
|
||||||
- Solve only the requested problem; do not add speculative features, configurability, or adjacent improvements.
|
below aggregation or quorum layers.
|
||||||
- Prefer editing existing code over rewriting files or reshaping unrelated logic.
|
|
||||||
- Modify only what is required. Remove any in-scope path or representation superseded by the change. If compatibility or rollback requires retention, adapt at the boundary to one canonical core and follow the repository's `RUSTFS_COMPAT_TODO` removal policy; never delete unrelated code merely to improve addition/deletion statistics.
|
|
||||||
- Preserve the existing control-flow and logic shape when fixing bugs or addressing review comments, especially in init, distributed coordination, locking, metadata, and concurrency paths.
|
|
||||||
- Do not refactor existing code only to make it easier to unit test.
|
|
||||||
- Keep fixes narrowly aligned with the requested behavior; avoid semantic-adjacent rewrites while touching sensitive paths.
|
|
||||||
- Keep code elegant, concise, and direct. Prefer the smallest readable design and existing abstractions over parallel managers, factories, adapters, or wrappers added only to make the design look extensible.
|
|
||||||
- Comments state non-obvious reasons, assumptions, and invariants in the shortest complete form. Their length follows the invariant's complexity: `SAFETY`, lock ordering, durability, and compatibility contracts may need a short list of conditions. Never narrate the next line, restate a signature, or record change history; move durable design rationale to architecture or operations documentation.
|
|
||||||
- Mention unrelated issues when useful, but do not fix them as part of a narrow task.
|
|
||||||
|
|
||||||
## Reuse Before You Write
|
|
||||||
|
|
||||||
Search for an existing implementation before writing a new one; extend what exists instead of duplicating it:
|
|
||||||
|
|
||||||
- **Helpers and utilities** (path/string handling, hashing, retry, env parsing, IO wrappers): check `crates/utils`, `crates/common`, the touched crate, the likely domain-owning crate, and relevant direct workspace dependencies from `Cargo.toml`. Search snake_case signatures with a focused term. Reimplementing an existing workspace helper — or hand-rolling what `std`, `tokio`, or an existing dependency already provides — is a review finding, not a style preference.
|
|
||||||
- **Reuse requires matching semantics, not a matching name**: before adopting a helper, check its normalization (`clean` resolves `.`/`..` — never apply it to raw S3 object keys), error type, backoff/deadline behavior, and durability gating against the call site. When semantics differ, a new narrowly-named helper with a comment naming the rejected lookalike is the correct outcome. The inverse also holds: workspace wrappers exist because raw `std`/`tokio` semantics were insufficient (durability gates, retries) — prefer the wrapper over the raw call.
|
|
||||||
- **Constants and fixed tokens** (protocol labels, error identifiers, header keys, event names, metric names, command tags): search for existing constants/enums that already represent the same semantic value and reuse them. If a value is truly new, define one local constant near related logic; never scatter the literal across sites. When changing existing behavior, align naming and format with the established constants.
|
|
||||||
- **Test scaffolding**: reuse existing test utilities and fixtures (the touched crate's own `test_util` module and `tests/fixtures`, or `crates/test-utils`) instead of writing new setup code — run `rg -l '<fn-under-test>' <crate>/src <crate>/tests` before writing a test. A new test must pin a failure mode no existing test covers. Near-duplicate means same code path AND same poison-value class: this repo's boundary companions (n==max vs max+1, absent vs empty vs nil UUID bytes, MetaObject vs MetaDeleteMarker) are distinct by definition and must all be written.
|
|
||||||
|
|
||||||
## Necessary Code Only
|
|
||||||
|
|
||||||
Net-new code — files, types, branches, comments — is cost to justify, not progress:
|
|
||||||
|
|
||||||
- Inspect production-code additions separately. Tests, fixtures, generated code, and documentation do not count as production-code growth. Line counts are signals, not quotas: new production structures must map to a current requirement, and a blocker requires a concrete smaller design that preserves correctness, compatibility, readability, and real boundaries.
|
|
||||||
- Validate at the trust boundary — untrusted client input, bytes read from disk, RPC payloads, config (see Serde Safety and Cross-Cutting Domain Invariants) — then trust the type: do not re-check what the type system or a validated upstream layer already guarantees, and cite the establishing check (`file:line`) when the guarantee is not obvious.
|
|
||||||
- The exception is load-bearing: a value that crossed a persistence, RPC, or version boundary is never guaranteed by the code on the other side — a peer may be older or buggy, disk bytes may be corrupt — so the Cross-Cutting Domain Invariant patterns apply at every consumer, and re-checks immediately before a destructive action (delete, overwrite, quorum decision) stay. Deleting an existing guard is a behavior change requiring adversarial review, not cleanup.
|
|
||||||
- Every new branch needs a nameable trigger: a concrete input, state, or failure that reaches it — for boundary-crossing values, corrupt or stale persisted/peer data is always nameable. If you cannot name one, do not write the branch. If the case is truly unreachable, encode the invariant in the type; where that is impossible, return a typed internal error (fail closed). `debug_assert!` is acceptable only for pure internal arithmetic on values that never crossed a disk/RPC/config boundary — never as the sole guard on decoded or peer-supplied data.
|
|
||||||
- Never substitute a default where the value is required (e.g. `unwrap_or_default()` on metadata that must exist) — that converts corruption into a wrong answer. Return the typed error instead: explicit failure over implicit success.
|
|
||||||
- Attach error context once, at the layer where it is actionable: re-wrapping equivalent context at every hop is noise, and expanding a fallible chain into nested `match` blocks where `?` or a combinator suffices is a finding. Never add context by converting a typed error into a generic variant below an error-aggregation or quorum layer (`reduce_errs` classifies by variant equality) — context there belongs in a `tracing` event, not the error value.
|
|
||||||
|
|
||||||
## Sources of Truth
|
## Sources of Truth
|
||||||
|
|
||||||
- Workspace layout and crate membership: `Cargo.toml` (`[workspace].members`)
|
- Workspace membership: `Cargo.toml`.
|
||||||
- Local quality commands: `Makefile` and `.config/make/`
|
- Local gates: `Makefile` and `.config/make/`.
|
||||||
- CI quality gates: `.github/workflows/ci.yml`
|
- CI gates: `.github/workflows/ci.yml`.
|
||||||
- PR template: `.github/pull_request_template.md`
|
- PR format: `.github/pull_request_template.md`.
|
||||||
- High-level architecture and crate map: `ARCHITECTURE.md`
|
- Architecture routing: `ARCHITECTURE.md` and `docs/architecture/README.md`.
|
||||||
- Migration guardrails, readiness contracts, support matrices:
|
- Agent skills: `.agents/skills/*/SKILL.md`.
|
||||||
`docs/architecture/README.md` (routes by audience)
|
|
||||||
- Shared agent skills (all tools): `.agents/skills/` — each `SKILL.md` carries
|
|
||||||
a frontmatter `description` stating when it applies. Scan the descriptions
|
|
||||||
before starting a task and follow any skill that matches, even if your tool
|
|
||||||
does not auto-load skills:
|
|
||||||
`grep -m1 '^description:' .agents/skills/*/SKILL.md`
|
|
||||||
Claude Code reads them through the `.claude/skills` symlink; add new skills
|
|
||||||
to `.agents/skills/` only, never as separate copies per tool
|
|
||||||
|
|
||||||
Avoid duplicating long crate lists or command matrices in instruction files.
|
Do not commit one-shot plans, trackers, migration ledgers, benchmark snapshots,
|
||||||
Reference the source files above instead.
|
or agent scratch notes. Durable architecture belongs under `docs/architecture/`,
|
||||||
|
operations under `docs/operations/`, and testing references under
|
||||||
|
`docs/testing/`. `scripts/check_no_planning_docs.sh` enforces this boundary.
|
||||||
|
|
||||||
Do not commit planning-type documents — one-shot implementation/optimization
|
## Verification
|
||||||
plans, task trackers, migration-progress ledgers, phase/PR templates,
|
|
||||||
issue-scoped benchmark-result snapshots or optimization conclusions, or
|
|
||||||
agent-generated working notes (e.g. anything a `superpowers`/scratch workflow
|
|
||||||
produces). Keep that work in the issue tracker or your local worktree, not in
|
|
||||||
the repository. Only durable reference — the architecture set under
|
|
||||||
`docs/architecture/`, repeatable operational runbooks under `docs/operations/`,
|
|
||||||
and the test-suite references under `docs/testing/` — belongs in version
|
|
||||||
control; `.gitignore` ignores everything else under `docs/` by default, so a new
|
|
||||||
plan file will not be tracked unless someone force-adds it — don't.
|
|
||||||
`scripts/check_no_planning_docs.sh` (wired into `make pre-commit`/`pre-pr` and
|
|
||||||
CI) fails the build if anything is committed under `docs/superpowers/`, even via
|
|
||||||
`git add -f`.
|
|
||||||
|
|
||||||
## Verification Before PR
|
Select checks from the final task-owned diff. Scoped `AGENTS.md` files may add a
|
||||||
|
concrete path-specific check, but must not replace this tiering with a generic
|
||||||
|
full-workspace gate.
|
||||||
|
|
||||||
Convert changes into independently verifiable outcomes. This section controls
|
### Documentation and Instructions
|
||||||
agent-run local validation; preparing a commit or PR does not by itself require
|
|
||||||
the broadest gate. Inspect only the final task-owned diff, classify it by
|
|
||||||
behavioral impact rather than line count or path alone, and run the smallest
|
|
||||||
set of checks that provides meaningful coverage. Do not let unrelated
|
|
||||||
worktree changes or a generic contributor checklist expand the scope.
|
|
||||||
Non-exempt changes must also pass Adversarial Validation (next section) before
|
|
||||||
the checks below count as completion.
|
|
||||||
|
|
||||||
### Validation floor
|
For prose, comments, agent instructions, and skill metadata that cannot affect
|
||||||
|
runtime/build output:
|
||||||
|
|
||||||
- Every change that is not documentation-only must finish with
|
- Run `git diff --check`.
|
||||||
`cargo fmt --all --check` passing. An umbrella gate that runs this exact
|
- Run the relevant documentation guard or skill validator when applicable.
|
||||||
check satisfies the requirement; do not run it twice. Use `cargo fmt --all`
|
- Skip Cargo formatting, compilation, Clippy, tests, `make pre-commit`, and
|
||||||
only when formatting needs to be fixed. Run the configured formatter or
|
`make pre-pr`.
|
||||||
validator for other changed languages when one exists.
|
|
||||||
- Documentation-only or instruction-only means all task-owned changes are
|
|
||||||
prose or documentation assets and cannot affect runtime, builds, CI,
|
|
||||||
dependencies, generated code, or tests. Run `git diff --check` and any
|
|
||||||
relevant documentation guard, but skip Cargo formatting, compilation,
|
|
||||||
Clippy, tests, `make pre-commit`, and `make pre-pr`.
|
|
||||||
- Behavior changes require relevant existing or new tests. Prefer the most
|
|
||||||
focused test or affected package. A passing targeted test can also provide
|
|
||||||
sufficient compilation coverage when it builds every changed target and
|
|
||||||
feature involved; do not add a redundant `cargo check` in that case.
|
|
||||||
- `cargo check` supplements compilation coverage; it never substitutes for a
|
|
||||||
behavioral test. If a relevant test cannot reasonably be added or run, use
|
|
||||||
the narrowest compilation check and report the reason and remaining risk.
|
|
||||||
|
|
||||||
### Validation tiers
|
### Non-Behavioral Source Changes
|
||||||
|
|
||||||
1. **Documentation/instruction-only:** Apply the exemption above. Run a guard
|
- Run the formatter/validator for the changed language.
|
||||||
such as `make doc-paths-check` only when it is relevant to the edited text.
|
- Add compilation or doctests only when syntax or executable examples changed.
|
||||||
2. **Non-behavioral source change:** For comments, formatting, or another
|
|
||||||
demonstrably non-executable change, run the formatting floor. Compilation,
|
|
||||||
Clippy, and tests may be skipped only when the edit cannot affect
|
|
||||||
compilation or runtime behavior; run targeted doctests if executable
|
|
||||||
documentation examples changed.
|
|
||||||
3. **Localized or bounded behavior change:** Run the formatting floor and the
|
|
||||||
narrowest relevant tests. Add package-scoped `cargo check` or Clippy only
|
|
||||||
for changed targets, features, APIs, error handling, async behavior, or
|
|
||||||
control flow not already covered. When several crates are affected but the
|
|
||||||
dependency set is identifiable, validate those packages and known
|
|
||||||
dependents instead of the whole workspace. Use `make pre-commit` only when
|
|
||||||
a repository-wide fast gate adds useful confidence beyond those checks.
|
|
||||||
4. **Broad or high-risk change:** Run `make pre-pr` only when targeted coverage
|
|
||||||
cannot bound the impact, including:
|
|
||||||
- dependency, feature, build-script, procedural-macro, code-generation,
|
|
||||||
toolchain, or CI changes that alter compilation or the test matrix;
|
|
||||||
- cross-crate public APIs, shared foundational code, or broad refactors with
|
|
||||||
an unbounded dependent set;
|
|
||||||
- locking, storage durability or formats, erasure coding, replication,
|
|
||||||
RPC/protocol compatibility, IAM/KMS/auth, cryptography, or other
|
|
||||||
security-sensitive behavior;
|
|
||||||
- a targeted check that reveals wider impact, an explicit user request, or
|
|
||||||
a release policy that requires the full gate.
|
|
||||||
|
|
||||||
Documentation-only and non-behavioral classifications take precedence over
|
### Localized Behavior Changes
|
||||||
path-based triggers. A small diff can still be high-risk, while a CI comment,
|
|
||||||
manifest comment, or release-note edit does not require full validation.
|
|
||||||
|
|
||||||
`make pre-pr` includes `make pre-commit` coverage. Never run both for the same
|
- Run `cargo fmt --all --check` for Rust changes.
|
||||||
unchanged diff, and do not repeat equivalent checks during PR preparation or
|
- Run the narrowest test that exercises the changed behavior.
|
||||||
because a local hook already ran them. Rerun only checks whose scope is affected
|
- Add package-scoped `cargo check` or Clippy only for targets, features, public
|
||||||
by later edits. Full workspace checks do not replace a relevant integration or
|
APIs, error handling, or control flow not compiled by the focused test.
|
||||||
E2E test for changed behavior; run that focused test when required and
|
- Use `make pre-commit` only when its repository-wide fast checks add confidence
|
||||||
available, or report why it was not run and the remaining risk.
|
beyond the focused checks.
|
||||||
|
|
||||||
If `make` is unavailable, run the equivalent checks defined under
|
### Broad or High-Risk Changes
|
||||||
`.config/make/`. At handoff, list the checks actually run, checks intentionally
|
|
||||||
skipped, and the reason for the selected tier.
|
|
||||||
|
|
||||||
After build-based verification completes, clean generated build artifacts before wrapping up to avoid unnecessary disk usage.
|
After the required adversarial review, run `make pre-pr` when targeted coverage
|
||||||
Do not open a PR with code changes when the required checks fail.
|
cannot bound the impact, including dependency/toolchain/build-matrix changes,
|
||||||
Make a failing check pass by fixing the cause, never by weakening the gate:
|
unbounded cross-crate APIs, or locking, durability, erasure coding, replication,
|
||||||
do not loosen or skip a guard script, add entries to a baseline or allowance
|
RPC, IAM/KMS/auth, cryptography, on-disk/on-wire, and S3-visible behavior.
|
||||||
list, suppress a lint with `#[allow]`, mark a failing test `#[ignore]`, or
|
|
||||||
delete or relax a failing assertion to get green. If a check itself is wrong,
|
|
||||||
change it deliberately and state the rationale in the PR.
|
|
||||||
|
|
||||||
For flaky tests, do not paper over them with retries. Follow the flake policy
|
`make pre-pr` includes `make pre-commit`; never run both for the same unchanged
|
||||||
in [docs/testing/README.md](docs/testing/README.md) (open an issue within 24h,
|
diff. Do not repeat a check already covered by a successful umbrella gate.
|
||||||
quarantine with an issue link, fix or delete within 30 days); the local
|
Rerun only checks affected by later edits.
|
||||||
`default` nextest profile never retries.
|
|
||||||
|
|
||||||
## Adversarial Validation (Default On)
|
Never weaken a gate to get green: do not add baselines/allowances, suppress
|
||||||
|
lints, ignore tests, or relax assertions unless changing that policy is itself
|
||||||
|
the reviewed task. Follow `docs/testing/README.md` for flaky tests.
|
||||||
|
|
||||||
Every non-exempt output (see Risk tiers) — code change, bug fix, or
|
## Adversarial Validation
|
||||||
design/solution proposal — passes multi-role adversarial review before it
|
|
||||||
counts as done.
|
|
||||||
Author confidence is not evidence: each role's job is to refute the change,
|
|
||||||
not to bless it.
|
|
||||||
|
|
||||||
### Risk tiers
|
Adversarial validation applies to final implementation diffs, explicitly
|
||||||
|
requested adversarial/design reviews, and agent-instruction changes that alter
|
||||||
|
execution. Ordinary questions, diagnoses, status reports, non-adversarial code
|
||||||
|
reviews, and low-risk planning do not trigger it.
|
||||||
|
|
||||||
Pick the tier from the riskiest file touched; when in doubt, pick the higher.
|
Risk and review shape:
|
||||||
|
|
||||||
- **Exempt:** docs/comments, formatting, and typos that cannot affect runtime,
|
- **Exempt:** documentation, comments, formatting, or typos with no runtime,
|
||||||
builds, tests, or agent execution. Skip this section.
|
build, test, or agent-execution effect.
|
||||||
- **Mechanical:** pure renames, file moves, test-only or tooling changes, and
|
- **Mechanical:** renames, moves, test/tooling-only changes, and agent-rule
|
||||||
agent-instruction changes that alter execution —
|
changes. Run correctness and simplicity lenses.
|
||||||
correctness and simplicity adversaries only.
|
- **Standard:** localized behavior changes. Run one integrated final-diff pass
|
||||||
- **Standard (the default):** any change that affects behavior.
|
covering correctness, simplicity, and test coverage; add only domain lenses
|
||||||
- **High risk:** touches locking, erasure coding, quorum/heal, replication,
|
matched by the diff.
|
||||||
multipart, RPC, lifecycle/tiering, metadata formats (`xl.meta`),
|
- **High risk / substantial PR review:** high risk includes locking,
|
||||||
persistence/fsync, IAM/KMS/auth, on-disk or on-wire formats, or
|
erasure/quorum/heal, replication, multipart, RPC, lifecycle/tiering,
|
||||||
S3 API-visible behavior.
|
persistence/fsync, IAM/KMS/auth, cryptography, on-disk/on-wire formats, and
|
||||||
|
S3-visible semantics. Cover all applicable lenses using exactly two
|
||||||
|
independent reviewers when delegation is explicitly authorized. Split the
|
||||||
|
lenses between them. Otherwise perform two fresh sequential passes.
|
||||||
|
|
||||||
### Roles
|
Available domain lenses are security, concurrency/durability, compatibility,
|
||||||
|
and performance. Select `.agents/skills/adversarial-validation/SKILL.md` for an
|
||||||
|
explicit adversarial request, a high-risk change, or a substantial PR review;
|
||||||
|
then read only its matching role references. A routine standard pass does not
|
||||||
|
load the playbook unless the reviewer needs a RustFS-specific probe.
|
||||||
|
|
||||||
Run each applicable role as an independent pass over the final diff (or
|
A finding must name a concrete input/state/interleaving and wrong outcome, or a
|
||||||
proposal text) — parallel reviewer agents where the tooling supports them,
|
specific missing regression check, with `file:line`. Resolve it by fixing the
|
||||||
otherwise sequential passes that each start fresh from the diff and the
|
diff or rebutting it with code-path/test/invariant evidence. After a non-trivial
|
||||||
nearest scoped `AGENTS.md`, discarding the writing session's assumptions.
|
fix, rerun only affected lenses.
|
||||||
Each role either produces findings or reports "attacked X, Y, Z — no break
|
|
||||||
found"; a bare pass is not a result. Repo-specific attack probes for every
|
|
||||||
role live in `.agents/skills/adversarial-validation/` — run them, they
|
|
||||||
encode this repo's shipped bugs.
|
|
||||||
|
|
||||||
- **Correctness adversary** — construct a concrete input/state/interleaving
|
For high-risk PRs, record one concise verdict per covered lens in the PR body.
|
||||||
that yields wrong output, data loss, or a crash. Probe error paths and edge
|
|
||||||
values (empty, nil UUID, zero-length, quorum−1, missing version).
|
|
||||||
- **Simplicity adversary** — same behavior, less code. Hunt reimplemented helpers, rewrites where an in-place edit suffices, speculative abstractions, defensive branches with no nameable trigger, redundant error wrapping, near-duplicate tests, and narration comments. A one-caller helper is a finding only when it merely forwards or splits a short linear flow without adding domain naming, boundary isolation, an invariant, or useful error context. Report a concrete smaller replacement; fewer lines alone are not evidence.
|
|
||||||
- **Security reviewer** — authn/authz bypass, injection, secret leakage,
|
|
||||||
untrusted deserialization (see Serde Safety), path traversal, timing leaks.
|
|
||||||
- **Concurrency/durability reviewer** — lock ordering, races, cancellation,
|
|
||||||
partial failure, retry/idempotency, crash and power-loss ordering.
|
|
||||||
- **Compatibility reviewer** — S3 API surface, MinIO interop, on-disk and
|
|
||||||
on-wire formats, mixed-version upgrade/downgrade paths.
|
|
||||||
- **Performance reviewer** — allocation and cloning on hot paths, lock hold
|
|
||||||
time across IO, sync or CPU-heavy work on async runtime threads, added
|
|
||||||
fsync/flush outside the durability gate, hot-path logging noise. A
|
|
||||||
measurable regression on a per-request or per-object path is a finding.
|
|
||||||
- **Test-coverage skeptic** — for each testable behavior claim, name the test
|
|
||||||
or executable check that detects a revert; then name a changed line that
|
|
||||||
could be wrong while all checks stay green. If a focused check is not
|
|
||||||
reasonable, require the reason and residual risk from the validation floor.
|
|
||||||
Test additions have no line-count or growth budget.
|
|
||||||
|
|
||||||
Standard tier: correctness adversary + simplicity adversary + test-coverage
|
## Pull Request Lifecycle
|
||||||
skeptic, plus every role whose domain the diff touches (async or
|
|
||||||
shared-state code → concurrency; parsing of untrusted input → security;
|
|
||||||
public crate API shape → compatibility; per-request or per-object hot paths
|
|
||||||
→ performance).
|
|
||||||
High risk: all seven roles.
|
|
||||||
|
|
||||||
### Protocol
|
- Creating or updating a PR includes one immediate snapshot of checks,
|
||||||
|
mergeability, reviews, and unresolved threads.
|
||||||
1. A finding states a concrete failure scenario (input/state → wrong
|
- Unless the user explicitly requests monitoring, a release workflow requires
|
||||||
outcome) or names a missing test, with severity and file:line. "Looks
|
it, or an automation already owns it, hand off after the PR is open with the
|
||||||
risky" is not a finding.
|
current state and next event to watch. Do not delay ordinary handoff with
|
||||||
2. Resolve every finding: fix it, or rebut it with evidence — a test, a
|
fixed quiet-period sleeps.
|
||||||
traced code path, or a cited invariant. Restated intent and "unlikely"
|
- For requested monitoring, use event-driven or bounded waits. Report only state
|
||||||
are not rebuttals.
|
changes, actionable failures, or a meaningful prolonged delay.
|
||||||
3. After non-trivial fixes, re-run the roles whose domain the fix touched.
|
- Investigate failures/comments before changing code. Fix task-attributable
|
||||||
4. For proposals with no diff, roles attack assumptions, failure modes,
|
issues, rerun affected verification, push, reply or resolve the thread, then
|
||||||
migration/rollback, and testability instead — including the simplest
|
resume the requested monitor.
|
||||||
rejected alternative and the blast radius when the design fails.
|
- Never merge without required reviewer approval or explicit authority.
|
||||||
|
- After an observed merge, verify the commit reached the base, then clean the
|
||||||
### Exit criteria
|
task worktree/branch when safe. Preserve unmerged work for closed PRs unless
|
||||||
|
deletion was explicitly authorized.
|
||||||
- Every applicable role has run; every finding is fixed or rebutted with
|
|
||||||
evidence.
|
|
||||||
- Every testable behavior change has a focused regression check. Exceptions
|
|
||||||
follow the validation floor and state why a check is impractical and what
|
|
||||||
risk remains.
|
|
||||||
- The Verification Before PR gates pass — adversarial review supplements
|
|
||||||
those gates, never replaces them.
|
|
||||||
- High risk only: record a one-line verdict per role in the PR description.
|
|
||||||
|
|
||||||
## Git and PR Baseline
|
## Git and PR Baseline
|
||||||
|
|
||||||
- Use feature branches based on the latest `main`.
|
- Follow Conventional Commits; keep the subject at most 72 characters.
|
||||||
- Assume other agent sessions work this repository concurrently. Never commit
|
- Source comments, commits, PR titles, and PR bodies are in English.
|
||||||
in a shared checkout; do all work on a dedicated feature branch, preferably
|
- Keep every heading from `.github/pull_request_template.md`; use `N/A` where
|
||||||
in a dedicated worktree.
|
needed and include commands actually run.
|
||||||
- Immediately before branching, fetch `origin/main` and branch from it;
|
- Use `--body-file` for multiline `gh pr create`/`gh pr edit` content.
|
||||||
confirm the target issue is not already fixed there before writing code.
|
- PR/issue/discussion content must not contain the literal sequence `\n` or
|
||||||
- Follow Conventional Commits, with subject length <= 72 characters.
|
hard-wrapped prose paragraphs.
|
||||||
- Keep PR title and description in English.
|
- Do not include local absolute paths or tool-specific labels/prefixes in GitHub
|
||||||
- Use `.github/pull_request_template.md` and keep all section headings.
|
content.
|
||||||
- Use `N/A` for non-applicable template sections.
|
- Resolve review threads after the underlying issue is fixed. If declining a
|
||||||
- Include verification commands in the PR description.
|
suggestion, reply with a short evidence-based reason.
|
||||||
- When using `gh pr create`/`gh pr edit`, write the markdown body to a file
|
|
||||||
and pass `--body-file`; multiline inline `--body` is unsafe — backticks and
|
|
||||||
shell expansion can corrupt content or trigger unintended commands.
|
|
||||||
Pattern: `cat > /tmp/pr_body.md <<'EOF' ... EOF`, then
|
|
||||||
`--body-file /tmp/pr_body.md` (keep the file outside the checkout).
|
|
||||||
- Do not include the literal sequence `\n` in any GitHub issue, pull request, or discussion comment.
|
|
||||||
- Do not hard-wrap prose in PR/issue/discussion bodies; write each paragraph as a
|
|
||||||
single line and let it reflow. GitHub renders single newlines inside a paragraph
|
|
||||||
as line breaks, so mid-sentence wrapping shows up as ugly breaks. Only break lines
|
|
||||||
for list items, code blocks, and deliberate separators.
|
|
||||||
- After fixing code review comments or CI findings, always mark corresponding review
|
|
||||||
comments/threads as resolved before returning to the user.
|
|
||||||
- In handling review comments, confirm the underlying issue before changing code.
|
|
||||||
If a suggested change is not appropriate for behavior or risk, reply with a
|
|
||||||
concise rationale instead of blindly applying it.
|
|
||||||
|
|
||||||
## Security Baseline
|
## Security Baseline
|
||||||
|
|
||||||
- Never commit secrets, credentials, or key material.
|
- Never commit secrets, credentials, or key material.
|
||||||
- Use environment variables or vault tooling for sensitive configuration.
|
- Use environment variables or vault tooling for sensitive configuration.
|
||||||
- For localhost-sensitive tests, verify proxy settings to avoid traffic leakage.
|
- For localhost-sensitive tests, bypass proxies explicitly.
|
||||||
|
- Untrusted S3 XML/JSON, lifecycle, policy, replication, and RPC structures use
|
||||||
|
strict deserialization where compatibility permits. Security-critical
|
||||||
|
defaults require explicit validation.
|
||||||
|
|
||||||
## Logging
|
## Logging
|
||||||
|
|
||||||
Applies to **every** `tracing` macro you add or edit, including a single line
|
For every added or edited `tracing` call:
|
||||||
added in passing while fixing something else — not only to log-focused changes.
|
|
||||||
|
|
||||||
- Fields first, message second: `event`, `component`, `subsystem`,
|
- Reuse the module's `EVENT_*`, `LOG_COMPONENT_*`, and `LOG_SUBSYSTEM_*`
|
||||||
`result`/`state`, then key context. The message is a short label, not a
|
constants and field shape.
|
||||||
sentence with values interpolated into it.
|
- Put fields first and a short label last.
|
||||||
- Reuse the existing `EVENT_*` / `LOG_COMPONENT_*` / `LOG_SUBSYSTEM_*`
|
- Use `error` for behavior/security failure, `warn` for degradation/fallback,
|
||||||
constants of the module you are editing; match the shape of the log sites
|
`info` for low-frequency lifecycle, `debug` for diagnostics, and `trace` for
|
||||||
already in that file rather than introducing a second style next to them.
|
repetitive request/object success paths.
|
||||||
- Level policy: `error` for behavior/security-affecting failures, `warn` for
|
- Never log secrets, credential payloads, or merged configs.
|
||||||
degraded or fallback paths, `info` for low-frequency lifecycle, `debug` for
|
|
||||||
targeted diagnostics, `trace` for hot paths. Per-object and per-request
|
|
||||||
success paths are `trace`.
|
|
||||||
- Never log secrets, tokens, credential payloads, or merged config dumps.
|
|
||||||
- `scripts/check_logging_guardrails.sh` enforces a subset of this on the files
|
|
||||||
it lists; passing it is a floor, not evidence the log matches the house style.
|
|
||||||
|
|
||||||
See `.agents/skills/rustfs-logging-governance/SKILL.md` for the full event
|
Use `.agents/skills/rustfs-logging-governance/SKILL.md` for logging changes.
|
||||||
model, level policy, and guardrail-update checklist.
|
|
||||||
|
|
||||||
## Tools
|
## Cross-Cutting Storage Invariants
|
||||||
|
|
||||||
### xl.meta decode tool Quick Use
|
- Write internal object metadata under both `x-rustfs-internal-<suffix>` and
|
||||||
|
`x-minio-internal-<suffix>` using
|
||||||
|
`crates/utils/src/http/metadata_compat.rs` helpers.
|
||||||
|
- Read binary UUID metadata with
|
||||||
|
`.and_then(|v| Uuid::from_slice(&v).ok()).filter(|u| !u.is_nil())`; absent,
|
||||||
|
empty, and nil all mean no value.
|
||||||
|
- Remote-tier version `None` or `""` means an unversioned bucket; send no
|
||||||
|
`versionId` on tier GET/DELETE.
|
||||||
|
- `DataUsageCacheInfo` and `DataUsageEntry` keep their hand-written map
|
||||||
|
serialization and new fields remain `#[serde(default)]` for older readers.
|
||||||
|
|
||||||
```
|
## Naming
|
||||||
cargo run -p rustfs-filemeta --example dump_fileinfo -- "/path/to/file/xl.meta"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Serde Safety
|
Use Rust API naming: `SCREAMING_SNAKE_CASE` constants/statics, `snake_case`
|
||||||
|
functions/variables, and `PascalCase` types. Do not rename unrelated existing
|
||||||
|
violations.
|
||||||
|
|
||||||
- Add `#[serde(deny_unknown_fields)]` to structs deserialized from untrusted input (S3 API XML/JSON, lifecycle rules, bucket policies, replication configs).
|
## Scoped Guidance
|
||||||
- When `deny_unknown_fields` is impractical (backward compatibility), at minimum log unknown fields at `warn` level.
|
|
||||||
- Never use `#[serde(default)]` on security-critical fields without explicit validation of the resulting value.
|
|
||||||
|
|
||||||
## Cross-Cutting Domain Invariants
|
Before editing, locate the nearest instructions with:
|
||||||
|
|
||||||
- Write internal object metadata under **both** `x-rustfs-internal-<suffix>`
|
|
||||||
and `x-minio-internal-<suffix>` keys (MinIO interop). Use the helpers in
|
|
||||||
`crates/utils/src/http/metadata_compat.rs` (`get_bytes` prefers the RustFS
|
|
||||||
key); never write only one of the two.
|
|
||||||
- Read binary UUID metadata defensively:
|
|
||||||
`.and_then(|v| Uuid::from_slice(&v).ok()).filter(|u| !u.is_nil())` —
|
|
||||||
absent, empty, and nil all mean "no value", never `Uuid::nil()`.
|
|
||||||
- A remote-tier version of `None`/`""` means the tier bucket is unversioned:
|
|
||||||
send **no** `versionId` on tier GET/DELETE.
|
|
||||||
- Structs persisted in the scanner data-usage cache (`DataUsageCacheInfo`,
|
|
||||||
`DataUsageEntry`) carry a hand-written map-encoded `Serialize`. MessagePack
|
|
||||||
encodes derived structs as arrays, where an appended field makes the whole
|
|
||||||
cache a decode error for older readers — keep new fields `#[serde(default)]`
|
|
||||||
and keep the map encoding rather than reverting to `derive(Serialize)`.
|
|
||||||
|
|
||||||
## Naming Conventions
|
|
||||||
|
|
||||||
- Follow Rust API Guidelines for naming: `SCREAMING_SNAKE_CASE` for statics and constants, `snake_case` for functions and variables, `PascalCase` for types.
|
|
||||||
- Do not use camelCase or Hungarian notation (e.g., `globalDeploymentIDPtr` → `GLOBAL_DEPLOYMENT_ID`).
|
|
||||||
- If existing code violates naming conventions, do not widen the violation in new code. Do not rename existing symbols as part of an unrelated task; mention the violation instead (see Change Style for Existing Logic).
|
|
||||||
|
|
||||||
## Scoped Guidance in This Repository
|
|
||||||
|
|
||||||
Many crates and modules carry their own `AGENTS.md` with path-specific rules
|
|
||||||
(security boundaries, lock ordering, domain invariants). Before editing a
|
|
||||||
path, check for the nearest one:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git ls-files '*AGENTS.md'
|
git ls-files '*AGENTS.md'
|
||||||
```
|
```
|
||||||
|
|
||||||
The nearest file wins. Do not maintain a hand-written index of these files
|
The nearest file wins for domain invariants. Keep generic workflow and
|
||||||
here — it goes stale.
|
validation policy in this root file.
|
||||||
|
|||||||
+6
-4
@@ -91,8 +91,9 @@ A green `make pre-commit` is not enough to open a pull request.
|
|||||||
`make pre-pr` is the **full** gate: it runs all of the guard checks above,
|
`make pre-pr` is the **full** gate: it runs all of the guard checks above,
|
||||||
then `clippy-check` (`cargo clippy --all-targets --all-features -- -D warnings`)
|
then `clippy-check` (`cargo clippy --all-targets --all-features -- -D warnings`)
|
||||||
and `test` (shell script tests, workspace tests excluding `e2e_test`, and doc
|
and `test` (shell script tests, workspace tests excluding `e2e_test`, and doc
|
||||||
tests). Run `make pre-pr` before opening or updating a pull request — this is
|
tests). Complete the applicable multi-role adversarial review described in
|
||||||
what CI enforces.
|
`AGENTS.md` before running `make pre-pr`; then run the gate before opening or
|
||||||
|
updating a pull request. This is what CI enforces.
|
||||||
|
|
||||||
### 🔒 Git Pre-commit Hooks (optional)
|
### 🔒 Git Pre-commit Hooks (optional)
|
||||||
|
|
||||||
@@ -150,8 +151,9 @@ Example output when formatting fails:
|
|||||||
2. **Format your code**: `make fmt` or `cargo fmt --all`
|
2. **Format your code**: `make fmt` or `cargo fmt --all`
|
||||||
3. **Run the fast gate**: `make pre-commit` (no clippy, no tests)
|
3. **Run the fast gate**: `make pre-commit` (no clippy, no tests)
|
||||||
4. **Commit your changes**: `git commit -m "your message"`
|
4. **Commit your changes**: `git commit -m "your message"`
|
||||||
5. **Run the full gate before opening/updating a PR**: `make pre-pr` (clippy + tests)
|
5. **Complete the applicable multi-role adversarial review** for non-exempt changes (see `AGENTS.md`)
|
||||||
6. **Push to your branch**: `git push`
|
6. **Run the full gate before opening/updating a PR**: `make pre-pr` (clippy + tests)
|
||||||
|
7. **Push to your branch**: `git push`
|
||||||
|
|
||||||
### 🛠️ IDE Integration
|
### 🛠️ IDE Integration
|
||||||
|
|
||||||
|
|||||||
Generated
+3
-5
@@ -3843,7 +3843,6 @@ dependencies = [
|
|||||||
"s3s",
|
"s3s",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serial_test",
|
|
||||||
"sha2 0.11.0",
|
"sha2 0.11.0",
|
||||||
"suppaftp",
|
"suppaftp",
|
||||||
"time",
|
"time",
|
||||||
@@ -4757,9 +4756,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "h2"
|
name = "h2"
|
||||||
version = "0.4.17"
|
version = "0.4.18"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f877e75f39e9827ec50a572dd592684ac28c029578726c85f1b2aa6ab807449"
|
checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atomic-waker",
|
"atomic-waker",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -9257,6 +9256,7 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
"urlencoding",
|
"urlencoding",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
"x509-parser",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
"zip",
|
"zip",
|
||||||
"zstd",
|
"zstd",
|
||||||
@@ -9920,7 +9920,6 @@ dependencies = [
|
|||||||
"rustfs-config",
|
"rustfs-config",
|
||||||
"rustfs-io-metrics",
|
"rustfs-io-metrics",
|
||||||
"rustfs-utils",
|
"rustfs-utils",
|
||||||
"serial_test",
|
|
||||||
"temp-env",
|
"temp-env",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -10293,7 +10292,6 @@ dependencies = [
|
|||||||
"s3s",
|
"s3s",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serial_test",
|
|
||||||
"sha2 0.11.0",
|
"sha2 0.11.0",
|
||||||
"temp-env",
|
"temp-env",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
|
|||||||
@@ -204,6 +204,7 @@ rsa = { version = "=0.10.0-rc.18" }
|
|||||||
rustls = { default-features = false, version = "0.23.43" }
|
rustls = { default-features = false, version = "0.23.43" }
|
||||||
rustls-native-certs = "0.8"
|
rustls-native-certs = "0.8"
|
||||||
rustls-pki-types = "1.15.1"
|
rustls-pki-types = "1.15.1"
|
||||||
|
x509-parser = "0.18.1"
|
||||||
sha1 = "0.11.0"
|
sha1 = "0.11.0"
|
||||||
sha2 = "0.11.0"
|
sha2 = "0.11.0"
|
||||||
subtle = "2.6"
|
subtle = "2.6"
|
||||||
|
|||||||
+6
-2
@@ -19,7 +19,9 @@ Applies to all paths under `crates/`.
|
|||||||
|
|
||||||
- Document lock acquisition order when a module uses multiple locks. Never acquire the same set of locks in different orders across code paths.
|
- Document lock acquisition order when a module uses multiple locks. Never acquire the same set of locks in different orders across code paths.
|
||||||
- Never hold a `tokio::sync::RwLock`/`Mutex` write guard across `.await` points unless the critical section is unavoidably async and the hold time is bounded.
|
- Never hold a `tokio::sync::RwLock`/`Mutex` write guard across `.await` points unless the critical section is unavoidably async and the hold time is bounded.
|
||||||
- Prefer `compare_exchange` loops over load-then-store for concurrent counters (peak values, adaptive heuristics).
|
- Prefer direct atomic `fetch_*` operations for unconditional updates and
|
||||||
|
`compare_exchange` loops only for conditional updates such as peaks or
|
||||||
|
adaptive state.
|
||||||
- When resetting multi-field atomic statistics, use a version/sequence counter or accept that concurrent readers may see partial snapshots; document the tradeoff.
|
- When resetting multi-field atomic statistics, use a version/sequence counter or accept that concurrent readers may see partial snapshots; document the tradeoff.
|
||||||
- `std::sync::Mutex` is acceptable in async context only when held for a brief, non-`await`-containing critical section. If in doubt, use `tokio::sync::Mutex`.
|
- `std::sync::Mutex` is acceptable in async context only when held for a brief, non-`await`-containing critical section. If in doubt, use `tokio::sync::Mutex`.
|
||||||
|
|
||||||
@@ -40,7 +42,9 @@ Applies to all paths under `crates/`.
|
|||||||
- Keep unit tests close to the module they test.
|
- Keep unit tests close to the module they test.
|
||||||
- Keep integration tests under each crate's `tests/` directory.
|
- Keep integration tests under each crate's `tests/` directory.
|
||||||
- Add regression tests for bug fixes and behavior changes.
|
- Add regression tests for bug fixes and behavior changes.
|
||||||
- Every test function must contain at least one `assert!`/`assert_eq!`/`assert_matches!`. A test that only calls code without asserting is not a test.
|
- Every test needs an observable failure criterion. Direct assertions,
|
||||||
|
delegated assertions, snapshots/properties, `#[should_panic]`, and meaningful
|
||||||
|
`Result` failures are all valid; a call that can silently succeed is not.
|
||||||
- In tests, prefer `.expect("context: what was being tested")` over bare `.unwrap()`. A test failure should tell you which operation failed and with what input.
|
- In tests, prefer `.expect("context: what was being tested")` over bare `.unwrap()`. A test failure should tell you which operation failed and with what input.
|
||||||
|
|
||||||
## Async and Performance
|
## Async and Performance
|
||||||
|
|||||||
@@ -50,4 +50,3 @@ crate.
|
|||||||
- `cargo test -p rustfs-audit`
|
- `cargo test -p rustfs-audit`
|
||||||
- Focused: `cargo test -p rustfs-audit --test pipeline_layer_test`
|
- Focused: `cargo test -p rustfs-audit --test pipeline_layer_test`
|
||||||
- Focused: `cargo test -p rustfs-audit pipeline`
|
- Focused: `cargo test -p rustfs-audit pipeline`
|
||||||
- Full gate before commit: `make pre-commit`
|
|
||||||
|
|||||||
@@ -729,7 +729,7 @@ fn timestamp_elapsed_seconds_since(now: Timestamp, earlier: Timestamp) -> u64 {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
u64::try_from(duration.as_secs()).map_or(u64::MAX, |seconds| seconds)
|
u64::try_from(duration.as_secs()).unwrap_or(u64::MAX)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
@@ -781,6 +781,19 @@ struct ScannerBucketDriveResultValue {
|
|||||||
last_seen: u64,
|
last_seen: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
|
struct ScannerActiveBucketDriveKey {
|
||||||
|
source: String,
|
||||||
|
bucket: String,
|
||||||
|
drive: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ScannerActiveBucketDriveValue {
|
||||||
|
count: u64,
|
||||||
|
started_at: Timestamp,
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Metrics
|
// Metrics
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -813,6 +826,7 @@ pub struct Metrics {
|
|||||||
scanner_set_scans_active: AtomicU64,
|
scanner_set_scans_active: AtomicU64,
|
||||||
scanner_disk_bucket_scan_states: Mutex<HashMap<ScannerDiskBucketScanKey, ScannerDiskBucketScanState>>,
|
scanner_disk_bucket_scan_states: Mutex<HashMap<ScannerDiskBucketScanKey, ScannerDiskBucketScanState>>,
|
||||||
scanner_bucket_drive_results: Mutex<ScannerBucketDriveResults>,
|
scanner_bucket_drive_results: Mutex<ScannerBucketDriveResults>,
|
||||||
|
scanner_active_bucket_drive_scans: Mutex<HashMap<ScannerActiveBucketDriveKey, ScannerActiveBucketDriveValue>>,
|
||||||
scanner_bucket_drive_result_clock: AtomicU64,
|
scanner_bucket_drive_result_clock: AtomicU64,
|
||||||
current_scan_cycle_bucket_drive_results_start: Mutex<HashMap<ScannerBucketDriveResultKey, u64>>,
|
current_scan_cycle_bucket_drive_results_start: Mutex<HashMap<ScannerBucketDriveResultKey, u64>>,
|
||||||
last_scan_cycle_bucket_drive_results: Mutex<Vec<ScannerBucketDriveResultSnapshot>>,
|
last_scan_cycle_bucket_drive_results: Mutex<Vec<ScannerBucketDriveResultSnapshot>>,
|
||||||
@@ -1045,6 +1059,15 @@ pub struct ScannerBucketDriveResultSnapshot {
|
|||||||
pub count: u64,
|
pub count: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct ScannerActiveBucketDriveSnapshot {
|
||||||
|
pub source: String,
|
||||||
|
pub bucket: String,
|
||||||
|
pub drive: String,
|
||||||
|
pub count: u64,
|
||||||
|
pub age_seconds: u64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
pub struct ScannerReplicationRepairSnapshot {
|
pub struct ScannerReplicationRepairSnapshot {
|
||||||
pub source: String,
|
pub source: String,
|
||||||
@@ -1387,6 +1410,8 @@ pub struct ScannerRuntimeDetailsReport {
|
|||||||
pub current_cycle_bucket_drive_results: Vec<ScannerBucketDriveResultSnapshot>,
|
pub current_cycle_bucket_drive_results: Vec<ScannerBucketDriveResultSnapshot>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub last_cycle_bucket_drive_results: Vec<ScannerBucketDriveResultSnapshot>,
|
pub last_cycle_bucket_drive_results: Vec<ScannerBucketDriveResultSnapshot>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub active_bucket_drive_scans: Vec<ScannerActiveBucketDriveSnapshot>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CurrentCycle {
|
impl CurrentCycle {
|
||||||
@@ -1746,7 +1771,7 @@ pub fn emit_scan_cycle_deferred(duration: Duration) {
|
|||||||
metrics::counter!(OTEL_SCANNER_CYCLES, "result" => SCAN_CYCLE_RESULT_DEFERRED_LABEL).increment(1);
|
metrics::counter!(OTEL_SCANNER_CYCLES, "result" => SCAN_CYCLE_RESULT_DEFERRED_LABEL).increment(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn emit_scan_bucket_drive_complete(success: bool, bucket: &str, disk: &str, duration: Duration) {
|
pub fn emit_scan_bucket_drive_complete(_source: ScannerWorkSource, success: bool, bucket: &str, disk: &str, duration: Duration) {
|
||||||
let result = if success { "success" } else { "error" };
|
let result = if success { "success" } else { "error" };
|
||||||
global_metrics().record_scanner_bucket_drive_result(bucket, disk, result);
|
global_metrics().record_scanner_bucket_drive_result(bucket, disk, result);
|
||||||
metrics::counter!(
|
metrics::counter!(
|
||||||
@@ -1764,7 +1789,7 @@ pub fn emit_scan_bucket_drive_complete(success: bool, bucket: &str, disk: &str,
|
|||||||
.record(duration.as_secs_f64());
|
.record(duration.as_secs_f64());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn emit_scan_bucket_drive_partial(bucket: &str, disk: &str, duration: Duration) {
|
pub fn emit_scan_bucket_drive_partial(_source: ScannerWorkSource, bucket: &str, disk: &str, duration: Duration) {
|
||||||
global_metrics().record_scanner_bucket_drive_result(bucket, disk, SCAN_CYCLE_RESULT_PARTIAL_LABEL);
|
global_metrics().record_scanner_bucket_drive_result(bucket, disk, SCAN_CYCLE_RESULT_PARTIAL_LABEL);
|
||||||
metrics::counter!(
|
metrics::counter!(
|
||||||
OTEL_SCANNER_BUCKETS_SCANNED,
|
OTEL_SCANNER_BUCKETS_SCANNED,
|
||||||
@@ -1817,6 +1842,7 @@ impl Metrics {
|
|||||||
scanner_set_scans_active: AtomicU64::new(0),
|
scanner_set_scans_active: AtomicU64::new(0),
|
||||||
scanner_disk_bucket_scan_states: Mutex::new(HashMap::new()),
|
scanner_disk_bucket_scan_states: Mutex::new(HashMap::new()),
|
||||||
scanner_bucket_drive_results: Mutex::new(ScannerBucketDriveResults::default()),
|
scanner_bucket_drive_results: Mutex::new(ScannerBucketDriveResults::default()),
|
||||||
|
scanner_active_bucket_drive_scans: Mutex::new(HashMap::new()),
|
||||||
scanner_bucket_drive_result_clock: AtomicU64::new(0),
|
scanner_bucket_drive_result_clock: AtomicU64::new(0),
|
||||||
current_scan_cycle_bucket_drive_results_start: Mutex::new(HashMap::new()),
|
current_scan_cycle_bucket_drive_results_start: Mutex::new(HashMap::new()),
|
||||||
last_scan_cycle_bucket_drive_results: Mutex::new(Vec::new()),
|
last_scan_cycle_bucket_drive_results: Mutex::new(Vec::new()),
|
||||||
@@ -2308,8 +2334,45 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn record_scan_bucket_drive_start(&self) {
|
pub fn record_scan_bucket_drive_start(&self, source: ScannerWorkSource, bucket: &str, drive: &str) {
|
||||||
self.operations[Metric::ScanBucketDriveStart as usize].fetch_add(1, Ordering::Relaxed);
|
self.operations[Metric::ScanBucketDriveStart as usize].fetch_add(1, Ordering::Relaxed);
|
||||||
|
if bucket.is_empty() || drive.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let key = ScannerActiveBucketDriveKey {
|
||||||
|
source: source.as_str().to_string(),
|
||||||
|
bucket: bucket.to_string(),
|
||||||
|
drive: drive.to_string(),
|
||||||
|
};
|
||||||
|
let mut active = self
|
||||||
|
.scanner_active_bucket_drive_scans
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
active
|
||||||
|
.entry(key)
|
||||||
|
.and_modify(|value| value.count = value.count.saturating_add(1))
|
||||||
|
.or_insert(ScannerActiveBucketDriveValue {
|
||||||
|
count: 1,
|
||||||
|
started_at: Timestamp::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_scan_bucket_drive_end(&self, source: ScannerWorkSource, bucket: &str, drive: &str) {
|
||||||
|
let key = ScannerActiveBucketDriveKey {
|
||||||
|
source: source.as_str().to_string(),
|
||||||
|
bucket: bucket.to_string(),
|
||||||
|
drive: drive.to_string(),
|
||||||
|
};
|
||||||
|
let mut active = self
|
||||||
|
.scanner_active_bucket_drive_scans
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
if let Some(value) = active.get_mut(&key) {
|
||||||
|
value.count = value.count.saturating_sub(1);
|
||||||
|
if value.count == 0 {
|
||||||
|
active.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn record_scan_bucket_drive_failure(&self) {
|
pub fn record_scan_bucket_drive_failure(&self) {
|
||||||
@@ -2782,6 +2845,26 @@ impl Metrics {
|
|||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
|
let now = Timestamp::now();
|
||||||
|
let mut active_bucket_drive_scans = self
|
||||||
|
.scanner_active_bucket_drive_scans
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
.iter()
|
||||||
|
.map(|(key, value)| ScannerActiveBucketDriveSnapshot {
|
||||||
|
source: key.source.clone(),
|
||||||
|
bucket: key.bucket.clone(),
|
||||||
|
drive: key.drive.clone(),
|
||||||
|
count: value.count,
|
||||||
|
age_seconds: timestamp_elapsed_seconds_since(now, value.started_at),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
active_bucket_drive_scans.sort_by(|left, right| {
|
||||||
|
left.source
|
||||||
|
.cmp(&right.source)
|
||||||
|
.then_with(|| left.bucket.cmp(&right.bucket))
|
||||||
|
.then_with(|| left.drive.cmp(&right.drive))
|
||||||
|
});
|
||||||
ScannerRuntimeDetailsReport {
|
ScannerRuntimeDetailsReport {
|
||||||
disk_bucket_scan_states: self.scanner_disk_bucket_scan_state_snapshots(),
|
disk_bucket_scan_states: self.scanner_disk_bucket_scan_state_snapshots(),
|
||||||
bucket_drive_results: self.scanner_bucket_drive_result_counter_snapshots(),
|
bucket_drive_results: self.scanner_bucket_drive_result_counter_snapshots(),
|
||||||
@@ -2791,6 +2874,7 @@ impl Metrics {
|
|||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
.clone(),
|
.clone(),
|
||||||
|
active_bucket_drive_scans,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4371,7 +4455,7 @@ mod tests {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn report_includes_bucket_drive_scan_starts() {
|
async fn report_includes_bucket_drive_scan_starts() {
|
||||||
let metrics = Metrics::new();
|
let metrics = Metrics::new();
|
||||||
metrics.record_scan_bucket_drive_start();
|
metrics.record_scan_bucket_drive_start(ScannerWorkSource::Usage, "bucket-a", "/mnt/data/1");
|
||||||
metrics.record_scan_bucket_drive_failure();
|
metrics.record_scan_bucket_drive_failure();
|
||||||
|
|
||||||
let report = metrics.report().await;
|
let report = metrics.report().await;
|
||||||
@@ -4380,6 +4464,27 @@ mod tests {
|
|||||||
assert_eq!(report.life_time_ops.get("scan_bucket_drive_failure"), Some(&1));
|
assert_eq!(report.life_time_ops.get("scan_bucket_drive_failure"), Some(&1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn active_bucket_drive_snapshot_is_structured_and_retired_on_end() {
|
||||||
|
let metrics = Metrics::new();
|
||||||
|
metrics.record_scan_bucket_drive_start(ScannerWorkSource::Usage, "bucket-a", "/mnt/data/1");
|
||||||
|
metrics.record_scan_bucket_drive_start(ScannerWorkSource::Usage, "bucket-a", "/mnt/data/1");
|
||||||
|
let active = metrics.scanner_runtime_details_report().active_bucket_drive_scans;
|
||||||
|
assert_eq!(active.len(), 1);
|
||||||
|
assert_eq!(active[0].source, ScannerWorkSource::Usage.as_str());
|
||||||
|
assert_eq!(active[0].bucket, "bucket-a");
|
||||||
|
assert_eq!(active[0].drive, "/mnt/data/1");
|
||||||
|
assert_eq!(active[0].count, 2);
|
||||||
|
|
||||||
|
metrics.record_scan_bucket_drive_end(ScannerWorkSource::Usage, "bucket-a", "/mnt/data/1");
|
||||||
|
assert_eq!(metrics.scanner_runtime_details_report().active_bucket_drive_scans[0].count, 1);
|
||||||
|
metrics.record_scan_bucket_drive_end(ScannerWorkSource::Usage, "bucket-a", "/mnt/data/1");
|
||||||
|
assert!(metrics.scanner_runtime_details_report().active_bucket_drive_scans.is_empty());
|
||||||
|
|
||||||
|
metrics.record_scan_bucket_drive_start(ScannerWorkSource::Usage, "", "/mnt/data/1");
|
||||||
|
assert!(metrics.scanner_runtime_details_report().active_bucket_drive_scans.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn report_includes_structured_bucket_drive_results() {
|
async fn report_includes_structured_bucket_drive_results() {
|
||||||
let metrics = Metrics::new();
|
let metrics = Metrics::new();
|
||||||
|
|||||||
@@ -115,6 +115,15 @@ Current guidance:
|
|||||||
- enables KMS readiness enforcement for `/health/ready`.
|
- enables KMS readiness enforcement for `/health/ready`.
|
||||||
- default is `false`.
|
- default is `false`.
|
||||||
|
|
||||||
|
## Object lock admission environment variables
|
||||||
|
|
||||||
|
- `RUSTFS_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS`
|
||||||
|
- experimental same-object PUT commit namespace-lock admission budget.
|
||||||
|
- default is `0`, which disables this override and keeps `RUSTFS_OBJECT_LOCK_ACQUIRE_TIMEOUT` behavior.
|
||||||
|
- when set, only `put_object_commit` write-lock acquisition is bounded by this millisecond budget; other namespace lock users keep the global object-lock timeout.
|
||||||
|
- timeout returns S3 `SlowDown`, so clients should use normal SDK retry handling.
|
||||||
|
- this is not a fdatasync or group-commit switch. Track fdatasync batching separately with `rustfs_s3_put_object_rename_fdatasync_batch_files`.
|
||||||
|
|
||||||
## Drive timeout environment variables
|
## Drive timeout environment variables
|
||||||
|
|
||||||
- `RUSTFS_DRIVE_METADATA_TIMEOUT_SECS`
|
- `RUSTFS_DRIVE_METADATA_TIMEOUT_SECS`
|
||||||
|
|||||||
@@ -427,6 +427,19 @@ pub const ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT: &str = "RUSTFS_OBJECT_LOCK_ACQUIRE_TI
|
|||||||
/// Default lock acquisition timeout: 5 seconds.
|
/// Default lock acquisition timeout: 5 seconds.
|
||||||
pub const DEFAULT_OBJECT_LOCK_ACQUIRE_TIMEOUT: u64 = 5;
|
pub const DEFAULT_OBJECT_LOCK_ACQUIRE_TIMEOUT: u64 = 5;
|
||||||
|
|
||||||
|
/// Environment variable for the experimental PUT commit namespace lock acquire timeout in milliseconds.
|
||||||
|
///
|
||||||
|
/// A value of `0` disables the experiment and keeps
|
||||||
|
/// `RUSTFS_OBJECT_LOCK_ACQUIRE_TIMEOUT` as the timeout. This only bounds the
|
||||||
|
/// `put_object_commit` namespace write-lock wait and is intended for #925
|
||||||
|
/// tail-drain admission experiments.
|
||||||
|
///
|
||||||
|
/// Default: 0 milliseconds (disabled).
|
||||||
|
pub const ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS: &str = "RUSTFS_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS";
|
||||||
|
|
||||||
|
/// Default: PUT commit namespace lock acquire timeout override is disabled.
|
||||||
|
pub const DEFAULT_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS: u64 = 0;
|
||||||
|
|
||||||
/// Environment variable for remote namespace lock RPC transport timeout in milliseconds.
|
/// Environment variable for remote namespace lock RPC transport timeout in milliseconds.
|
||||||
///
|
///
|
||||||
/// This timeout bounds the internode RPC call itself. It is intentionally
|
/// This timeout bounds the internode RPC call itself. It is intentionally
|
||||||
|
|||||||
@@ -57,6 +57,13 @@ pub const DEFAULT_MAX_IO_EVENTS_PER_TICK: usize = 1024;
|
|||||||
pub const DEFAULT_EVENT_INTERVAL: u32 = 61;
|
pub const DEFAULT_EVENT_INTERVAL: u32 = 61;
|
||||||
pub const DEFAULT_RNG_SEED: Option<u64> = None; // None means random
|
pub const DEFAULT_RNG_SEED: Option<u64> = None; // None means random
|
||||||
|
|
||||||
|
/// Dedicated blocking thread pool for fsync/fdatasync operations.
|
||||||
|
/// When > 1, fsync operations are isolated from the main blocking pool to
|
||||||
|
/// prevent device-bound fsync from starving read operations (pread/stat/open).
|
||||||
|
/// Default 0 means auto (no isolation, use main runtime).
|
||||||
|
pub const ENV_FSYNC_BLOCKING_THREADS: &str = "RUSTFS_RUNTIME_FSYNC_BLOCKING_THREADS";
|
||||||
|
pub const DEFAULT_FSYNC_BLOCKING_THREADS: usize = 0;
|
||||||
|
|
||||||
// Dial9 Tokio Telemetry Default values
|
// Dial9 Tokio Telemetry Default values
|
||||||
pub const DEFAULT_RUNTIME_DIAL9_ENABLED: bool = false; // Disabled by default
|
pub const DEFAULT_RUNTIME_DIAL9_ENABLED: bool = false; // Disabled by default
|
||||||
pub const DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR: &str = "/var/log/rustfs/telemetry";
|
pub const DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR: &str = "/var/log/rustfs/telemetry";
|
||||||
|
|||||||
@@ -585,9 +585,12 @@ impl VersionsHistogram {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replication statistics for a single target
|
/// Replication statistics for a single target.
|
||||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
///
|
||||||
pub struct ReplicationStats {
|
/// Renamed from `ReplicationStats`; serde field names are preserved
|
||||||
|
/// byte-identically to maintain wire compatibility with existing snapshots.
|
||||||
|
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct ReplicationTargetUsage {
|
||||||
pub pending_size: u64,
|
pub pending_size: u64,
|
||||||
pub replicated_size: u64,
|
pub replicated_size: u64,
|
||||||
pub failed_size: u64,
|
pub failed_size: u64,
|
||||||
@@ -600,7 +603,7 @@ pub struct ReplicationStats {
|
|||||||
pub replicated_count: u64,
|
pub replicated_count: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ReplicationStats {
|
impl ReplicationTargetUsage {
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
let Self {
|
let Self {
|
||||||
pending_size,
|
pending_size,
|
||||||
@@ -636,7 +639,7 @@ impl ReplicationStats {
|
|||||||
/// Replication statistics for all targets
|
/// Replication statistics for all targets
|
||||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||||
pub struct ReplicationAllStats {
|
pub struct ReplicationAllStats {
|
||||||
pub targets: HashMap<String, ReplicationStats>,
|
pub targets: HashMap<String, ReplicationTargetUsage>,
|
||||||
pub replica_size: u64,
|
pub replica_size: u64,
|
||||||
pub replica_count: u64,
|
pub replica_count: u64,
|
||||||
}
|
}
|
||||||
@@ -649,7 +652,7 @@ impl ReplicationAllStats {
|
|||||||
targets,
|
targets,
|
||||||
} = self;
|
} = self;
|
||||||
|
|
||||||
*replica_size == 0 && *replica_count == 0 && targets.values().all(ReplicationStats::is_empty)
|
*replica_size == 0 && *replica_count == 0 && targets.values().all(ReplicationTargetUsage::is_empty)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[deprecated(note = "use is_empty instead")]
|
#[deprecated(note = "use is_empty instead")]
|
||||||
@@ -2466,7 +2469,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn replication_stats_empty_checks_every_field() {
|
fn replication_stats_empty_checks_every_field() {
|
||||||
type SetField = fn(&mut ReplicationStats);
|
type SetField = fn(&mut ReplicationTargetUsage);
|
||||||
|
|
||||||
let cases: [(&str, SetField); 10] = [
|
let cases: [(&str, SetField); 10] = [
|
||||||
("pending_size", |stats| stats.pending_size = 1),
|
("pending_size", |stats| stats.pending_size = 1),
|
||||||
@@ -2481,9 +2484,9 @@ mod tests {
|
|||||||
("replicated_count", |stats| stats.replicated_count = 1),
|
("replicated_count", |stats| stats.replicated_count = 1),
|
||||||
];
|
];
|
||||||
|
|
||||||
assert!(ReplicationStats::default().is_empty());
|
assert!(ReplicationTargetUsage::default().is_empty());
|
||||||
for (field, set_nonzero) in cases {
|
for (field, set_nonzero) in cases {
|
||||||
let mut stats = ReplicationStats::default();
|
let mut stats = ReplicationTargetUsage::default();
|
||||||
set_nonzero(&mut stats);
|
set_nonzero(&mut stats);
|
||||||
assert!(!stats.is_empty(), "{field} must make replication stats non-empty");
|
assert!(!stats.is_empty(), "{field} must make replication stats non-empty");
|
||||||
}
|
}
|
||||||
@@ -2514,17 +2517,17 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let empty_targets = ReplicationAllStats {
|
let empty_targets = ReplicationAllStats {
|
||||||
targets: HashMap::from([("arn:test:empty".to_string(), ReplicationStats::default())]),
|
targets: HashMap::from([("arn:test:empty".to_string(), ReplicationTargetUsage::default())]),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
assert!(empty_targets.is_empty(), "all-empty targets must keep aggregate stats empty");
|
assert!(empty_targets.is_empty(), "all-empty targets must keep aggregate stats empty");
|
||||||
|
|
||||||
let stats = ReplicationAllStats {
|
let stats = ReplicationAllStats {
|
||||||
targets: HashMap::from([
|
targets: HashMap::from([
|
||||||
("arn:test:empty".to_string(), ReplicationStats::default()),
|
("arn:test:empty".to_string(), ReplicationTargetUsage::default()),
|
||||||
(
|
(
|
||||||
"arn:test:non-empty".to_string(),
|
"arn:test:non-empty".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
pending_count: 1,
|
pending_count: 1,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -2565,7 +2568,7 @@ mod tests {
|
|||||||
replication_stats: Some(ReplicationAllStats {
|
replication_stats: Some(ReplicationAllStats {
|
||||||
targets: HashMap::from([(
|
targets: HashMap::from([(
|
||||||
"arn:test:pending".to_string(),
|
"arn:test:pending".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
pending_count: 1,
|
pending_count: 1,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -2714,7 +2717,7 @@ mod tests {
|
|||||||
targets: HashMap::from([
|
targets: HashMap::from([
|
||||||
(
|
(
|
||||||
"arn:self-only".to_string(),
|
"arn:self-only".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
pending_size: 7,
|
pending_size: 7,
|
||||||
pending_count: 1,
|
pending_count: 1,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -2722,7 +2725,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
(
|
(
|
||||||
"arn:shared".to_string(),
|
"arn:shared".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
failed_size: 3,
|
failed_size: 3,
|
||||||
failed_count: 1,
|
failed_count: 1,
|
||||||
missed_threshold_size: 2,
|
missed_threshold_size: 2,
|
||||||
@@ -2741,7 +2744,7 @@ mod tests {
|
|||||||
targets: HashMap::from([
|
targets: HashMap::from([
|
||||||
(
|
(
|
||||||
"arn:shared".to_string(),
|
"arn:shared".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
failed_size: 5,
|
failed_size: 5,
|
||||||
failed_count: 2,
|
failed_count: 2,
|
||||||
after_threshold_size: 4,
|
after_threshold_size: 4,
|
||||||
@@ -2751,7 +2754,7 @@ mod tests {
|
|||||||
),
|
),
|
||||||
(
|
(
|
||||||
"arn:other-only".to_string(),
|
"arn:other-only".to_string(),
|
||||||
ReplicationStats {
|
ReplicationTargetUsage {
|
||||||
replicated_size: 11,
|
replicated_size: 11,
|
||||||
replicated_count: 3,
|
replicated_count: 3,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -2993,7 +2996,9 @@ mod tests {
|
|||||||
fn replication_target_deserialization_preserves_large_historical_maps() {
|
fn replication_target_deserialization_preserves_large_historical_maps() {
|
||||||
let mut stats = ReplicationAllStats::default();
|
let mut stats = ReplicationAllStats::default();
|
||||||
for index in 0..=1024 {
|
for index in 0..=1024 {
|
||||||
stats.targets.insert(format!("target-{index}"), ReplicationStats::default());
|
stats
|
||||||
|
.targets
|
||||||
|
.insert(format!("target-{index}"), ReplicationTargetUsage::default());
|
||||||
}
|
}
|
||||||
let encoded = rmp_serde::to_vec_named(&stats).expect("large replication target fixture should encode");
|
let encoded = rmp_serde::to_vec_named(&stats).expect("large replication target fixture should encode");
|
||||||
let decoded = rmp_serde::from_slice::<ReplicationAllStats>(&encoded)
|
let decoded = rmp_serde::from_slice::<ReplicationAllStats>(&encoded)
|
||||||
@@ -3002,6 +3007,47 @@ mod tests {
|
|||||||
assert_eq!(decoded.targets.len(), stats.targets.len());
|
assert_eq!(decoded.targets.len(), stats.targets.len());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Round-trip test: encoding a [`ReplicationTargetUsage`] and decoding it back
|
||||||
|
/// must produce the exact same value. This guards against accidental serde
|
||||||
|
/// field-name drift during the `ReplicationStats` -> `ReplicationTargetUsage`
|
||||||
|
/// rename. Wire-level field names are the serialized Rust field identifiers,
|
||||||
|
/// which must remain byte-identical.
|
||||||
|
#[test]
|
||||||
|
fn replication_target_usage_rmp_round_trip() {
|
||||||
|
let original = ReplicationTargetUsage {
|
||||||
|
pending_size: 100,
|
||||||
|
replicated_size: 2_000,
|
||||||
|
failed_size: 50,
|
||||||
|
failed_count: 3,
|
||||||
|
pending_count: 7,
|
||||||
|
missed_threshold_size: 11,
|
||||||
|
after_threshold_size: 22,
|
||||||
|
missed_threshold_count: 1,
|
||||||
|
after_threshold_count: 2,
|
||||||
|
replicated_count: 99,
|
||||||
|
};
|
||||||
|
|
||||||
|
let buf = rmp_serde::to_vec_named(&original).expect("encode ReplicationTargetUsage to msgpack");
|
||||||
|
let decoded: ReplicationTargetUsage = rmp_serde::from_slice(&buf).expect("decode ReplicationTargetUsage from msgpack");
|
||||||
|
assert_eq!(original, decoded, "round-trip through rmp must preserve every field");
|
||||||
|
|
||||||
|
// Also verify that encoding as an unnamed sequence and then decoding
|
||||||
|
// with named fields produces the correct mapping (this catches reordering).
|
||||||
|
let named_buf = rmp_serde::to_vec_named(&original).expect("re-encode for field-name pinning");
|
||||||
|
// Spot-check that known field names appear in the named encoding.
|
||||||
|
let named_str = String::from_utf8_lossy(&named_buf);
|
||||||
|
assert!(named_str.contains("pending_size"), "field 'pending_size' must survive the rename");
|
||||||
|
assert!(named_str.contains("replicated_size"), "field 'replicated_size' must survive the rename");
|
||||||
|
assert!(
|
||||||
|
named_str.contains("missed_threshold_size"),
|
||||||
|
"field 'missed_threshold_size' must survive the rename"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
named_str.contains("after_threshold_count"),
|
||||||
|
"field 'after_threshold_count' must survive the rename"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn checked_merge_rejects_noncanonical_histograms_without_mutation() {
|
fn checked_merge_rejects_noncanonical_histograms_without_mutation() {
|
||||||
let mut entry = DataUsageEntry {
|
let mut entry = DataUsageEntry {
|
||||||
|
|||||||
@@ -28,4 +28,3 @@ follow.
|
|||||||
## Suggested Validation
|
## Suggested Validation
|
||||||
|
|
||||||
- `cargo test --package e2e_test`
|
- `cargo test --package e2e_test`
|
||||||
- Full gate before commit: `make pre-commit`
|
|
||||||
|
|||||||
@@ -96,7 +96,6 @@ tokio-stream = { workspace = true }
|
|||||||
rustfs-madmin.workspace = true
|
rustfs-madmin.workspace = true
|
||||||
rustfs-filemeta.workspace = true
|
rustfs-filemeta.workspace = true
|
||||||
bytes = { workspace = true, features = ["serde"] }
|
bytes = { workspace = true, features = ["serde"] }
|
||||||
serial_test = { workspace = true }
|
|
||||||
aws-sdk-s3 = { workspace = true, default-features = false, features = ["sigv4a", "default-https-client", "rt-tokio"] }
|
aws-sdk-s3 = { workspace = true, default-features = false, features = ["sigv4a", "default-https-client", "rt-tokio"] }
|
||||||
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
|
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
|
||||||
aws-config = { workspace = true }
|
aws-config = { workspace = true }
|
||||||
|
|||||||
+26
-21
@@ -48,16 +48,14 @@ cargo nextest run --profile e2e-smoke -p e2e_test
|
|||||||
cargo nextest run -j1 --run-ignored ignored-only -p rustfs-scanner -p rustfs \
|
cargo nextest run -j1 --run-ignored ignored-only -p rustfs-scanner -p rustfs \
|
||||||
-E 'binary(lifecycle_integration_test) or (package(rustfs) and test(lifecycle_transition_api_test))'
|
-E 'binary(lifecycle_integration_test) or (package(rustfs) and test(lifecycle_transition_api_test))'
|
||||||
|
|
||||||
# Protocols suite — fixed ports, MUST be single-threaded, gated by build features
|
|
||||||
RUSTFS_BUILD_FEATURES=ftps,webdav,sftp \
|
|
||||||
cargo test -p e2e_test test_protocol_core_suite -- --test-threads=1 --nocapture
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The protocols suite has its own contract (fixed bind ports 9022–9301,
|
The protocols suite has its own contract (fixed bind ports 9022–9301,
|
||||||
`--test-threads=1`, feature-gated scheduling) documented in
|
single-worker execution, feature-gated scheduling) documented in
|
||||||
[`src/protocols/README.md`](src/protocols/README.md). `RUSTFS_BUILD_FEATURES`
|
[`src/protocols/README.md`](src/protocols/README.md). `RUSTFS_BUILD_FEATURES`
|
||||||
selects which features the spawned binary is built with; leave it unset to run
|
selects which features the spawned binary is built with; leave it unset to run
|
||||||
every protocol entry.
|
every protocol entry. Use the exact profile command under
|
||||||
|
[Troubleshooting](#troubleshooting) for CI-equivalent execution.
|
||||||
|
|
||||||
### `#[ignore]` semantics
|
### `#[ignore]` semantics
|
||||||
|
|
||||||
@@ -159,27 +157,26 @@ construction (random port + isolated temp dir) and need no serialization.
|
|||||||
## CI map
|
## CI map
|
||||||
|
|
||||||
`e2e_test` is **excluded** from the main `cargo nextest run --profile ci --all`
|
`e2e_test` is **excluded** from the main `cargo nextest run --profile ci --all`
|
||||||
pass ([`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) line 158,
|
pass (`--exclude e2e_test`) — the whole crate is too slow to gate every PR.
|
||||||
`--exclude e2e_test`) — the whole crate is too slow to gate every PR. Subsets
|
Subsets join CI through nextest profiles; the fixed-port protocol suite uses
|
||||||
join CI through the nextest profile system only (never as ad-hoc jobs):
|
the same profile for membership and execution with one nightly worker.
|
||||||
|
|
||||||
| Suite | Runs where | Status |
|
| Suite | Runs where | Status |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Smoke subset (`e2e-smoke` profile) | `e2e-tests` job, every PR | **Active** (backlog#1149 ci-4) |
|
| 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` + `e2e-tests-rio-v2` jobs | **Active** (external conformance tool) |
|
||||||
| ILM / lifecycle (ignored) | `test-ilm-integration-serial` lane, `-j1` | **Active** (backlog#1148 ilm-1) |
|
| ILM / lifecycle (ignored) | `test-ilm-integration-serial` lane, `-j1` | **Active** (backlog#1148 ilm-1) |
|
||||||
| KMS suite | — | Not in CI yet (backlog#1149 ci-5) |
|
| KMS suite | `e2e-full` job, merge queue + main | **Active** |
|
||||||
| Protocols (FTPS/WebDAV/SFTP) | — | Not in CI yet (backlog#1149 ci-7) |
|
| Cluster faults (`e2e-nightly` profile) | consolidated nightly workflow | **Active** (backlog#1149 ci-7) |
|
||||||
|
| Protocols (FTPS/WebDAV/SFTP) | consolidated nightly workflow, serial | **Active** (backlog#1149 ci-7) |
|
||||||
| Replication (fast subset) | `e2e-smoke` profile, `e2e-tests` job, every PR | **Active** (backlog#1147 repl-1) |
|
| Replication (fast subset) | `e2e-smoke` profile, `e2e-tests` job, every PR | **Active** (backlog#1147 repl-1) |
|
||||||
| Replication (slow + dual-node) | `e2e-repl-nightly` profile, scheduled workflow | **Active** (backlog#1147 repl-1) |
|
| Replication (slow + multi-node) | `e2e-repl-nightly` profile, consolidated nightly workflow | **Active** (backlog#1147 repl-1) |
|
||||||
| `reliant/*` (pre-started server) | — | Manual only |
|
| `reliant/*` | 19 tests in PR smoke; remaining default tests in `e2e-full` | **Active** except `#[ignore]` |
|
||||||
|
|
||||||
Links: [`ci.yml`](../../.github/workflows/ci.yml) `e2e-tests` (line 347),
|
The profile filters in [`.config/nextest.toml`](../../.config/nextest.toml) are
|
||||||
`test-ilm-integration-serial` (line 196). The `e2e-smoke` `default-filter` in
|
the wiring source of truth. Committed test-ID digests under
|
||||||
[`.config/nextest.toml`](../../.config/nextest.toml) is the **single wiring
|
`.config/e2e-*-selection.txt` make every membership change explicit.
|
||||||
mechanism** — extend that filter (or add a sibling profile) to admit more
|
|
||||||
tests; do not add e2e jobs to `ci.yml`. repl-1 / ilm-3 are landing in parallel
|
|
||||||
and may add lanes; keep the table above easy to extend.
|
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
@@ -188,9 +185,15 @@ and may add lanes; keep the table above easy to extend.
|
|||||||
```bash
|
```bash
|
||||||
# Smoke (e2e-tests job) — includes the 20 fast replication tests
|
# Smoke (e2e-tests job) — includes the 20 fast replication tests
|
||||||
cargo nextest run --profile e2e-smoke -p e2e_test
|
cargo nextest run --profile e2e-smoke -p e2e_test
|
||||||
# Replication nightly lane (16 slow + dual-node tests; install awscurl for the
|
# Full single-node merge/main lane
|
||||||
# STS dual-node test, else it skips gracefully)
|
cargo nextest run --profile e2e-full -p e2e_test
|
||||||
|
# Cluster fault nightly lane
|
||||||
|
cargo nextest run --profile e2e-nightly -p e2e_test
|
||||||
|
# Replication nightly lane; install awscurl so STS paths do not skip
|
||||||
cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
||||||
|
# Fixed-port protocol nightly lane
|
||||||
|
RUSTFS_BUILD_FEATURES=ftps,webdav,sftp \
|
||||||
|
cargo nextest run -j 1 --profile e2e-protocols -p e2e_test --no-capture
|
||||||
# ILM serial lane
|
# ILM serial lane
|
||||||
cargo nextest run -j1 --run-ignored ignored-only -p rustfs-scanner -p rustfs \
|
cargo nextest run -j1 --run-ignored ignored-only -p rustfs-scanner -p rustfs \
|
||||||
-E 'binary(lifecycle_integration_test) or (package(rustfs) and test(lifecycle_transition_api_test))'
|
-E 'binary(lifecycle_integration_test) or (package(rustfs) and test(lifecycle_transition_api_test))'
|
||||||
@@ -273,4 +276,6 @@ current subset is.
|
|||||||
`docs/testing/e2e-suite-inventory.md` records the per-module test counts as
|
`docs/testing/e2e-suite-inventory.md` records the per-module test counts as
|
||||||
listed by `cargo nextest list -p e2e_test`. Regenerate it when adding or
|
listed by `cargo nextest list -p e2e_test`. Regenerate it when adding or
|
||||||
moving e2e tests so acceptance numbers in the test-strategy issues
|
moving e2e tests so acceptance numbers in the test-strategy issues
|
||||||
(backlog#1147–#1155) stay auditable.
|
(backlog#1147–#1155) stay auditable. When a profile membership change is
|
||||||
|
intentional, review its JSON listing before updating the matching
|
||||||
|
`.config/e2e-*-selection.txt` test-ID digest.
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ use reqwest::StatusCode;
|
|||||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||||
use rustfs_signer::sign_v4;
|
use rustfs_signer::sign_v4;
|
||||||
use s3s::Body;
|
use s3s::Body;
|
||||||
|
use serde_json;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::fs as stdfs;
|
use std::fs as stdfs;
|
||||||
use std::io::ErrorKind;
|
use std::io::ErrorKind;
|
||||||
@@ -53,7 +54,8 @@ pub(crate) const FAST_DATA_USAGE_SCANNER_ENV: &[(&str, &str)] =
|
|||||||
pub const TEST_BUCKET: &str = "e2e-test-bucket";
|
pub const TEST_BUCKET: &str = "e2e-test-bucket";
|
||||||
const RUSTFS_FULL_FEATURE: &str = "full";
|
const RUSTFS_FULL_FEATURE: &str = "full";
|
||||||
const TEST_PORT_MIN: u16 = 20_000;
|
const TEST_PORT_MIN: u16 = 20_000;
|
||||||
const TEST_PORT_RANGE: u16 = 40_000;
|
// Keep allocator ports below the ephemeral range used by bind(..., 0) test helpers.
|
||||||
|
const TEST_PORT_RANGE: u16 = 10_000;
|
||||||
const TEST_PORT_COUNTER_PATH: &str = "/tmp/rustfs_e2e_next_port";
|
const TEST_PORT_COUNTER_PATH: &str = "/tmp/rustfs_e2e_next_port";
|
||||||
const TEST_PORT_LOCK_DIR: &str = "/tmp/rustfs_e2e_port_allocator.lock";
|
const TEST_PORT_LOCK_DIR: &str = "/tmp/rustfs_e2e_port_allocator.lock";
|
||||||
const TEST_PORT_LOCK_STALE_AFTER: Duration = Duration::from_secs(30);
|
const TEST_PORT_LOCK_STALE_AFTER: Duration = Duration::from_secs(30);
|
||||||
@@ -1582,6 +1584,156 @@ impl Drop for RustFSTestClusterEnvironment {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send a SigV4-signed HTTP request and return the raw `reqwest::Response`.
|
||||||
|
///
|
||||||
|
/// Unlike [`signed_s3_request`], this variant accepts `body: Option<Vec<u8>>`
|
||||||
|
/// (binary-safe) and reorders parameters so that `access_key`/`secret_key`
|
||||||
|
/// appear before the body — matching the convention used by the replication
|
||||||
|
/// extension and object-lambda e2e suites.
|
||||||
|
pub(crate) async fn signed_request(
|
||||||
|
method: http::Method,
|
||||||
|
url: &str,
|
||||||
|
access_key: &str,
|
||||||
|
secret_key: &str,
|
||||||
|
body: Option<Vec<u8>>,
|
||||||
|
content_type: Option<&str>,
|
||||||
|
) -> Result<reqwest::Response, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let uri = url.parse::<http::Uri>()?;
|
||||||
|
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
||||||
|
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
||||||
|
request = request.header(HOST, authority);
|
||||||
|
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
||||||
|
if let Some(content_type) = content_type {
|
||||||
|
request = request.header(CONTENT_TYPE, content_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
||||||
|
let signed = sign_v4(request.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
||||||
|
|
||||||
|
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
||||||
|
let client = local_http_client();
|
||||||
|
let mut request_builder = client.request(reqwest_method, url);
|
||||||
|
for (name, value) in signed.headers() {
|
||||||
|
request_builder = request_builder.header(name, value);
|
||||||
|
}
|
||||||
|
if let Some(body) = body {
|
||||||
|
request_builder = request_builder.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(request_builder.send().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`signed_request`], but uses a caller-supplied `reqwest::Client`
|
||||||
|
/// instead of the shared [`local_http_client`].
|
||||||
|
pub(crate) async fn signed_request_with_client(
|
||||||
|
client: &reqwest::Client,
|
||||||
|
method: http::Method,
|
||||||
|
url: &str,
|
||||||
|
access_key: &str,
|
||||||
|
secret_key: &str,
|
||||||
|
body: Option<Vec<u8>>,
|
||||||
|
content_type: Option<&str>,
|
||||||
|
) -> Result<reqwest::Response, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let uri = url.parse::<http::Uri>()?;
|
||||||
|
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
||||||
|
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
||||||
|
request = request.header(HOST, authority);
|
||||||
|
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
||||||
|
if let Some(content_type) = content_type {
|
||||||
|
request = request.header(CONTENT_TYPE, content_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
||||||
|
let signed = sign_v4(request.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
||||||
|
|
||||||
|
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
||||||
|
let mut request_builder = client.request(reqwest_method, url);
|
||||||
|
for (name, value) in signed.headers() {
|
||||||
|
request_builder = request_builder.header(name, value);
|
||||||
|
}
|
||||||
|
if let Some(body) = body {
|
||||||
|
request_builder = request_builder.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(request_builder.send().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`signed_request`], but includes a `session_token` in the
|
||||||
|
/// `x-amz-security-token` header and passes it to the SigV4 signer.
|
||||||
|
pub(crate) async fn signed_request_with_session_token(
|
||||||
|
method: http::Method,
|
||||||
|
url: &str,
|
||||||
|
access_key: &str,
|
||||||
|
secret_key: &str,
|
||||||
|
session_token: &str,
|
||||||
|
body: Option<Vec<u8>>,
|
||||||
|
content_type: Option<&str>,
|
||||||
|
) -> Result<reqwest::Response, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let uri = url.parse::<http::Uri>()?;
|
||||||
|
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
||||||
|
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
||||||
|
request = request.header(HOST, authority);
|
||||||
|
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
||||||
|
if !session_token.is_empty() {
|
||||||
|
request = request.header("x-amz-security-token", session_token);
|
||||||
|
}
|
||||||
|
if let Some(content_type) = content_type {
|
||||||
|
request = request.header(CONTENT_TYPE, content_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
||||||
|
let signed = sign_v4(
|
||||||
|
request.body(Body::empty())?,
|
||||||
|
content_len,
|
||||||
|
access_key,
|
||||||
|
secret_key,
|
||||||
|
session_token,
|
||||||
|
"us-east-1",
|
||||||
|
);
|
||||||
|
|
||||||
|
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
||||||
|
let client = local_http_client();
|
||||||
|
let mut request_builder = client.request(reqwest_method, url);
|
||||||
|
for (name, value) in signed.headers() {
|
||||||
|
request_builder = request_builder.header(name, value);
|
||||||
|
}
|
||||||
|
if let Some(body) = body {
|
||||||
|
request_builder = request_builder.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(request_builder.send().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new user via the admin API.
|
||||||
|
pub(crate) async fn admin_create_user(
|
||||||
|
env: &RustFSTestEnvironment,
|
||||||
|
username: &str,
|
||||||
|
secret_key: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let url = format!("{}/rustfs/admin/v3/add-user?accessKey={}", env.url, username);
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"secretKey": secret_key,
|
||||||
|
"status": "enabled"
|
||||||
|
});
|
||||||
|
let response = signed_request(
|
||||||
|
http::Method::PUT,
|
||||||
|
&url,
|
||||||
|
&env.access_key,
|
||||||
|
&env.secret_key,
|
||||||
|
Some(body.to_string().into_bytes()),
|
||||||
|
Some("application/json"),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if response.status() != reqwest::StatusCode::OK {
|
||||||
|
let status = response.status();
|
||||||
|
let body = response.text().await.unwrap_or_default();
|
||||||
|
return Err(format!("create user failed: {status} {body}").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -55,7 +55,6 @@ mod tests {
|
|||||||
use aws_sdk_s3::Client;
|
use aws_sdk_s3::Client;
|
||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
||||||
use serial_test::serial;
|
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use tokio::time::{Duration, timeout};
|
use tokio::time::{Duration, timeout};
|
||||||
@@ -269,7 +268,6 @@ mod tests {
|
|||||||
/// stripes) and a multipart object (3 parts × 5 MiB) must GET back as a
|
/// stripes) and a multipart object (3 parts × 5 MiB) must GET back as a
|
||||||
/// full, byte-identical body with the correct Content-Length. No early EOF.
|
/// full, byte-identical body with the correct Content-Length. No early EOF.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn degraded_read_large_objects_with_one_disk_offline_return_full_body() -> TestResult {
|
async fn degraded_read_large_objects_with_one_disk_offline_return_full_body() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("dist-13 (a): large-object degraded read with one of four disks offline");
|
info!("dist-13 (a): large-object degraded read with one of four disks offline");
|
||||||
@@ -335,7 +333,6 @@ mod tests {
|
|||||||
/// mid-stream — the exact window the fixes had to reconstruct through rather
|
/// mid-stream — the exact window the fixes had to reconstruct through rather
|
||||||
/// than truncate.
|
/// than truncate.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn degraded_read_reconstructs_through_midstream_bitrot_within_quorum() -> TestResult {
|
async fn degraded_read_reconstructs_through_midstream_bitrot_within_quorum() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("dist-13 (b): mid-stream bitrot within quorum must reconstruct a full body");
|
info!("dist-13 (b): mid-stream bitrot within quorum must reconstruct a full body");
|
||||||
@@ -393,7 +390,6 @@ mod tests {
|
|||||||
/// Content-Length. `get_checked` panics on that forbidden outcome, so this
|
/// Content-Length. `get_checked` panics on that forbidden outcome, so this
|
||||||
/// test fails loudly if the truncation bug ever returns.
|
/// test fails loudly if the truncation bug ever returns.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn beyond_quorum_degraded_read_never_silently_truncates() -> TestResult {
|
async fn beyond_quorum_degraded_read_never_silently_truncates() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("dist-13 (c): beyond-quorum degraded read must fail, never 200+truncated");
|
info!("dist-13 (c): beyond-quorum degraded read must fail, never 200+truncated");
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ mod tests {
|
|||||||
use aws_sdk_s3::Client;
|
use aws_sdk_s3::Client;
|
||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
||||||
use serial_test::serial;
|
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use tokio::time::{Duration, timeout};
|
use tokio::time::{Duration, timeout};
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
@@ -129,7 +128,6 @@ mod tests {
|
|||||||
/// the body — and assert the server log names the object, at the log level a
|
/// the body — and assert the server log names the object, at the log level a
|
||||||
/// default deployment actually runs with.
|
/// default deployment actually runs with.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn midstream_get_failure_is_logged_with_the_object_at_default_log_level() -> TestResult {
|
async fn midstream_get_failure_is_logged_with_the_object_at_default_log_level() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("rustfs#4784: a mid-stream GET failure must name its object in the source log");
|
info!("rustfs#4784: a mid-stream GET failure must name its object in the source log");
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ use prost::Message;
|
|||||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||||
use rustfs_signer::sign_v4;
|
use rustfs_signer::sign_v4;
|
||||||
use s3s::Body;
|
use s3s::Body;
|
||||||
use serial_test::serial;
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
@@ -1028,20 +1027,6 @@ impl<'a> ReaderPathExpectation<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_size_bucket(
|
|
||||||
object: ReaderObject<'a>,
|
|
||||||
expected_path: &'a str,
|
|
||||||
object_class: &'a str,
|
|
||||||
expected_size_bucket: &'a str,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
object,
|
|
||||||
expected_path,
|
|
||||||
object_class,
|
|
||||||
expected_size_bucket: Some(expected_size_bucket),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_any_size_bucket(object: ReaderObject<'a>, expected_path: &'a str, object_class: &'a str) -> Self {
|
fn with_any_size_bucket(object: ReaderObject<'a>, expected_path: &'a str, object_class: &'a str) -> Self {
|
||||||
Self {
|
Self {
|
||||||
object,
|
object,
|
||||||
@@ -1709,7 +1694,6 @@ fn assert_storage_layout(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_inline_storage_and_get_boundaries() -> TestResult {
|
async fn four_node_inline_storage_and_get_boundaries() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -1781,7 +1765,6 @@ async fn four_node_inline_storage_and_get_boundaries() -> TestResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_empty_legacy_volumes_start_as_fresh() -> TestResult {
|
async fn four_node_empty_legacy_volumes_start_as_fresh() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -1819,7 +1802,6 @@ async fn four_node_empty_legacy_volumes_start_as_fresh() -> TestResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_inline_fallback_controls() -> TestResult {
|
async fn four_node_inline_fallback_controls() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -1884,7 +1866,6 @@ async fn four_node_inline_fallback_controls() -> TestResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_compressed_inline_fallback() -> TestResult {
|
async fn four_node_compressed_inline_fallback() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -1909,12 +1890,7 @@ async fn four_node_compressed_inline_fallback() -> TestResult {
|
|||||||
assert_reader_path(
|
assert_reader_path(
|
||||||
&collector,
|
&collector,
|
||||||
&client,
|
&client,
|
||||||
ReaderPathExpectation::with_size_bucket(
|
ReaderPathExpectation::for_class(ReaderObject::new(bucket, key, &body, put.e_tag(), None), LEGACY_DUPLEX, COMPRESSED),
|
||||||
ReaderObject::new(bucket, key, &body, put.e_tag(), None),
|
|
||||||
LEGACY_DUPLEX,
|
|
||||||
COMPRESSED,
|
|
||||||
size_bucket(4 * KIB),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -1924,7 +1900,6 @@ async fn four_node_compressed_inline_fallback() -> TestResult {
|
|||||||
/// Multipart disk compression is live again, so a compression-enabled cluster classifies multipart objects as compressed and the roundtrip (full GET plus partNumber GET) must still return the original bytes.
|
/// Multipart disk compression is live again, so a compression-enabled cluster classifies multipart objects as compressed and the roundtrip (full GET plus partNumber GET) must still return the original bytes.
|
||||||
/// Reverting the multipart compression fix must fail this test.
|
/// Reverting the multipart compression fix must fail this test.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_multipart_disk_compression_roundtrip() -> TestResult {
|
async fn four_node_multipart_disk_compression_roundtrip() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -1971,7 +1946,6 @@ async fn four_node_multipart_disk_compression_roundtrip() -> TestResult {
|
|||||||
/// read costs on the order of the covering part's block size against a ~5 MiB
|
/// read costs on the order of the covering part's block size against a ~5 MiB
|
||||||
/// object.
|
/// object.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_compressed_multipart_tail_range_reads_are_bounded() -> TestResult {
|
async fn four_node_compressed_multipart_tail_range_reads_are_bounded() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2038,7 +2012,6 @@ async fn four_node_compressed_multipart_tail_range_reads_are_bounded() -> TestRe
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls() -> TestResult {
|
async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2142,7 +2115,6 @@ async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls() -> Te
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_add_tier_converges() -> TestResult {
|
async fn four_node_add_tier_converges() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2161,7 +2133,6 @@ async fn four_node_add_tier_converges() -> TestResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_add_tier_converges_after_offline_node_restart_without_second_mutation() -> TestResult {
|
async fn four_node_add_tier_converges_after_offline_node_restart_without_second_mutation() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2183,7 +2154,6 @@ async fn four_node_add_tier_converges_after_offline_node_restart_without_second_
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_manual_transition_job_status_survives_node_restart() -> TestResult {
|
async fn four_node_manual_transition_job_status_survives_node_restart() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2258,7 +2228,6 @@ async fn four_node_manual_transition_job_status_survives_node_restart() -> TestR
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_manual_transition_distributed_admission_conflict_reports_status_and_backpressure() -> TestResult {
|
async fn four_node_manual_transition_distributed_admission_conflict_reports_status_and_backpressure() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2274,6 +2243,7 @@ async fn four_node_manual_transition_distributed_admission_conflict_reports_stat
|
|||||||
hot.set_env("RUSTFS_SCANNER_CYCLE", "3600");
|
hot.set_env("RUSTFS_SCANNER_CYCLE", "3600");
|
||||||
hot.set_env("RUSTFS_MAX_TRANSITION_WORKERS", "1");
|
hot.set_env("RUSTFS_MAX_TRANSITION_WORKERS", "1");
|
||||||
hot.set_env("RUSTFS_TRANSITION_QUEUE_CAPACITY", "1");
|
hot.set_env("RUSTFS_TRANSITION_QUEUE_CAPACITY", "1");
|
||||||
|
hot.set_env("RUSTFS_TRANSITION_QUEUE_SEND_TIMEOUT_MS", "1");
|
||||||
hot.start().await?;
|
hot.start().await?;
|
||||||
|
|
||||||
let hot_client = hot.create_s3_client(0)?;
|
let hot_client = hot.create_s3_client(0)?;
|
||||||
@@ -2290,7 +2260,7 @@ async fn four_node_manual_transition_distributed_admission_conflict_reports_stat
|
|||||||
.put_object()
|
.put_object()
|
||||||
.bucket(&bucket)
|
.bucket(&bucket)
|
||||||
.key(key)
|
.key(key)
|
||||||
.body(ByteStream::from(payload(64 * KIB, index)))
|
.body(ByteStream::from(payload(1024 * KIB, index)))
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
@@ -2399,7 +2369,6 @@ async fn four_node_manual_transition_distributed_admission_conflict_reports_stat
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
#[ignore = "manual #1508 evidence harness: starts a 4-node cluster, a remote tier, and an in-flight transition job"]
|
#[ignore = "manual #1508 evidence harness: starts a 4-node cluster, a remote tier, and an in-flight transition job"]
|
||||||
async fn four_node_manual_transition_rollout_non_empty_restart_readback() -> TestResult {
|
async fn four_node_manual_transition_rollout_non_empty_restart_readback() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
@@ -2504,7 +2473,6 @@ async fn four_node_manual_transition_rollout_non_empty_restart_readback() -> Tes
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls_during_transition() -> TestResult {
|
async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls_during_transition() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
@@ -2616,7 +2584,6 @@ async fn four_node_mixed_msgpack_compat_mode_preserves_fallback_controls_during_
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn four_node_transitioned_inline_fallback() -> TestResult {
|
async fn four_node_transitioned_inline_fallback() -> TestResult {
|
||||||
init_logging();
|
init_logging();
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ use std::time::Duration;
|
|||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use tokio::time::sleep;
|
use tokio::time::sleep;
|
||||||
use tracing::{debug, error, info};
|
use tracing::{debug, error, info, warn};
|
||||||
|
|
||||||
// KMS-specific constants
|
// KMS-specific constants
|
||||||
pub const TEST_BUCKET: &str = "kms-test-bucket";
|
pub const TEST_BUCKET: &str = "kms-test-bucket";
|
||||||
@@ -177,6 +177,49 @@ pub async fn get_kms_status(
|
|||||||
Ok(status)
|
Ok(status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Poll the KMS status endpoint until the backend reports ready or the timeout
|
||||||
|
/// expires. Replaces hard-coded `sleep(Duration::from_secs(3))` startup waits
|
||||||
|
/// with an active readiness probe so tests start as soon as KMS is usable
|
||||||
|
/// (typically < 1 s) instead of always waiting the full 3 s.
|
||||||
|
///
|
||||||
|
/// Uses exponential back-off starting at 200 ms (doubling each attempt, capped
|
||||||
|
/// at 1 s) up to a total wall-clock budget of 5 s.
|
||||||
|
pub async fn wait_for_kms_ready(
|
||||||
|
base_url: &str,
|
||||||
|
access_key: &str,
|
||||||
|
secret_key: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let total_deadline = Duration::from_secs(5);
|
||||||
|
let start = tokio::time::Instant::now();
|
||||||
|
let mut backoff = Duration::from_millis(200);
|
||||||
|
let max_backoff = Duration::from_secs(1);
|
||||||
|
let mut first_attempt = true;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if !first_attempt {
|
||||||
|
if start.elapsed() >= total_deadline {
|
||||||
|
return Err("KMS failed to become ready within 5 seconds".into());
|
||||||
|
}
|
||||||
|
sleep(backoff).await;
|
||||||
|
backoff = (backoff * 2).min(max_backoff);
|
||||||
|
}
|
||||||
|
first_attempt = false;
|
||||||
|
|
||||||
|
match get_kms_status(base_url, access_key, secret_key).await {
|
||||||
|
Ok(status) => {
|
||||||
|
info!("KMS is ready (status: {})", status);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if start.elapsed() >= total_deadline {
|
||||||
|
return Err(format!("KMS did not become ready within 5 s: last error: {e}").into());
|
||||||
|
}
|
||||||
|
warn!(error = %e, elapsed_ms = start.elapsed().as_millis() as u64, "KMS not ready yet, retrying…");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a default KMS key for testing and return the created key ID
|
/// Create a default KMS key for testing and return the created key ID
|
||||||
pub async fn create_default_key(
|
pub async fn create_default_key(
|
||||||
base_url: &str,
|
base_url: &str,
|
||||||
@@ -861,6 +904,13 @@ impl LocalKMSTestEnvironment {
|
|||||||
Ok(default_key_id.to_string())
|
Ok(default_key_id.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Poll the KMS status endpoint until the backend reports ready.
|
||||||
|
///
|
||||||
|
/// Prefer this over a fixed `sleep` after calling `start_rustfs_for_local_kms`.
|
||||||
|
pub async fn wait_for_kms_ready(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
wait_for_kms_ready(&self.base_env.url, &self.base_env.access_key, &self.base_env.secret_key).await
|
||||||
|
}
|
||||||
|
|
||||||
/// Configure Local KMS backend with a predefined default key
|
/// Configure Local KMS backend with a predefined default key
|
||||||
pub async fn configure_local_kms(&self) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn configure_local_kms(&self) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
// Use a fixed, predictable default key ID
|
// Use a fixed, predictable default key ID
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ use std::time::Duration;
|
|||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
|
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
|
||||||
|
type S3OperationResult<T> = Result<T, Box<aws_sdk_s3::Error>>;
|
||||||
|
|
||||||
const ALLOWED_KEY: &str = "kms-matrix-allowed-key";
|
const ALLOWED_KEY: &str = "kms-matrix-allowed-key";
|
||||||
const OTHER_KEY: &str = "kms-matrix-other-key";
|
const OTHER_KEY: &str = "kms-matrix-other-key";
|
||||||
@@ -130,7 +131,7 @@ fn policy_document(statements: Vec<serde_json::Value>) -> String {
|
|||||||
serde_json::json!({ "Version": "2012-10-17", "Statement": statements }).to_string()
|
serde_json::json!({ "Version": "2012-10-17", "Statement": statements }).to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn put_sse_kms(client: &Client, key: &str, kms_key_id: &str) -> Result<(), aws_sdk_s3::Error> {
|
async fn put_sse_kms(client: &Client, key: &str, kms_key_id: &str) -> S3OperationResult<()> {
|
||||||
client
|
client
|
||||||
.put_object()
|
.put_object()
|
||||||
.bucket(BUCKET)
|
.bucket(BUCKET)
|
||||||
@@ -141,16 +142,23 @@ async fn put_sse_kms(client: &Client, key: &str, kms_key_id: &str) -> Result<(),
|
|||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(aws_sdk_s3::Error::from)
|
.map_err(|error| Box::new(aws_sdk_s3::Error::from(error)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Assert the operation failed with `AccessDenied` rather than any other error.
|
/// Assert the operation failed with `AccessDenied` rather than any other error.
|
||||||
///
|
///
|
||||||
/// A bare `is_err` would also accept `KMSKeyDisabled` or an internal error, which
|
/// A bare `is_err` would also accept `KMSKeyDisabled` or an internal error, which
|
||||||
/// would hide both a leak of key state and an outage masquerading as a denial.
|
/// would hide both a leak of key state and an outage masquerading as a denial.
|
||||||
fn assert_access_denied<T: std::fmt::Debug>(result: Result<T, aws_sdk_s3::Error>, what: &str) {
|
fn assert_access_denied<T: std::fmt::Debug, E: std::fmt::Debug + std::borrow::Borrow<aws_sdk_s3::Error>>(
|
||||||
|
result: Result<T, E>,
|
||||||
|
what: &str,
|
||||||
|
) {
|
||||||
let error = result.expect_err(&format!("{what} must be denied"));
|
let error = result.expect_err(&format!("{what} must be denied"));
|
||||||
assert_eq!(error.code(), Some("AccessDenied"), "{what} must fail with AccessDenied: {error:?}");
|
assert_eq!(
|
||||||
|
error.borrow().code(),
|
||||||
|
Some("AccessDenied"),
|
||||||
|
"{what} must fail with AccessDenied: {error:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retry an SSE-KMS write until the identity's policy has reached the request path.
|
/// Retry an SSE-KMS write until the identity's policy has reached the request path.
|
||||||
@@ -296,7 +304,7 @@ async fn sse_kms_per_key_authorization_negative_matrix() -> TestResult {
|
|||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(aws_sdk_s3::Error::from),
|
.map_err(|err| Box::new(aws_sdk_s3::Error::from(err))),
|
||||||
"SSE-KMS read by an identity holding no kms grant",
|
"SSE-KMS read by an identity holding no kms grant",
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -310,7 +318,7 @@ async fn sse_kms_per_key_authorization_negative_matrix() -> TestResult {
|
|||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(aws_sdk_s3::Error::from),
|
.map_err(|err| Box::new(aws_sdk_s3::Error::from(err))),
|
||||||
"SSE-KMS read by an identity holding kms:GenerateDataKey but not kms:Decrypt",
|
"SSE-KMS read by an identity holding kms:GenerateDataKey but not kms:Decrypt",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@
|
|||||||
//! multipart upload behaviour.
|
//! multipart upload behaviour.
|
||||||
|
|
||||||
use crate::common::{TEST_BUCKET, init_logging};
|
use crate::common::{TEST_BUCKET, init_logging};
|
||||||
use serial_test::serial;
|
|
||||||
use tokio::time::{Duration, sleep};
|
use tokio::time::{Duration, sleep};
|
||||||
use tracing::{error, info};
|
use tracing::{error, info};
|
||||||
|
|
||||||
@@ -62,7 +61,6 @@ impl VaultKmsTestContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_vault_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_vault_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_end_to_end") {
|
if skip_if_kms_admin_tool_unavailable("test_vault_kms_end_to_end") {
|
||||||
@@ -118,7 +116,6 @@ async fn test_vault_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + S
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_vault_kms_key_isolation() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_vault_kms_key_isolation() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_isolation") {
|
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_isolation") {
|
||||||
@@ -205,7 +202,6 @@ async fn test_vault_kms_key_isolation() -> Result<(), Box<dyn std::error::Error
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_vault_kms_large_file() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_vault_kms_large_file() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_large_file") {
|
if skip_if_kms_admin_tool_unavailable("test_vault_kms_large_file") {
|
||||||
@@ -270,7 +266,6 @@ async fn test_vault_kms_large_file() -> Result<(), Box<dyn std::error::Error + S
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_vault_kms_multipart_upload() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_vault_kms_multipart_upload() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_multipart_upload") {
|
if skip_if_kms_admin_tool_unavailable("test_vault_kms_multipart_upload") {
|
||||||
@@ -301,7 +296,6 @@ async fn test_vault_kms_multipart_upload() -> Result<(), Box<dyn std::error::Err
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_vault_kms_key_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_vault_kms_key_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_operations") {
|
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_operations") {
|
||||||
|
|||||||
@@ -12,12 +12,11 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
use crate::common::{RustFSTestClusterEnvironment, RustFSTestEnvironment, init_logging, local_http_client};
|
use crate::common::{RustFSTestClusterEnvironment, RustFSTestEnvironment, init_logging, local_http_client, signed_request};
|
||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use http::header::{CONTENT_TYPE, HOST};
|
use http::header::{CONTENT_TYPE, HOST};
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
use rustfs_signer::pre_sign_v4;
|
||||||
use rustfs_signer::{pre_sign_v4, sign_v4};
|
|
||||||
use rustfs_utils::egress::ENV_OUTBOUND_ALLOW_ORIGINS;
|
use rustfs_utils::egress::ENV_OUTBOUND_ALLOW_ORIGINS;
|
||||||
use s3s::Body;
|
use s3s::Body;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -227,39 +226,6 @@ async fn presigned_get_request(
|
|||||||
Ok(local_http_client().get(signed.uri().to_string()).send().await?)
|
Ok(local_http_client().get(signed.uri().to_string()).send().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signed_request(
|
|
||||||
method: http::Method,
|
|
||||||
url: &str,
|
|
||||||
access_key: &str,
|
|
||||||
secret_key: &str,
|
|
||||||
body: Option<Vec<u8>>,
|
|
||||||
content_type: Option<&str>,
|
|
||||||
) -> Result<reqwest::Response, Box<dyn Error + Send + Sync>> {
|
|
||||||
let uri = url.parse::<http::Uri>()?;
|
|
||||||
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
|
||||||
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
|
||||||
request = request.header(HOST, authority);
|
|
||||||
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
|
||||||
if let Some(content_type) = content_type {
|
|
||||||
request = request.header(CONTENT_TYPE, content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
|
||||||
let signed = sign_v4(request.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
|
||||||
|
|
||||||
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
|
||||||
let client = local_http_client();
|
|
||||||
let mut request_builder = client.request(reqwest_method, url);
|
|
||||||
for (name, value) in signed.headers() {
|
|
||||||
request_builder = request_builder.header(name, value);
|
|
||||||
}
|
|
||||||
if let Some(body) = body {
|
|
||||||
request_builder = request_builder.body(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(request_builder.send().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn configure_webhook_target(
|
async fn configure_webhook_target(
|
||||||
env: &RustFSTestEnvironment,
|
env: &RustFSTestEnvironment,
|
||||||
target_name: &str,
|
target_name: &str,
|
||||||
|
|||||||
@@ -17,7 +17,6 @@
|
|||||||
use crate::common::{awscurl_delete, awscurl_put, init_logging};
|
use crate::common::{awscurl_delete, awscurl_put, init_logging};
|
||||||
use crate::policy::test_env::PolicyTestEnvironment;
|
use crate::policy::test_env::PolicyTestEnvironment;
|
||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use serial_test::serial;
|
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
/// Helper function to create a regular user with given credentials
|
/// Helper function to create a regular user with given credentials
|
||||||
@@ -122,7 +121,6 @@ async fn cleanup_user_and_policy(env: &PolicyTestEnvironment, username: &str, po
|
|||||||
|
|
||||||
/// Test AWS policy variables with single-value scenarios
|
/// Test AWS policy variables with single-value scenarios
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_single_value() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_single_value() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_single_value_impl().await
|
test_aws_policy_variables_single_value_impl().await
|
||||||
@@ -275,7 +273,6 @@ pub async fn test_aws_policy_variables_single_value_impl_with_env(
|
|||||||
|
|
||||||
/// Test AWS policy variables with multi-value scenarios
|
/// Test AWS policy variables with multi-value scenarios
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_multi_value() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_multi_value() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_multi_value_impl().await
|
test_aws_policy_variables_multi_value_impl().await
|
||||||
@@ -401,7 +398,6 @@ pub async fn test_aws_policy_variables_multi_value_impl_with_env(
|
|||||||
|
|
||||||
/// Test AWS policy variables with variable concatenation
|
/// Test AWS policy variables with variable concatenation
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_concatenation() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_concatenation() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_concatenation_impl().await
|
test_aws_policy_variables_concatenation_impl().await
|
||||||
@@ -491,7 +487,6 @@ pub async fn test_aws_policy_variables_concatenation_impl_with_env(
|
|||||||
|
|
||||||
/// Test AWS policy variables with nested scenarios
|
/// Test AWS policy variables with nested scenarios
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_nested() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_nested() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_nested_impl().await
|
test_aws_policy_variables_nested_impl().await
|
||||||
@@ -509,7 +504,6 @@ pub async fn test_aws_policy_variables_nested_impl() -> Result<(), Box<dyn std::
|
|||||||
|
|
||||||
/// Test AWS policy variables with STS temporary credentials
|
/// Test AWS policy variables with STS temporary credentials
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_sts() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_sts() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_sts_impl().await
|
test_aws_policy_variables_sts_impl().await
|
||||||
@@ -705,7 +699,6 @@ pub async fn test_aws_policy_variables_sts_impl_with_env(
|
|||||||
|
|
||||||
/// Test AWS policy variables with deny scenarios
|
/// Test AWS policy variables with deny scenarios
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
#[ignore = "Starts a rustfs server; enable when running full E2E"]
|
||||||
pub async fn test_aws_policy_variables_deny() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
pub async fn test_aws_policy_variables_deny() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
test_aws_policy_variables_deny_impl().await
|
test_aws_policy_variables_deny_impl().await
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
|
|
||||||
use crate::common::init_logging;
|
use crate::common::init_logging;
|
||||||
use crate::policy::test_env::PolicyTestEnvironment;
|
use crate::policy::test_env::PolicyTestEnvironment;
|
||||||
use serial_test::serial;
|
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use tokio::time::{Duration, sleep};
|
use tokio::time::{Duration, sleep};
|
||||||
use tracing::{error, info};
|
use tracing::{error, info};
|
||||||
@@ -213,7 +212,6 @@ impl PolicyTestSuite {
|
|||||||
|
|
||||||
/// Test suite
|
/// Test suite
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
#[ignore = "Connects to existing rustfs server"]
|
#[ignore = "Connects to existing rustfs server"]
|
||||||
async fn test_policy_critical_suite() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_policy_critical_suite() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let config = TestSuiteConfig {
|
let config = TestSuiteConfig {
|
||||||
|
|||||||
@@ -11,10 +11,17 @@ test process directly.
|
|||||||
|
|
||||||
## Running Tests
|
## Running Tests
|
||||||
|
|
||||||
|
Use the canonical CI-equivalent protocol command in the parent
|
||||||
|
[`e2e_test` README](../../README.md#troubleshooting).
|
||||||
|
|
||||||
|
For targeted debugging of the core suite only:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
RUSTFS_BUILD_FEATURES=ftps,webdav,sftp cargo test --package e2e_test test_protocol_core_suite -- --test-threads=1 --nocapture
|
RUSTFS_BUILD_FEATURES=ftps,webdav,sftp cargo test --package e2e_test test_protocol_core_suite -- --test-threads=1 --nocapture
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This targeted command does not cover the full `e2e-protocols` profile.
|
||||||
|
|
||||||
`RUSTFS_BUILD_FEATURES` controls which features the test rustfs binary is
|
`RUSTFS_BUILD_FEATURES` controls which features the test rustfs binary is
|
||||||
built with. When this variable is set, the protocol test runner schedules
|
built with. When this variable is set, the protocol test runner schedules
|
||||||
only entries whose protocol is present in the requested feature list. Leave
|
only entries whose protocol is present in the requested feature list. Leave
|
||||||
@@ -133,4 +140,3 @@ property without consulting any external doc.
|
|||||||
Bind ports 9023 (SFTP) and 9100 (S3). Spawns rustfs with
|
Bind ports 9023 (SFTP) and 9100 (S3). Spawns rustfs with
|
||||||
`RUSTFS_SFTP_IDLE_TIMEOUT=5`, sleeps 10 s past the timeout, then issues an
|
`RUSTFS_SFTP_IDLE_TIMEOUT=5`, sleeps 10 s past the timeout, then issues an
|
||||||
SFTP request and asserts the server has closed the session.
|
SFTP request and asserts the server has closed the session.
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ use reqwest::Client;
|
|||||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||||
use rustfs_signer::sign_v4;
|
use rustfs_signer::sign_v4;
|
||||||
use s3s::Body;
|
use s3s::Body;
|
||||||
use serial_test::serial;
|
|
||||||
use tokio::process::Command;
|
use tokio::process::Command;
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
@@ -233,6 +232,111 @@ pub async fn test_webdav_core_operations() -> Result<()> {
|
|||||||
);
|
);
|
||||||
info!("PASS: PUT file '{}' successful", filename);
|
info!("PASS: PUT file '{}' successful", filename);
|
||||||
|
|
||||||
|
// Regression for #6260: a bucket-scoped policy must be able to discover its bucket at the
|
||||||
|
// WebDAV root without the unrelated global ListAllMyBuckets permission.
|
||||||
|
let scoped_bucket = "webdav-scoped-bucket";
|
||||||
|
let scoped_file = "visible.txt";
|
||||||
|
let scoped_user = "webdav-scoped-user";
|
||||||
|
let scoped_secret = "webdav-scoped-secret";
|
||||||
|
let scoped_policy_name = "webdav-scoped-policy";
|
||||||
|
|
||||||
|
let resp = client
|
||||||
|
.request(reqwest::Method::from_bytes(b"MKCOL").unwrap(), format!("{}/{}", base_url, scoped_bucket))
|
||||||
|
.header("Authorization", &auth_header)
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
assert_eq!(resp.status().as_u16(), 201, "scoped test bucket should be created");
|
||||||
|
|
||||||
|
let resp = client
|
||||||
|
.put(format!("{}/{}/{}", base_url, scoped_bucket, scoped_file))
|
||||||
|
.header("Authorization", &auth_header)
|
||||||
|
.body("visible to the scoped principal")
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
assert_eq!(resp.status().as_u16(), 201, "scoped test object should be created");
|
||||||
|
|
||||||
|
admin_create_user(&admin_base_url, scoped_user, scoped_secret).await?;
|
||||||
|
admin_add_canned_policy(
|
||||||
|
&admin_base_url,
|
||||||
|
scoped_policy_name,
|
||||||
|
&serde_json::json!({
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{
|
||||||
|
"Effect": "Allow",
|
||||||
|
"Action": ["s3:*"],
|
||||||
|
"Resource": [
|
||||||
|
format!("arn:aws:s3:::{}", scoped_bucket),
|
||||||
|
format!("arn:aws:s3:::{}/*", scoped_bucket)
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Effect": "Deny",
|
||||||
|
"Action": ["s3:*"],
|
||||||
|
"Resource": [
|
||||||
|
format!("arn:aws:s3:::{}", scoped_bucket),
|
||||||
|
format!("arn:aws:s3:::{}/*", scoped_bucket)
|
||||||
|
],
|
||||||
|
"Condition": { "Bool": { "aws:SecureTransport": "true" } }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Effect": "Deny",
|
||||||
|
"Action": ["s3:*"],
|
||||||
|
"Resource": [
|
||||||
|
format!("arn:aws:s3:::{}", scoped_bucket),
|
||||||
|
format!("arn:aws:s3:::{}/*", scoped_bucket)
|
||||||
|
],
|
||||||
|
"Condition": { "StringEquals": { "s3:signatureversion": "AWS4-HMAC-SHA256" } }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
admin_attach_policy_to_user(&admin_base_url, scoped_policy_name, scoped_user).await?;
|
||||||
|
|
||||||
|
let scoped_auth = basic_auth_header_for(scoped_user, scoped_secret);
|
||||||
|
let resp = client
|
||||||
|
.request(reqwest::Method::from_bytes(b"PROPFIND").unwrap(), &base_url)
|
||||||
|
.header("Authorization", &scoped_auth)
|
||||||
|
.header("Depth", "1")
|
||||||
|
.header("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD")
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
assert_eq!(resp.status().as_u16(), 207, "bucket-scoped root PROPFIND should succeed");
|
||||||
|
let root_listing = resp.text().await?;
|
||||||
|
assert!(root_listing.contains(scoped_bucket), "the authorized bucket should be listed");
|
||||||
|
assert!(!root_listing.contains(bucket_name), "an unauthorized bucket must not be listed");
|
||||||
|
|
||||||
|
let resp = client
|
||||||
|
.request(
|
||||||
|
reqwest::Method::from_bytes(b"PROPFIND").unwrap(),
|
||||||
|
format!("{}/{}", base_url, scoped_bucket),
|
||||||
|
)
|
||||||
|
.header("Authorization", &scoped_auth)
|
||||||
|
.header("Depth", "1")
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
assert_eq!(resp.status().as_u16(), 207, "authorized bucket PROPFIND should succeed");
|
||||||
|
assert!(resp.text().await?.contains(scoped_file), "the authorized object should be listed");
|
||||||
|
|
||||||
|
let denied_user = "webdav-no-buckets-user";
|
||||||
|
let denied_secret = "webdav-no-buckets-secret";
|
||||||
|
admin_create_user(&admin_base_url, denied_user, denied_secret).await?;
|
||||||
|
let resp = client
|
||||||
|
.request(reqwest::Method::from_bytes(b"PROPFIND").unwrap(), &base_url)
|
||||||
|
.header("Authorization", basic_auth_header_for(denied_user, denied_secret))
|
||||||
|
.header("Depth", "1")
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
assert_eq!(
|
||||||
|
resp.status().as_u16(),
|
||||||
|
207,
|
||||||
|
"PROPFIND keeps the root resource visible when the directory listing is forbidden"
|
||||||
|
);
|
||||||
|
let denied_body = resp.text().await?;
|
||||||
|
assert!(!denied_body.contains(scoped_bucket), "a denied response must not leak the scoped bucket");
|
||||||
|
assert!(!denied_body.contains(bucket_name), "a denied response must not leak the admin bucket");
|
||||||
|
|
||||||
// Test GET (download file)
|
// Test GET (download file)
|
||||||
info!("Testing WebDAV: GET (download file '{}')", filename);
|
info!("Testing WebDAV: GET (download file '{}')", filename);
|
||||||
let resp = client
|
let resp = client
|
||||||
@@ -716,7 +820,6 @@ pub async fn test_webdav_core_operations() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_webdav_core_operations_direct() -> Result<()> {
|
async fn test_webdav_core_operations_direct() -> Result<()> {
|
||||||
test_webdav_core_operations().await
|
test_webdav_core_operations().await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,6 +169,42 @@ impl QuotaTestEnv {
|
|||||||
bucket: &str,
|
bucket: &str,
|
||||||
quota_bytes: u64,
|
quota_bytes: u64,
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
self.wait_for_quota_usage_for(bucket).await?;
|
||||||
|
|
||||||
|
let quota_path = format!("/rustfs/admin/v3/quota/{bucket}");
|
||||||
|
let quota_config = serde_json::json!({
|
||||||
|
"quota": quota_bytes,
|
||||||
|
"quota_type": "HARD"
|
||||||
|
})
|
||||||
|
.to_string();
|
||||||
|
let readiness = async {
|
||||||
|
loop {
|
||||||
|
let (status, response) = admin_request(
|
||||||
|
&self.env.url,
|
||||||
|
Method::PUT,
|
||||||
|
"a_path,
|
||||||
|
Some(quota_config.clone()),
|
||||||
|
&self.env.access_key,
|
||||||
|
&self.env.secret_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
if status.is_success() {
|
||||||
|
return Ok::<(), Box<dyn std::error::Error + Send + Sync>>(());
|
||||||
|
}
|
||||||
|
if status != StatusCode::SERVICE_UNAVAILABLE {
|
||||||
|
return Err(format!("failed to set quota for {bucket}: {status} {response}").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep(Duration::from_secs(1)).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match timeout(Duration::from_secs(30), readiness).await {
|
||||||
|
Ok(result) => result,
|
||||||
|
Err(_) => Err(format!("quota readiness did not converge for {bucket} within 30 seconds").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn wait_for_quota_usage_for(&self, bucket: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let stats_path = format!("/rustfs/admin/v3/quota-stats/{bucket}");
|
let stats_path = format!("/rustfs/admin/v3/quota-stats/{bucket}");
|
||||||
let readiness = async {
|
let readiness = async {
|
||||||
loop {
|
loop {
|
||||||
@@ -181,28 +217,12 @@ impl QuotaTestEnv {
|
|||||||
if status != StatusCode::SERVICE_UNAVAILABLE {
|
if status != StatusCode::SERVICE_UNAVAILABLE {
|
||||||
return Err(format!("quota usage readiness failed for {bucket}: {status} {response}").into());
|
return Err(format!("quota usage readiness failed for {bucket}: {status} {response}").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
sleep(Duration::from_secs(1)).await;
|
sleep(Duration::from_secs(1)).await;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
match timeout(Duration::from_secs(30), readiness).await {
|
match timeout(Duration::from_secs(30), readiness).await {
|
||||||
Ok(result) => result?,
|
Ok(result) => result,
|
||||||
Err(_) => {
|
Err(_) => Err(format!("quota usage did not become authoritative for {bucket} within 30 seconds").into()),
|
||||||
return Err(format!("quota usage did not become authoritative for {bucket} within 30 seconds").into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = format!("{}/rustfs/admin/v3/quota/{}", self.env.url, bucket);
|
|
||||||
let quota_config = serde_json::json!({
|
|
||||||
"quota": quota_bytes,
|
|
||||||
"quota_type": "HARD"
|
|
||||||
});
|
|
||||||
|
|
||||||
let response = awscurl_put(&url, "a_config.to_string(), &self.env.access_key, &self.env.secret_key).await?;
|
|
||||||
if response.contains("error") {
|
|
||||||
Err(format!("Failed to set quota: {}", response).into())
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -614,6 +634,7 @@ mod integration_tests {
|
|||||||
let env = QuotaTestEnv::new().await?;
|
let env = QuotaTestEnv::new().await?;
|
||||||
|
|
||||||
env.create_bucket().await?;
|
env.create_bucket().await?;
|
||||||
|
env.wait_for_quota_usage_for(&env.bucket_name).await?;
|
||||||
|
|
||||||
// Test 1: GET quota for bucket without quota config
|
// Test 1: GET quota for bucket without quota config
|
||||||
let url = format!("{}/rustfs/admin/v3/quota/{}", env.env.url, env.bucket_name);
|
let url = format!("{}/rustfs/admin/v3/quota/{}", env.env.url, env.bucket_name);
|
||||||
@@ -621,12 +642,7 @@ mod integration_tests {
|
|||||||
assert!(response.contains("quota") && response.contains("null"));
|
assert!(response.contains("quota") && response.contains("null"));
|
||||||
|
|
||||||
// Test 2: PUT quota - valid config
|
// Test 2: PUT quota - valid config
|
||||||
let quota_config = serde_json::json!({
|
env.set_bucket_quota(1048576).await?;
|
||||||
"quota": 1048576,
|
|
||||||
"quota_type": "HARD"
|
|
||||||
});
|
|
||||||
let response = awscurl_put(&url, "a_config.to_string(), &env.env.access_key, &env.env.secret_key).await?;
|
|
||||||
assert!(response.contains("success") || !response.contains("error"));
|
|
||||||
|
|
||||||
// Test 3: GET quota after setting
|
// Test 3: GET quota after setting
|
||||||
let response = awscurl_get(&url, &env.env.access_key, &env.env.secret_key).await?;
|
let response = awscurl_get(&url, &env.env.access_key, &env.env.secret_key).await?;
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ mod tests {
|
|||||||
use aws_sdk_s3::Client;
|
use aws_sdk_s3::Client;
|
||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
|
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
|
||||||
use serial_test::serial;
|
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
@@ -157,7 +156,6 @@ mod tests {
|
|||||||
/// content, degraded writes must succeed, and everything must still
|
/// content, degraded writes must succeed, and everything must still
|
||||||
/// verify after the disk returns.
|
/// verify after the disk returns.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_degraded_read_write_with_one_disk_offline() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_degraded_read_write_with_one_disk_offline() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("Reliability: degraded read/write with one of four disks offline");
|
info!("Reliability: degraded read/write with one of four disks offline");
|
||||||
@@ -210,7 +208,6 @@ mod tests {
|
|||||||
/// bytes to a reader: per-shard bitrot checksums reject the bad shard and
|
/// bytes to a reader: per-shard bitrot checksums reject the bad shard and
|
||||||
/// the object is reconstructed from the remaining shards.
|
/// the object is reconstructed from the remaining shards.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_bitrot_corrupted_shard_read_returns_correct_data() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_bitrot_corrupted_shard_read_returns_correct_data() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("Reliability: GET must read through a bitrot-corrupted shard");
|
info!("Reliability: GET must read through a bitrot-corrupted shard");
|
||||||
@@ -253,7 +250,6 @@ mod tests {
|
|||||||
/// heal, and require the replaced disk to be rebuilt and all content to
|
/// heal, and require the replaced disk to be rebuilt and all content to
|
||||||
/// verify against the sha256 manifest.
|
/// verify against the sha256 manifest.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_fresh_disk_replacement_heals_after_sigkill_restart() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn test_fresh_disk_replacement_heals_after_sigkill_restart() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("Reliability: fresh-disk replacement heals after SIGKILL restart");
|
info!("Reliability: fresh-disk replacement heals after SIGKILL restart");
|
||||||
@@ -327,7 +323,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[serial]
|
|
||||||
async fn test_versioned_shard_census_selects_each_version_data_dir() -> Result<(), Box<dyn Error + Send + Sync>> {
|
async fn test_versioned_shard_census_selects_each_version_data_dir() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
init_logging();
|
init_logging();
|
||||||
info!("Reliability: physical shard census selects the requested object version");
|
info!("Reliability: physical shard census selects the requested object version");
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ const USER_META_KEY: &str = "ilm7-origin";
|
|||||||
const USER_META_VAL: &str = "hermetic-transition";
|
const USER_META_VAL: &str = "hermetic-transition";
|
||||||
const HDR_SOURCE_REPLICATION_REQUEST: &str = "x-rustfs-source-replication-request";
|
const HDR_SOURCE_REPLICATION_REQUEST: &str = "x-rustfs-source-replication-request";
|
||||||
const HDR_SOURCE_MTIME: &str = "x-rustfs-source-mtime";
|
const HDR_SOURCE_MTIME: &str = "x-rustfs-source-mtime";
|
||||||
|
const TIER_MUTATION_RECOVERY_CHANGED: &str = "Remote tier mutation recovery changed before publish";
|
||||||
|
|
||||||
/// 5 MiB — the S3 minimum size for a non-final multipart part; the object's only
|
/// 5 MiB — the S3 minimum size for a non-final multipart part; the object's only
|
||||||
/// internal part boundary sits at this offset.
|
/// internal part boundary sits at this offset.
|
||||||
@@ -183,19 +184,39 @@ async fn add_rustfs_tier(hot: &RustFSTestEnvironment, cold: &RustFSTestEnvironme
|
|||||||
})
|
})
|
||||||
.to_string();
|
.to_string();
|
||||||
|
|
||||||
let (status, resp) = signed_admin_request(
|
let verify_path = format!("/rustfs/admin/v3/tier/{TIER_NAME}");
|
||||||
&hot.url,
|
let deadline = Instant::now() + StdDuration::from_secs(30);
|
||||||
Method::PUT,
|
let mut recovery_changed = false;
|
||||||
"/rustfs/admin/v3/tier",
|
loop {
|
||||||
Some(&body),
|
if recovery_changed {
|
||||||
&hot.access_key,
|
let (status, _) =
|
||||||
&hot.secret_key,
|
signed_admin_request(&hot.url, Method::GET, &verify_path, None, &hot.access_key, &hot.secret_key).await?;
|
||||||
)
|
if status.is_success() {
|
||||||
.await?;
|
return Ok(());
|
||||||
if !status.is_success() {
|
}
|
||||||
return Err(format!("AddTier(RustFS) failed: status={status}, body={resp}").into());
|
}
|
||||||
|
let (status, resp) = signed_admin_request(
|
||||||
|
&hot.url,
|
||||||
|
Method::PUT,
|
||||||
|
"/rustfs/admin/v3/tier",
|
||||||
|
Some(&body),
|
||||||
|
&hot.access_key,
|
||||||
|
&hot.secret_key,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
if status.is_success() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if resp.contains(TIER_MUTATION_RECOVERY_CHANGED) {
|
||||||
|
recovery_changed = true;
|
||||||
|
} else if !recovery_changed || !resp.contains("TierNameAlreadyExist") {
|
||||||
|
return Err(format!("AddTier(RustFS) failed: status={status}, body={resp}").into());
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
return Err(format!("AddTier(RustFS) failed: status={status}, body={resp}").into());
|
||||||
|
}
|
||||||
|
tokio::time::sleep(StdDuration::from_millis(100)).await;
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn remove_rustfs_tier_force(hot: &RustFSTestEnvironment) -> TestResult {
|
async fn remove_rustfs_tier_force(hot: &RustFSTestEnvironment) -> TestResult {
|
||||||
@@ -207,10 +228,12 @@ async fn remove_rustfs_tier_force(hot: &RustFSTestEnvironment) -> TestResult {
|
|||||||
if status.is_success() {
|
if status.is_success() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if !resp.contains("TierNameBackendInUse") || Instant::now() >= deadline {
|
if (!resp.contains("TierNameBackendInUse") && !resp.contains(TIER_MUTATION_RECOVERY_CHANGED))
|
||||||
|
|| Instant::now() >= deadline
|
||||||
|
{
|
||||||
return Err(format!("RemoveTier(RustFS) failed: status={status}, body={resp}").into());
|
return Err(format!("RemoveTier(RustFS) failed: status={status}, body={resp}").into());
|
||||||
}
|
}
|
||||||
// AddTier cleanup is asynchronous; wait until its committed mutation fence clears.
|
// Tier mutation cleanup and startup recovery are asynchronous.
|
||||||
tokio::time::sleep(StdDuration::from_millis(100)).await;
|
tokio::time::sleep(StdDuration::from_millis(100)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ mod tests {
|
|||||||
use aws_sdk_s3::primitives::ByteStream;
|
use aws_sdk_s3::primitives::ByteStream;
|
||||||
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
|
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
|
||||||
use http::Method;
|
use http::Method;
|
||||||
use serial_test::serial;
|
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
@@ -1061,7 +1060,6 @@ mod tests {
|
|||||||
/// Linux mount namespaces are per-thread; keep mount setup and process
|
/// Linux mount namespaces are per-thread; keep mount setup and process
|
||||||
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
|
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
|
||||||
#[tokio::test(flavor = "current_thread")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "requires Linux root/CAP_SYS_ADMIN and RUSTFS_PRIVILEGED_REPLACEMENT_E2E=1"]
|
#[ignore = "requires Linux root/CAP_SYS_ADMIN and RUSTFS_PRIVILEGED_REPLACEMENT_E2E=1"]
|
||||||
async fn test_privileged_3x4_auto_replacement_rebuilds_ec8_plus_4_without_admin_heal()
|
async fn test_privileged_3x4_auto_replacement_rebuilds_ec8_plus_4_without_admin_heal()
|
||||||
-> Result<(), Box<dyn Error + Send + Sync>> {
|
-> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
@@ -1075,7 +1073,6 @@ mod tests {
|
|||||||
/// Linux mount namespaces are per-thread; keep mount setup and process
|
/// Linux mount namespaces are per-thread; keep mount setup and process
|
||||||
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
|
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
|
||||||
#[tokio::test(flavor = "current_thread")]
|
#[tokio::test(flavor = "current_thread")]
|
||||||
#[serial]
|
|
||||||
#[ignore = "requires Linux root/CAP_SYS_ADMIN and RUSTFS_PRIVILEGED_REPLACEMENT_E2E=1"]
|
#[ignore = "requires Linux root/CAP_SYS_ADMIN and RUSTFS_PRIVILEGED_REPLACEMENT_E2E=1"]
|
||||||
async fn test_privileged_3x4_auto_replacement_rebuilds_ec6_plus_6_without_admin_heal()
|
async fn test_privileged_3x4_auto_replacement_rebuilds_ec6_plus_6_without_admin_heal()
|
||||||
-> Result<(), Box<dyn Error + Send + Sync>> {
|
-> Result<(), Box<dyn Error + Send + Sync>> {
|
||||||
|
|||||||
@@ -13,8 +13,9 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
use crate::common::{
|
use crate::common::{
|
||||||
RustFSTestEnvironment, awscurl_available, awscurl_post_sts_form_urlencoded, init_logging, local_http_client,
|
RustFSTestEnvironment, admin_create_user, awscurl_available, awscurl_post_sts_form_urlencoded, init_logging,
|
||||||
replication_fast_env, rustfs_binary_path,
|
local_http_client, replication_fast_env, rustfs_binary_path, signed_request, signed_request_with_client,
|
||||||
|
signed_request_with_session_token,
|
||||||
};
|
};
|
||||||
use crate::fake_s3_target::{
|
use crate::fake_s3_target::{
|
||||||
FAKE_ACCESS_KEY, FAKE_SECRET_KEY, FakeS3Target, FaultAction as FakeTargetFault, Operation as FakeTargetOperation,
|
FAKE_ACCESS_KEY, FAKE_SECRET_KEY, FakeS3Target, FaultAction as FakeTargetFault, Operation as FakeTargetOperation,
|
||||||
@@ -35,7 +36,7 @@ use base64::{Engine, engine::general_purpose::STANDARD as BASE64_STANDARD};
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
use futures::{Stream, StreamExt};
|
use futures::{Stream, StreamExt};
|
||||||
use http::header::{CONTENT_ENCODING, CONTENT_TYPE, HOST};
|
use http::header::CONTENT_ENCODING;
|
||||||
use http_body_util::{BodyExt, Full};
|
use http_body_util::{BodyExt, Full};
|
||||||
use hyper::body::Incoming;
|
use hyper::body::Incoming;
|
||||||
use hyper::server::conn::http1;
|
use hyper::server::conn::http1;
|
||||||
@@ -56,9 +57,6 @@ use rustfs_madmin::{
|
|||||||
AddServiceAccountReq, ListServiceAccountsResp, PeerInfo, PeerSite, ReplicateAddStatus, ReplicateEditStatus,
|
AddServiceAccountReq, ListServiceAccountsResp, PeerInfo, PeerSite, ReplicateAddStatus, ReplicateEditStatus,
|
||||||
ReplicateRemoveStatus, SRRemoveReq, SRResyncOpStatus, SRStatusInfo, SiteReplicationInfo, SyncStatus,
|
ReplicateRemoveStatus, SRRemoveReq, SRResyncOpStatus, SRStatusInfo, SiteReplicationInfo, SyncStatus,
|
||||||
};
|
};
|
||||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
|
||||||
use rustfs_signer::sign_v4;
|
|
||||||
use s3s::Body;
|
|
||||||
use s3s::header::X_AMZ_REPLICATION_STATUS;
|
use s3s::header::X_AMZ_REPLICATION_STATUS;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
@@ -387,116 +385,6 @@ struct ReplicationResetStatusTarget {
|
|||||||
object: String,
|
object: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signed_request(
|
|
||||||
method: http::Method,
|
|
||||||
url: &str,
|
|
||||||
access_key: &str,
|
|
||||||
secret_key: &str,
|
|
||||||
body: Option<Vec<u8>>,
|
|
||||||
content_type: Option<&str>,
|
|
||||||
) -> Result<reqwest::Response, Box<dyn Error + Send + Sync>> {
|
|
||||||
let uri = url.parse::<http::Uri>()?;
|
|
||||||
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
|
||||||
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
|
||||||
request = request.header(HOST, authority);
|
|
||||||
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
|
||||||
if let Some(content_type) = content_type {
|
|
||||||
request = request.header(CONTENT_TYPE, content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
|
||||||
let signed = sign_v4(request.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
|
||||||
|
|
||||||
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
|
||||||
let client = local_http_client();
|
|
||||||
let mut request_builder = client.request(reqwest_method, url);
|
|
||||||
for (name, value) in signed.headers() {
|
|
||||||
request_builder = request_builder.header(name, value);
|
|
||||||
}
|
|
||||||
if let Some(body) = body {
|
|
||||||
request_builder = request_builder.body(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(request_builder.send().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn signed_request_with_client(
|
|
||||||
client: &reqwest::Client,
|
|
||||||
method: http::Method,
|
|
||||||
url: &str,
|
|
||||||
access_key: &str,
|
|
||||||
secret_key: &str,
|
|
||||||
body: Option<Vec<u8>>,
|
|
||||||
content_type: Option<&str>,
|
|
||||||
) -> Result<reqwest::Response, Box<dyn Error + Send + Sync>> {
|
|
||||||
let uri = url.parse::<http::Uri>()?;
|
|
||||||
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
|
||||||
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
|
||||||
request = request.header(HOST, authority);
|
|
||||||
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
|
||||||
if let Some(content_type) = content_type {
|
|
||||||
request = request.header(CONTENT_TYPE, content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
|
||||||
let signed = sign_v4(request.body(Body::empty())?, content_len, access_key, secret_key, "", "us-east-1");
|
|
||||||
|
|
||||||
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
|
||||||
let mut request_builder = client.request(reqwest_method, url);
|
|
||||||
for (name, value) in signed.headers() {
|
|
||||||
request_builder = request_builder.header(name, value);
|
|
||||||
}
|
|
||||||
if let Some(body) = body {
|
|
||||||
request_builder = request_builder.body(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(request_builder.send().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn signed_request_with_session_token(
|
|
||||||
method: http::Method,
|
|
||||||
url: &str,
|
|
||||||
access_key: &str,
|
|
||||||
secret_key: &str,
|
|
||||||
session_token: &str,
|
|
||||||
body: Option<Vec<u8>>,
|
|
||||||
content_type: Option<&str>,
|
|
||||||
) -> Result<reqwest::Response, Box<dyn Error + Send + Sync>> {
|
|
||||||
let uri = url.parse::<http::Uri>()?;
|
|
||||||
let authority = uri.authority().ok_or("request URL missing authority")?.to_string();
|
|
||||||
let mut request = http::Request::builder().method(method.clone()).uri(uri);
|
|
||||||
request = request.header(HOST, authority);
|
|
||||||
request = request.header("x-amz-content-sha256", UNSIGNED_PAYLOAD);
|
|
||||||
if !session_token.is_empty() {
|
|
||||||
request = request.header("x-amz-security-token", session_token);
|
|
||||||
}
|
|
||||||
if let Some(content_type) = content_type {
|
|
||||||
request = request.header(CONTENT_TYPE, content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
let content_len = body.as_ref().map(|body| body.len() as i64).unwrap_or_default();
|
|
||||||
let signed = sign_v4(
|
|
||||||
request.body(Body::empty())?,
|
|
||||||
content_len,
|
|
||||||
access_key,
|
|
||||||
secret_key,
|
|
||||||
session_token,
|
|
||||||
"us-east-1",
|
|
||||||
);
|
|
||||||
|
|
||||||
let reqwest_method = reqwest::Method::from_bytes(method.as_str().as_bytes())?;
|
|
||||||
let client = local_http_client();
|
|
||||||
let mut request_builder = client.request(reqwest_method, url);
|
|
||||||
for (name, value) in signed.headers() {
|
|
||||||
request_builder = request_builder.header(name, value);
|
|
||||||
}
|
|
||||||
if let Some(body) = body {
|
|
||||||
request_builder = request_builder.body(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(request_builder.send().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_xml_tag(xml: &str, tag: &str) -> Option<String> {
|
fn extract_xml_tag(xml: &str, tag: &str) -> Option<String> {
|
||||||
let open = format!("<{tag}>");
|
let open = format!("<{tag}>");
|
||||||
let close = format!("</{tag}>");
|
let close = format!("</{tag}>");
|
||||||
@@ -1016,35 +904,6 @@ fn create_user_s3_client(env: &RustFSTestEnvironment, access_key: &str, secret_k
|
|||||||
Client::from_conf(config)
|
Client::from_conf(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn admin_create_user(
|
|
||||||
env: &RustFSTestEnvironment,
|
|
||||||
username: &str,
|
|
||||||
secret_key: &str,
|
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync>> {
|
|
||||||
let url = format!("{}/rustfs/admin/v3/add-user?accessKey={}", env.url, username);
|
|
||||||
let body = serde_json::json!({
|
|
||||||
"secretKey": secret_key,
|
|
||||||
"status": "enabled"
|
|
||||||
});
|
|
||||||
let response = signed_request(
|
|
||||||
http::Method::PUT,
|
|
||||||
&url,
|
|
||||||
&env.access_key,
|
|
||||||
&env.secret_key,
|
|
||||||
Some(body.to_string().into_bytes()),
|
|
||||||
Some("application/json"),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if response.status() != StatusCode::OK {
|
|
||||||
let status = response.status();
|
|
||||||
let body = response.text().await.unwrap_or_default();
|
|
||||||
return Err(format!("create user failed: {status} {body}").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn admin_add_canned_policy(
|
async fn admin_add_canned_policy(
|
||||||
env: &RustFSTestEnvironment,
|
env: &RustFSTestEnvironment,
|
||||||
policy_name: &str,
|
policy_name: &str,
|
||||||
|
|||||||
@@ -49,4 +49,3 @@ Applies to `crates/ecstore/`.
|
|||||||
## Suggested Validation
|
## Suggested Validation
|
||||||
|
|
||||||
- `cargo test -p rustfs-ecstore`
|
- `cargo test -p rustfs-ecstore`
|
||||||
- Full gate before commit: `make pre-commit`
|
|
||||||
|
|||||||
@@ -90,6 +90,12 @@ use uuid::Uuid;
|
|||||||
const MAX_CONCURRENT_TARGET_HEALTH_CHECKS: usize = 16;
|
const MAX_CONCURRENT_TARGET_HEALTH_CHECKS: usize = 16;
|
||||||
const REDACTED_CREDENTIAL: &str = "<redacted>";
|
const REDACTED_CREDENTIAL: &str = "<redacted>";
|
||||||
|
|
||||||
|
pub type HeadObjectSdkError = Box<SdkError<HeadObjectError>>;
|
||||||
|
pub type GetObjectSdkError = Box<SdkError<GetObjectError>>;
|
||||||
|
pub type GetObjectTaggingSdkError = Box<SdkError<GetObjectTaggingError>>;
|
||||||
|
pub type PutObjectTaggingSdkError = Box<SdkError<PutObjectTaggingError>>;
|
||||||
|
pub type DeleteObjectTaggingSdkError = Box<SdkError<DeleteObjectTaggingError>>;
|
||||||
|
|
||||||
pub static GLOBAL_BUCKET_TARGET_SYS: OnceLock<BucketTargetSys> = OnceLock::new();
|
pub static GLOBAL_BUCKET_TARGET_SYS: OnceLock<BucketTargetSys> = OnceLock::new();
|
||||||
|
|
||||||
fn replication_target_versioning_enabled(versioning: Option<&BucketVersioningStatus>) -> bool {
|
fn replication_target_versioning_enabled(versioning: Option<&BucketVersioningStatus>) -> bool {
|
||||||
@@ -860,7 +866,7 @@ impl BucketTargetSys {
|
|||||||
return Some(cli);
|
return Some(cli);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: spawn a task to reload the target
|
// TODO(backlog): spawn an async task to proactively reload the replication target
|
||||||
if self.is_reloading_target(bucket, arn).await {
|
if self.is_reloading_target(bucket, arn).await {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -1968,7 +1974,7 @@ impl TargetClient {
|
|||||||
bucket: &str,
|
bucket: &str,
|
||||||
object: &str,
|
object: &str,
|
||||||
version_id: Option<String>,
|
version_id: Option<String>,
|
||||||
) -> Result<HeadObjectOutput, SdkError<HeadObjectError>> {
|
) -> Result<HeadObjectOutput, HeadObjectSdkError> {
|
||||||
// Announce the replication check so a RustFS target returns SSE-C
|
// Announce the replication check so a RustFS target returns SSE-C
|
||||||
// object metadata (etag/size) without the customer key the replication
|
// object metadata (etag/size) without the customer key the replication
|
||||||
// worker cannot hold; otherwise SSE-C replicas never converge on HEAD.
|
// worker cannot hold; otherwise SSE-C replicas never converge on HEAD.
|
||||||
@@ -1981,8 +1987,7 @@ impl TargetClient {
|
|||||||
// object with an identical ETag, and the worker concludes the object
|
// object with an identical ETag, and the worker concludes the object
|
||||||
// already converged — so it never actually replicates it.
|
// already converged — so it never actually replicates it.
|
||||||
insert_header(&mut headers, SUFFIX_SOURCE_PROXY_REQUEST, "false");
|
insert_header(&mut headers, SUFFIX_SOURCE_PROXY_REQUEST, "false");
|
||||||
match self
|
self.client
|
||||||
.client
|
|
||||||
.head_object()
|
.head_object()
|
||||||
.bucket(bucket)
|
.bucket(bucket)
|
||||||
.key(object)
|
.key(object)
|
||||||
@@ -1999,10 +2004,7 @@ impl TargetClient {
|
|||||||
})
|
})
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
{
|
.map_err(Box::new)
|
||||||
Ok(res) => Ok(res),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// HEAD used by the read-proxy path (GET/HEAD of an object not yet
|
/// HEAD used by the read-proxy path (GET/HEAD of an object not yet
|
||||||
@@ -2023,7 +2025,7 @@ impl TargetClient {
|
|||||||
range: Option<String>,
|
range: Option<String>,
|
||||||
part_number: Option<i32>,
|
part_number: Option<i32>,
|
||||||
extra_headers: HeaderMap,
|
extra_headers: HeaderMap,
|
||||||
) -> Result<HeadObjectOutput, SdkError<HeadObjectError>> {
|
) -> Result<HeadObjectOutput, HeadObjectSdkError> {
|
||||||
let headers = proxy_outbound_headers(extra_headers);
|
let headers = proxy_outbound_headers(extra_headers);
|
||||||
self.client
|
self.client
|
||||||
.head_object()
|
.head_object()
|
||||||
@@ -2036,6 +2038,7 @@ impl TargetClient {
|
|||||||
.map_request(move |req| apply_extra_headers(req, &headers))
|
.map_request(move |req| apply_extra_headers(req, &headers))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
.map_err(Box::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET used by the read-proxy path (MinIO `proxyGetToReplicationTarget`).
|
/// GET used by the read-proxy path (MinIO `proxyGetToReplicationTarget`).
|
||||||
@@ -2051,7 +2054,7 @@ impl TargetClient {
|
|||||||
range: Option<String>,
|
range: Option<String>,
|
||||||
part_number: Option<i32>,
|
part_number: Option<i32>,
|
||||||
extra_headers: HeaderMap,
|
extra_headers: HeaderMap,
|
||||||
) -> Result<GetObjectOutput, SdkError<GetObjectError>> {
|
) -> Result<GetObjectOutput, GetObjectSdkError> {
|
||||||
let headers = proxy_outbound_headers(extra_headers);
|
let headers = proxy_outbound_headers(extra_headers);
|
||||||
self.client
|
self.client
|
||||||
.get_object()
|
.get_object()
|
||||||
@@ -2064,6 +2067,7 @@ impl TargetClient {
|
|||||||
.map_request(move |req| apply_extra_headers(req, &headers))
|
.map_request(move |req| apply_extra_headers(req, &headers))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
.map_err(Box::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GetObjectTagging for the tagging read-proxy path
|
/// GetObjectTagging for the tagging read-proxy path
|
||||||
@@ -2073,7 +2077,7 @@ impl TargetClient {
|
|||||||
bucket: &str,
|
bucket: &str,
|
||||||
object: &str,
|
object: &str,
|
||||||
version_id: Option<String>,
|
version_id: Option<String>,
|
||||||
) -> Result<GetObjectTaggingOutput, SdkError<GetObjectTaggingError>> {
|
) -> Result<GetObjectTaggingOutput, GetObjectTaggingSdkError> {
|
||||||
let headers = proxy_outbound_headers(HeaderMap::new());
|
let headers = proxy_outbound_headers(HeaderMap::new());
|
||||||
self.client
|
self.client
|
||||||
.get_object_tagging()
|
.get_object_tagging()
|
||||||
@@ -2084,6 +2088,7 @@ impl TargetClient {
|
|||||||
.map_request(move |req| apply_extra_headers(req, &headers))
|
.map_request(move |req| apply_extra_headers(req, &headers))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
.map_err(Box::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PutObjectTagging for the tagging proxy path
|
/// PutObjectTagging for the tagging proxy path
|
||||||
@@ -2094,7 +2099,7 @@ impl TargetClient {
|
|||||||
object: &str,
|
object: &str,
|
||||||
version_id: Option<String>,
|
version_id: Option<String>,
|
||||||
tagging: SdkTagging,
|
tagging: SdkTagging,
|
||||||
) -> Result<PutObjectTaggingOutput, SdkError<PutObjectTaggingError>> {
|
) -> Result<PutObjectTaggingOutput, PutObjectTaggingSdkError> {
|
||||||
let headers = proxy_outbound_headers(HeaderMap::new());
|
let headers = proxy_outbound_headers(HeaderMap::new());
|
||||||
self.client
|
self.client
|
||||||
.put_object_tagging()
|
.put_object_tagging()
|
||||||
@@ -2106,6 +2111,7 @@ impl TargetClient {
|
|||||||
.map_request(move |req| apply_extra_headers(req, &headers))
|
.map_request(move |req| apply_extra_headers(req, &headers))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
.map_err(Box::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// DeleteObjectTagging for the tagging proxy path
|
/// DeleteObjectTagging for the tagging proxy path
|
||||||
@@ -2115,7 +2121,7 @@ impl TargetClient {
|
|||||||
bucket: &str,
|
bucket: &str,
|
||||||
object: &str,
|
object: &str,
|
||||||
version_id: Option<String>,
|
version_id: Option<String>,
|
||||||
) -> Result<DeleteObjectTaggingOutput, SdkError<DeleteObjectTaggingError>> {
|
) -> Result<DeleteObjectTaggingOutput, DeleteObjectTaggingSdkError> {
|
||||||
let headers = proxy_outbound_headers(HeaderMap::new());
|
let headers = proxy_outbound_headers(HeaderMap::new());
|
||||||
self.client
|
self.client
|
||||||
.delete_object_tagging()
|
.delete_object_tagging()
|
||||||
@@ -2126,6 +2132,7 @@ impl TargetClient {
|
|||||||
.map_request(move |req| apply_extra_headers(req, &headers))
|
.map_request(move |req| apply_extra_headers(req, &headers))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
|
.map_err(Box::new)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// On success returns the version id the target assigned (from
|
/// On success returns the version id the target assigned (from
|
||||||
|
|||||||
@@ -2180,7 +2180,7 @@ pub async fn recover_manual_transition_jobs_once(
|
|||||||
if limit == 0 {
|
if limit == 0 {
|
||||||
return Err(Error::other("manual transition job recovery limit must be greater than zero"));
|
return Err(Error::other("manual transition job recovery limit must be greater than zero"));
|
||||||
}
|
}
|
||||||
let list_limit = i32::try_from(limit).map_or(i32::MAX, |value| value);
|
let list_limit = i32::try_from(limit).unwrap_or(i32::MAX);
|
||||||
let page = api
|
let page = api
|
||||||
.clone()
|
.clone()
|
||||||
.list_objects_v2(
|
.list_objects_v2(
|
||||||
@@ -2386,7 +2386,7 @@ async fn replay_manual_transition_pending_tasks(
|
|||||||
version_id: task.version_id,
|
version_id: task.version_id,
|
||||||
etag: task.etag,
|
etag: task.etag,
|
||||||
mod_time,
|
mod_time,
|
||||||
size: task.size.map_or(0, |size| size),
|
size: task.size.unwrap_or(0),
|
||||||
is_latest: task.is_latest.unwrap_or(false),
|
is_latest: task.is_latest.unwrap_or(false),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1016,7 +1016,7 @@ pub async fn recover_transition_transaction_records(
|
|||||||
return Err(Error::other("transition transaction recovery limit must be greater than zero"));
|
return Err(Error::other("transition transaction recovery limit must be greater than zero"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let list_limit = i32::try_from(limit).map_or(i32::MAX, |value| value);
|
let list_limit = i32::try_from(limit).unwrap_or(i32::MAX);
|
||||||
let list = api
|
let list = api
|
||||||
.clone()
|
.clone()
|
||||||
.list_objects_v2(
|
.list_objects_v2(
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ const IAM_FORMAT_FILE_PATH: &str = "config/iam/format.json";
|
|||||||
const IAM_USERS_PREFIX: &str = "config/iam/users/";
|
const IAM_USERS_PREFIX: &str = "config/iam/users/";
|
||||||
const IAM_SERVICE_ACCOUNTS_PREFIX: &str = "config/iam/service-accounts/";
|
const IAM_SERVICE_ACCOUNTS_PREFIX: &str = "config/iam/service-accounts/";
|
||||||
const IAM_STS_PREFIX: &str = "config/iam/sts/";
|
const IAM_STS_PREFIX: &str = "config/iam/sts/";
|
||||||
|
const MINIO_GO_ZERO_TIME: OffsetDateTime = time::macros::datetime!(0001-01-01 00:00 UTC);
|
||||||
const IAM_GROUPS_PREFIX: &str = "config/iam/groups/";
|
const IAM_GROUPS_PREFIX: &str = "config/iam/groups/";
|
||||||
const IAM_POLICIES_PREFIX: &str = "config/iam/policies/";
|
const IAM_POLICIES_PREFIX: &str = "config/iam/policies/";
|
||||||
const IAM_POLICY_DB_PREFIX: &str = "config/iam/policydb/";
|
const IAM_POLICY_DB_PREFIX: &str = "config/iam/policydb/";
|
||||||
@@ -120,6 +121,15 @@ fn normalize_iam_config_blob(path: &str, data: &[u8]) -> std::result::Result<Opt
|
|||||||
if is_identity_path(path) {
|
if is_identity_path(path) {
|
||||||
let mut identity: UserIdentity =
|
let mut identity: UserIdentity =
|
||||||
serde_json::from_slice(data).map_err(|err| format!("parse IAM identity failed: {err}"))?;
|
serde_json::from_slice(data).map_err(|err| format!("parse IAM identity failed: {err}"))?;
|
||||||
|
if (path.starts_with(IAM_USERS_PREFIX) || path.starts_with(IAM_SERVICE_ACCOUNTS_PREFIX))
|
||||||
|
&& identity
|
||||||
|
.credentials
|
||||||
|
.expiration
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|expiration| *expiration == MINIO_GO_ZERO_TIME || *expiration == OffsetDateTime::UNIX_EPOCH)
|
||||||
|
{
|
||||||
|
identity.credentials.expiration = None;
|
||||||
|
}
|
||||||
if identity.update_at.is_none() {
|
if identity.update_at.is_none() {
|
||||||
identity.update_at = Some(OffsetDateTime::now_utc());
|
identity.update_at = Some(OffsetDateTime::now_utc());
|
||||||
}
|
}
|
||||||
@@ -441,7 +451,10 @@ mod tests {
|
|||||||
use crate::bucket::replication::{
|
use crate::bucket::replication::{
|
||||||
BucketReplicationResyncStatus, ReplicationMigrationBridge, ResyncStatusType, TargetReplicationResyncStatus,
|
BucketReplicationResyncStatus, ReplicationMigrationBridge, ResyncStatusType, TargetReplicationResyncStatus,
|
||||||
};
|
};
|
||||||
|
use rustfs_policy::auth::UserIdentity;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use time::format_description::well_known::Rfc3339;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_normalize_policy_mapping_legacy_timestamp_and_fields() {
|
fn test_normalize_policy_mapping_legacy_timestamp_and_fields() {
|
||||||
@@ -493,6 +506,54 @@ mod tests {
|
|||||||
assert!(v.get("updatedAt").is_some(), "normalize should backfill updatedAt");
|
assert!(v.get("updatedAt").is_some(), "normalize should backfill updatedAt");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_normalize_minio_permanent_credential_expiration() {
|
||||||
|
let cases = [
|
||||||
|
("config/iam/users/alice/identity.json", "0001-01-01T00:00:00Z", true),
|
||||||
|
("config/iam/users/alice/identity.json", "1970-01-01T00:00:00Z", true),
|
||||||
|
("config/iam/service-accounts/svc/identity.json", "0001-01-01T00:00:00Z", true),
|
||||||
|
("config/iam/service-accounts/svc/identity.json", "1970-01-01T00:00:00Z", true),
|
||||||
|
("config/iam/service-accounts/svc/identity.json", "1970-01-01T00:00:00.000000001Z", false),
|
||||||
|
("config/iam/sts/temp/identity.json", "0001-01-01T00:00:00Z", false),
|
||||||
|
("config/iam/sts/temp/identity.json", "1970-01-01T00:00:00Z", false),
|
||||||
|
("config/iam/users/alice/identity.json", "1969-12-31T23:59:59Z", false),
|
||||||
|
("config/iam/users/alice/identity.json", "1970-01-01T00:00:00.000000001Z", false),
|
||||||
|
("config/iam/users/alice/identity.json", "0001-01-01T00:00:00.000000001Z", false),
|
||||||
|
("config/iam/users/alice/identity.json", "2030-01-01T00:00:00Z", false),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (path, expiration, should_clear) in cases {
|
||||||
|
let input = serde_json::json!({
|
||||||
|
"version": 1,
|
||||||
|
"credentials": {
|
||||||
|
"accessKey": "test-access",
|
||||||
|
"secretKey": "test-secret",
|
||||||
|
"sessionToken": "test-session-token",
|
||||||
|
"parentUser": "test-parent",
|
||||||
|
"expiration": expiration,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let output = normalize_iam_config_blob(path, &serde_json::to_vec(&input).expect("serialize identity fixture"))
|
||||||
|
.expect("normalize should succeed")
|
||||||
|
.expect("identity path should be supported");
|
||||||
|
let identity: UserIdentity = serde_json::from_slice(&output).expect("deserialize normalized identity");
|
||||||
|
|
||||||
|
assert_eq!(identity.credentials.access_key, "test-access");
|
||||||
|
assert_eq!(identity.credentials.secret_key, "test-secret");
|
||||||
|
assert_eq!(identity.credentials.session_token, "test-session-token");
|
||||||
|
assert_eq!(identity.credentials.parent_user, "test-parent");
|
||||||
|
if should_clear {
|
||||||
|
assert_eq!(identity.credentials.expiration, None, "path: {path}, expiration: {expiration}");
|
||||||
|
} else {
|
||||||
|
assert_eq!(
|
||||||
|
identity.credentials.expiration,
|
||||||
|
Some(OffsetDateTime::parse(expiration, &Rfc3339).expect("parse expected expiration")),
|
||||||
|
"path: {path}, expiration: {expiration}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_normalize_bucket_meta_blob_resync_reencode() {
|
fn test_normalize_bucket_meta_blob_resync_reencode() {
|
||||||
let path = ".buckets/test/.replication/resync.bin";
|
let path = ".buckets/test/.replication/resync.bin";
|
||||||
|
|||||||
@@ -76,7 +76,12 @@ impl QuotaChecker {
|
|||||||
|
|
||||||
let current_usage = self.get_real_time_usage(bucket).await?;
|
let current_usage = self.get_real_time_usage(bucket).await?;
|
||||||
|
|
||||||
let admission_size = if uses_durable_reservations { 0 } else { operation_size };
|
// The reporting path projects this operation; storage mutations reserve it at commit.
|
||||||
|
let admission_size = if uses_durable_reservations && !force_usage_calculation {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
operation_size
|
||||||
|
};
|
||||||
let expected_usage = match operation {
|
let expected_usage = match operation {
|
||||||
QuotaOperation::PutObject | QuotaOperation::PostObject | QuotaOperation::CopyObject => {
|
QuotaOperation::PutObject | QuotaOperation::PostObject | QuotaOperation::CopyObject => {
|
||||||
current_usage.saturating_add(admission_size)
|
current_usage.saturating_add(admission_size)
|
||||||
|
|||||||
@@ -52,8 +52,8 @@ use super::replication_storage_boundary::{
|
|||||||
ReplicationObjectIO, ReplicationStorage, StatObjectOptions, StorageObjectInfoOrErr, WalkOptions,
|
ReplicationObjectIO, ReplicationStorage, StatObjectOptions, StorageObjectInfoOrErr, WalkOptions,
|
||||||
};
|
};
|
||||||
use super::replication_target_boundary::{
|
use super::replication_target_boundary::{
|
||||||
ERR_REPLICATION_SSEC_PASSTHROUGH_UNSUPPORTED, PutObjectOptions, PutObjectPartOptions, ReplicationTargetStore,
|
ERR_REPLICATION_SSEC_PASSTHROUGH_UNSUPPORTED, HeadObjectSdkError, PutObjectOptions, PutObjectPartOptions,
|
||||||
SsecPassthroughCapability, SsecPassthroughGate, TargetClient, is_replication_target_offline_error,
|
ReplicationTargetStore, SsecPassthroughCapability, SsecPassthroughGate, TargetClient, is_replication_target_offline_error,
|
||||||
replication_action_for_target_head, replication_complete_multipart_options, replication_delete_marker_purge_remove_options,
|
replication_action_for_target_head, replication_complete_multipart_options, replication_delete_marker_purge_remove_options,
|
||||||
replication_delete_remove_options, replication_force_delete_remove_options, replication_object_is_ssec_encrypted,
|
replication_delete_remove_options, replication_force_delete_remove_options, replication_object_is_ssec_encrypted,
|
||||||
replication_put_object_header_size, replication_put_object_options, replication_target_head_is_newer_null_version,
|
replication_put_object_header_size, replication_put_object_options, replication_target_head_is_newer_null_version,
|
||||||
@@ -214,7 +214,7 @@ async fn head_object_for_worker(
|
|||||||
target_bucket: &str,
|
target_bucket: &str,
|
||||||
object: &str,
|
object: &str,
|
||||||
version_id: Option<String>,
|
version_id: Option<String>,
|
||||||
) -> std::result::Result<HeadObjectOutput, SdkError<HeadObjectError>> {
|
) -> std::result::Result<HeadObjectOutput, HeadObjectSdkError> {
|
||||||
target_client.head_object(target_bucket, object, version_id).await
|
target_client.head_object(target_bucket, object, version_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,7 +233,7 @@ async fn mark_replication_target_offline_if_needed(target_client: &Arc<TargetCli
|
|||||||
async fn head_object_fallback(
|
async fn head_object_fallback(
|
||||||
tgt_client: &TargetClient,
|
tgt_client: &TargetClient,
|
||||||
object: &str,
|
object: &str,
|
||||||
) -> std::result::Result<Option<HeadObjectOutput>, SdkError<HeadObjectError>> {
|
) -> std::result::Result<Option<HeadObjectOutput>, HeadObjectSdkError> {
|
||||||
match head_object_for_worker(tgt_client, &tgt_client.bucket, object, None).await {
|
match head_object_for_worker(tgt_client, &tgt_client.bucket, object, None).await {
|
||||||
Ok(oi) => Ok(Some(oi)),
|
Ok(oi) => Ok(Some(oi)),
|
||||||
Err(e) if e.as_service_error().is_some_and(|se| se.is_not_found()) || has_raw_status(&e, 404) => Ok(None),
|
Err(e) if e.as_service_error().is_some_and(|se| se.is_not_found()) || has_raw_status(&e, 404) => Ok(None),
|
||||||
@@ -1152,11 +1152,11 @@ fn spawn_resync_walk_task<S: ReplicationStorage>(
|
|||||||
/// updating the per-object status counters and returning the accounted size
|
/// updating the per-object status counters and returning the accounted size
|
||||||
/// together with any verification error.
|
/// together with any verification error.
|
||||||
async fn verify_resync_head_result(
|
async fn verify_resync_head_result(
|
||||||
head_result: std::result::Result<HeadObjectOutput, SdkError<HeadObjectError>>,
|
head_result: std::result::Result<HeadObjectOutput, HeadObjectSdkError>,
|
||||||
roi: &ReplicateObjectInfo,
|
roi: &ReplicateObjectInfo,
|
||||||
st: &mut TargetReplicationResyncStatus,
|
st: &mut TargetReplicationResyncStatus,
|
||||||
target_client: &Arc<TargetClient>,
|
target_client: &Arc<TargetClient>,
|
||||||
) -> (i64, Option<SdkError<HeadObjectError>>) {
|
) -> (i64, Option<HeadObjectSdkError>) {
|
||||||
match head_result {
|
match head_result {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
st.replicated_count += 1;
|
st.replicated_count += 1;
|
||||||
@@ -1275,7 +1275,7 @@ async fn resync_worker_process_object<S: ReplicationStorage>(
|
|||||||
"Processed resync object"
|
"Processed resync object"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
st.error = err.as_ref().and_then(resync_target_error_detail);
|
st.error = err.as_ref().and_then(|err| resync_target_error_detail(err.as_ref()));
|
||||||
|
|
||||||
st
|
st
|
||||||
}
|
}
|
||||||
@@ -2467,7 +2467,7 @@ async fn replicate_delete_to_target(dobj: &DeletedObjectReplicationInfo, tgt_cli
|
|||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let non_retryable = matches!(
|
let non_retryable = matches!(
|
||||||
&e,
|
e.as_ref(),
|
||||||
SdkError::ServiceError(service_err)
|
SdkError::ServiceError(service_err)
|
||||||
if is_retryable_delete_replication_head_error(
|
if is_retryable_delete_replication_head_error(
|
||||||
service_err.err().is_not_found(),
|
service_err.err().is_not_found(),
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ use time::OffsetDateTime;
|
|||||||
use time::format_description::well_known::Rfc3339;
|
use time::format_description::well_known::Rfc3339;
|
||||||
|
|
||||||
pub(crate) use crate::bucket::bucket_target_sys::{
|
pub(crate) use crate::bucket::bucket_target_sys::{
|
||||||
AdvancedPutOptions, PutObjectOptions, PutObjectPartOptions, RemoveObjectOptions, TargetClient, resolve_read_api_version_id,
|
AdvancedPutOptions, HeadObjectSdkError, PutObjectOptions, PutObjectPartOptions, RemoveObjectOptions, TargetClient,
|
||||||
|
resolve_read_api_version_id,
|
||||||
};
|
};
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) use crate::bucket::target::BucketTarget;
|
pub(crate) use crate::bucket::target::BucketTarget;
|
||||||
|
|||||||
@@ -454,7 +454,7 @@ impl S3PeerSys {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
topology_complete &= bucket_map.values().all(|count| *count >= quorum);
|
topology_complete &= bucket_map.values().all(|count| *count >= quorum);
|
||||||
// TODO: MRF
|
// TODO(backlog): integrate MRF backlog stats into scanner bucket listing
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut buckets: Vec<BucketInfo> = result_map.into_values().collect();
|
let mut buckets: Vec<BucketInfo> = result_map.into_values().collect();
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ use rustfs_protos::evict_failed_connection;
|
|||||||
use rustfs_protos::proto_gen::node_service::RenamePartRequest;
|
use rustfs_protos::proto_gen::node_service::RenamePartRequest;
|
||||||
use rustfs_protos::proto_gen::node_service::{
|
use rustfs_protos::proto_gen::node_service::{
|
||||||
BatchReadVersionRequest, BatchReadVersionResponse, CheckPartsRequest, DeletePathsRequest, DeleteRequest,
|
BatchReadVersionRequest, BatchReadVersionResponse, CheckPartsRequest, DeletePathsRequest, DeleteRequest,
|
||||||
DeleteVersionRequest, DeleteVersionsRequest, DeleteVolumeRequest, DiskInfoRequest, ListDirRequest, ListVolumesRequest,
|
DeleteVersionRequest, DeleteVersionsRequest, DeleteVersionsResponse, DeleteVolumeRequest, DiskInfoRequest, ListDirRequest,
|
||||||
MakeVolumeRequest, MakeVolumesRequest, PreparePartTransactionRequest, ReadAllRequest, ReadMetadataRequest,
|
ListVolumesRequest, MakeVolumeRequest, MakeVolumesRequest, PreparePartTransactionRequest, ReadAllRequest,
|
||||||
ReadMultipleRequest, ReadMultipleResponse, ReadPartsRequest, ReadVersionRequest, ReadXlRequest, RenameDataRequest,
|
ReadMetadataRequest, ReadMultipleRequest, ReadMultipleResponse, ReadPartsRequest, ReadVersionRequest, ReadXlRequest,
|
||||||
RenameFileRequest, SettlePartTransactionRequest, SnapshotLeaseReleaseRequest, SnapshotLeaseRenewRequest,
|
RenameDataRequest, RenameFileRequest, SettlePartTransactionRequest, SnapshotLeaseReleaseRequest, SnapshotLeaseRenewRequest,
|
||||||
SnapshotLeaseRequest, SnapshotLeaseResponse, StatVolumeRequest, UpdateMetadataRequest, VerifyFileRequest, WriteAllRequest,
|
SnapshotLeaseRequest, SnapshotLeaseResponse, StatVolumeRequest, UpdateMetadataRequest, VerifyFileRequest, WriteAllRequest,
|
||||||
WriteMetadataRequest, node_service_client::NodeServiceClient,
|
WriteMetadataRequest, node_service_client::NodeServiceClient,
|
||||||
};
|
};
|
||||||
@@ -112,6 +112,28 @@ const EVENT_REMOTE_DISK_RPC: &str = "remote_disk_rpc";
|
|||||||
const SNAPSHOT_LEASE_PROTOCOL_VERSION: u32 = 1;
|
const SNAPSHOT_LEASE_PROTOCOL_VERSION: u32 = 1;
|
||||||
pub const REMOTE_SNAPSHOT_LEASE_TTL: Duration = Duration::from_secs(60);
|
pub const REMOTE_SNAPSHOT_LEASE_TTL: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
fn decode_delete_versions_errors(response: DeleteVersionsResponse, expected_len: usize) -> Vec<Option<Error>> {
|
||||||
|
if !response.item_errors.is_empty() {
|
||||||
|
if response.item_errors.len() != expected_len {
|
||||||
|
return vec![Some(Error::other("malformed delete_versions item errors")); expected_len];
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
.item_errors
|
||||||
|
.into_iter()
|
||||||
|
.map(|error| (error.code != 0).then(|| error.into()))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.errors.len() != expected_len {
|
||||||
|
return vec![Some(Error::other("malformed delete_versions errors")); expected_len];
|
||||||
|
}
|
||||||
|
response
|
||||||
|
.errors
|
||||||
|
.into_iter()
|
||||||
|
.map(|error| (!error.is_empty()).then(|| Error::other(error)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn snapshot_lease_token_from_response(response: SnapshotLeaseResponse) -> Result<SnapshotLeaseToken> {
|
fn snapshot_lease_token_from_response(response: SnapshotLeaseResponse) -> Result<SnapshotLeaseToken> {
|
||||||
if !response.success {
|
if !response.success {
|
||||||
return Err(response.error.unwrap_or_default().into());
|
return Err(response.error.unwrap_or_default().into());
|
||||||
@@ -2406,8 +2428,6 @@ impl DiskAPI for RemoteDisk {
|
|||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: use Error not string
|
|
||||||
|
|
||||||
let result = self
|
let result = self
|
||||||
.execute_with_timeout(
|
.execute_with_timeout(
|
||||||
|| async {
|
|| async {
|
||||||
@@ -2439,17 +2459,7 @@ impl DiskAPI for RemoteDisk {
|
|||||||
}
|
}
|
||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
response
|
decode_delete_versions_errors(response, versions.len())
|
||||||
.errors
|
|
||||||
.iter()
|
|
||||||
.map(|error| {
|
|
||||||
if error.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(Error::other(error.to_string()))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(level = "trace", skip_all)]
|
#[tracing::instrument(level = "trace", skip_all)]
|
||||||
@@ -3760,6 +3770,63 @@ mod tests {
|
|||||||
|
|
||||||
static INIT: Once = Once::new();
|
static INIT: Once = Once::new();
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delete_versions_response_preserves_typed_item_errors() {
|
||||||
|
let errors = decode_delete_versions_errors(
|
||||||
|
DeleteVersionsResponse {
|
||||||
|
success: true,
|
||||||
|
errors: vec!["file not found".to_string(), String::new()],
|
||||||
|
error: None,
|
||||||
|
item_errors: vec![
|
||||||
|
rustfs_protos::proto_gen::node_service::Error {
|
||||||
|
code: DiskError::FileNotFound.to_u32(),
|
||||||
|
error_info: "file not found".to_string(),
|
||||||
|
},
|
||||||
|
rustfs_protos::proto_gen::node_service::Error::default(),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(matches!(errors.as_slice(), [Some(DiskError::FileNotFound), None]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delete_versions_response_accepts_legacy_string_errors() {
|
||||||
|
let errors = decode_delete_versions_errors(
|
||||||
|
DeleteVersionsResponse {
|
||||||
|
success: true,
|
||||||
|
errors: vec!["legacy error".to_string(), String::new()],
|
||||||
|
error: None,
|
||||||
|
item_errors: Vec::new(),
|
||||||
|
},
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(errors.len(), 2);
|
||||||
|
assert_eq!(errors[0].as_ref().map(ToString::to_string).as_deref(), Some("io error legacy error"));
|
||||||
|
assert!(errors[1].is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delete_versions_response_rejects_misaligned_item_errors() {
|
||||||
|
let errors = decode_delete_versions_errors(
|
||||||
|
DeleteVersionsResponse {
|
||||||
|
success: true,
|
||||||
|
errors: vec!["file not found".to_string()],
|
||||||
|
error: None,
|
||||||
|
item_errors: vec![rustfs_protos::proto_gen::node_service::Error {
|
||||||
|
code: DiskError::FileNotFound.to_u32(),
|
||||||
|
error_info: "file not found".to_string(),
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(errors.len(), 2);
|
||||||
|
assert!(errors.iter().all(Option::is_some));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn disk_mutation_digest_marks_rolling_compatibility() {
|
fn disk_mutation_digest_marks_rolling_compatibility() {
|
||||||
let mut request = Request::new(());
|
let mut request = Request::new(());
|
||||||
|
|||||||
+512
-122
@@ -36,7 +36,8 @@ use crate::disk::error::DiskError;
|
|||||||
use crate::disk::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
|
use crate::disk::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::error::{
|
use crate::error::{
|
||||||
StorageError, is_err_bucket_exists, is_err_bucket_not_found, is_err_object_not_found, is_err_version_not_found,
|
StorageError, is_err_bucket_exists, is_err_bucket_not_found, is_err_object_not_found, is_err_operation_canceled,
|
||||||
|
is_err_version_not_found,
|
||||||
};
|
};
|
||||||
use crate::layout::endpoints::EndpointServerPools;
|
use crate::layout::endpoints::EndpointServerPools;
|
||||||
use crate::object_api::{GetObjectReader, ObjectOptions};
|
use crate::object_api::{GetObjectReader, ObjectOptions};
|
||||||
@@ -89,11 +90,15 @@ const DECOMMISSION_STAGE_SOURCE_CLEANUP: &str = "source_cleanup";
|
|||||||
const DECOMMISSION_STAGE_ENTRY_FINISHED: &str = "entry_finished";
|
const DECOMMISSION_STAGE_ENTRY_FINISHED: &str = "entry_finished";
|
||||||
const DECOMMISSION_PROGRESS_SAVE_INTERVAL: Duration = Duration::seconds(30);
|
const DECOMMISSION_PROGRESS_SAVE_INTERVAL: Duration = Duration::seconds(30);
|
||||||
const DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD: usize = 1000;
|
const DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD: usize = 1000;
|
||||||
|
const DECOMMISSION_PROGRESS_SAVE_RETRY_BACKOFF: Duration = Duration::seconds(1);
|
||||||
const DECOMMISSION_BUCKET_CONCURRENCY_ENV: &str = "RUSTFS_DECOMMISSION_BUCKET_CONCURRENCY";
|
const DECOMMISSION_BUCKET_CONCURRENCY_ENV: &str = "RUSTFS_DECOMMISSION_BUCKET_CONCURRENCY";
|
||||||
const DECOMMISSION_BUCKET_CONCURRENCY_DEFAULT_CAP: usize = 4;
|
const DECOMMISSION_BUCKET_CONCURRENCY_DEFAULT_CAP: usize = 4;
|
||||||
const DECOMMISSION_TARGET_CAPACITY_OVERHEAD_PERCENT: usize = 30;
|
const DECOMMISSION_TARGET_CAPACITY_OVERHEAD_PERCENT: usize = 30;
|
||||||
const DECOMMISSION_LISTING_MAX_ATTEMPTS: usize = 3;
|
const DECOMMISSION_LISTING_MAX_ATTEMPTS: usize = 3;
|
||||||
const DECOMMISSION_LISTING_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
|
const DECOMMISSION_LISTING_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
|
||||||
|
/// Background decommission walks must tolerate slow object migrations; the
|
||||||
|
/// stall timeout is the drive-health bound, not the total listing duration.
|
||||||
|
const DECOMMISSION_BACKGROUND_WALKDIR_STALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||||
|
|
||||||
pub const POOL_META_NAME: &str = "pool.bin";
|
pub const POOL_META_NAME: &str = "pool.bin";
|
||||||
pub const POOL_META_FORMAT: u16 = 1;
|
pub const POOL_META_FORMAT: u16 = 1;
|
||||||
@@ -635,22 +640,6 @@ fn track_decommission_current_object(meta: &mut PoolMeta, idx: usize, bucket: &s
|
|||||||
track_decommission_current_object_stage(meta, idx, bucket, object, "")
|
track_decommission_current_object_stage(meta, idx, bucket, object, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn touch_decommission_progress(meta: &mut PoolMeta, idx: usize) -> Result<()> {
|
|
||||||
let pool_count = meta.pools.len();
|
|
||||||
ensure_valid_decommission_pool_index(pool_count, idx)?;
|
|
||||||
|
|
||||||
let Some(pool) = meta.pools.get_mut(idx) else {
|
|
||||||
return Err(invalid_decommission_pool_index_error(pool_count, idx));
|
|
||||||
};
|
|
||||||
let Some(info) = pool.decommission.as_mut() else {
|
|
||||||
return Err(decommission_metadata_not_initialized_error("touch decommission progress"));
|
|
||||||
};
|
|
||||||
|
|
||||||
pool.last_update = OffsetDateTime::now_utc();
|
|
||||||
info.mark_progress_saved();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_decommission_update_after_result(result: Result<bool>) -> Result<bool> {
|
fn resolve_decommission_update_after_result(result: Result<bool>) -> Result<bool> {
|
||||||
result.map_err(|err| Error::other(format!("decommission metadata update failed: {err}")))
|
result.map_err(|err| Error::other(format!("decommission metadata update failed: {err}")))
|
||||||
}
|
}
|
||||||
@@ -770,7 +759,76 @@ async fn load_decommission_entry_exact_versions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_decommission_check_after_list_result(list_result: Result<()>, entry_error: Option<Error>) -> Result<()> {
|
fn resolve_decommission_check_after_list_result(list_result: Result<()>, entry_error: Option<Error>) -> Result<()> {
|
||||||
if let Some(err) = entry_error { Err(err) } else { list_result }
|
match list_result {
|
||||||
|
Ok(()) => entry_error.map_or(Ok(()), Err),
|
||||||
|
Err(list_err) => resolve_decommission_listing_error(Some(list_err), entry_error).map_or(Ok(()), Err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_decommission_listing_error(listing_error: Option<Error>, entry_error: Option<Error>) -> Option<Error> {
|
||||||
|
match (listing_error, entry_error) {
|
||||||
|
(Some(listing_error), Some(entry_error)) if is_err_operation_canceled(&listing_error) => Some(entry_error),
|
||||||
|
(Some(listing_error), Some(entry_error)) if is_err_operation_canceled(&entry_error) => Some(listing_error),
|
||||||
|
(Some(listing_error), _) => Some(listing_error),
|
||||||
|
(None, entry_error) => entry_error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decommission_unresolved_listing_error(
|
||||||
|
bucket: &str,
|
||||||
|
prefix: &str,
|
||||||
|
candidate: Option<&str>,
|
||||||
|
candidate_count: usize,
|
||||||
|
disk_error_count: usize,
|
||||||
|
pool_index: usize,
|
||||||
|
set_index: usize,
|
||||||
|
) -> Error {
|
||||||
|
let location = candidate.unwrap_or(prefix);
|
||||||
|
Error::other(format!(
|
||||||
|
"decommission listing could not resolve metadata for {bucket}/{location} on pool {pool_index} set {set_index} ({candidate_count} candidate(s), {disk_error_count} disk error(s))"
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_decommission_partial_listing_entry(
|
||||||
|
entries: MetaCacheEntries,
|
||||||
|
resolver: MetadataResolutionParams,
|
||||||
|
bucket: &str,
|
||||||
|
prefix: &str,
|
||||||
|
disk_error_count: usize,
|
||||||
|
pool_index: usize,
|
||||||
|
set_index: usize,
|
||||||
|
) -> Result<MetaCacheEntry> {
|
||||||
|
let candidate_count = entries.as_ref().iter().flatten().count();
|
||||||
|
if let Some(entry) = entries.resolve(resolver) {
|
||||||
|
return Ok(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
let candidate = entries.as_ref().iter().flatten().map(|entry| entry.name.as_str()).next();
|
||||||
|
Err(decommission_unresolved_listing_error(
|
||||||
|
bucket,
|
||||||
|
prefix,
|
||||||
|
candidate,
|
||||||
|
candidate_count,
|
||||||
|
disk_error_count,
|
||||||
|
pool_index,
|
||||||
|
set_index,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn record_decommission_entry_error(
|
||||||
|
entry_error: &Arc<tokio::sync::Mutex<Option<Error>>>,
|
||||||
|
rx: &CancellationToken,
|
||||||
|
err: Error,
|
||||||
|
) {
|
||||||
|
if rx.is_cancelled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut first_err = entry_error.lock().await;
|
||||||
|
if first_err.is_none() && !rx.is_cancelled() {
|
||||||
|
*first_err = Some(err);
|
||||||
|
rx.cancel();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_decommission_pool_meta_reload_result(result: Result<()>, stage: &str) -> Result<()> {
|
fn resolve_decommission_pool_meta_reload_result(result: Result<()>, stage: &str) -> Result<()> {
|
||||||
@@ -1480,6 +1538,7 @@ impl TryFrom<PersistedPoolDecommissionInfo> for PoolDecommissionInfo {
|
|||||||
terminal_reload_attempt_at: value.terminal_reload_attempt_at,
|
terminal_reload_attempt_at: value.terminal_reload_attempt_at,
|
||||||
terminal_reload_failures: value.terminal_reload_failures,
|
terminal_reload_failures: value.terminal_reload_failures,
|
||||||
progress_save_item_baseline: value.items_decommissioned.saturating_add(value.items_decommission_failed),
|
progress_save_item_baseline: value.items_decommissioned.saturating_add(value.items_decommission_failed),
|
||||||
|
progress_save_retry_after: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1511,6 +1570,7 @@ impl TryFrom<LegacyPoolDecommissionInfo> for PoolDecommissionInfo {
|
|||||||
terminal_reload_attempt_at: None,
|
terminal_reload_attempt_at: None,
|
||||||
terminal_reload_failures: Vec::new(),
|
terminal_reload_failures: Vec::new(),
|
||||||
progress_save_item_baseline: value.items_decommissioned.saturating_add(value.items_decommission_failed),
|
progress_save_item_baseline: value.items_decommissioned.saturating_add(value.items_decommission_failed),
|
||||||
|
progress_save_retry_after: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1624,6 +1684,82 @@ impl PoolMeta {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn decommission_progress_checkpoint(
|
||||||
|
&self,
|
||||||
|
idx: usize,
|
||||||
|
duration: Duration,
|
||||||
|
now: OffsetDateTime,
|
||||||
|
) -> Result<Option<DecommissionProgressCheckpoint>> {
|
||||||
|
let pool_count = self.pools.len();
|
||||||
|
ensure_valid_decommission_pool_index(pool_count, idx)?;
|
||||||
|
|
||||||
|
let Some(pool) = self.pools.get(idx) else {
|
||||||
|
return Err(invalid_decommission_pool_index_error(pool_count, idx));
|
||||||
|
};
|
||||||
|
let Some(info) = pool.decommission.as_ref() else {
|
||||||
|
return Err(decommission_metadata_not_initialized_error("update decommission metadata timestamp"));
|
||||||
|
};
|
||||||
|
|
||||||
|
if info.progress_save_retry_after.is_some_and(|retry_after| now < retry_after) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let time_threshold_reached = now.unix_timestamp() - pool.last_update.unix_timestamp() >= duration.whole_seconds();
|
||||||
|
let item_threshold_reached = info.items_since_last_progress_save() >= DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD;
|
||||||
|
if !time_threshold_reached && !item_threshold_reached {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Some(DecommissionProgressCheckpoint {
|
||||||
|
start_time: info.start_time,
|
||||||
|
queued: info.queued,
|
||||||
|
counted_items: info.counted_items(),
|
||||||
|
checkpoint_at: now,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit_decommission_progress_checkpoint(&mut self, idx: usize, checkpoint: DecommissionProgressCheckpoint) -> bool {
|
||||||
|
let Some(pool) = self.pools.get_mut(idx) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(info) = pool.decommission.as_mut() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if info.start_time != checkpoint.start_time
|
||||||
|
|| info.queued != checkpoint.queued
|
||||||
|
|| !is_decommission_active(info.complete, info.failed, info.canceled)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
info.progress_save_item_baseline = info.progress_save_item_baseline.max(checkpoint.counted_items);
|
||||||
|
info.progress_save_retry_after = None;
|
||||||
|
pool.last_update = pool.last_update.max(checkpoint.checkpoint_at);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn defer_decommission_progress_checkpoint(
|
||||||
|
&mut self,
|
||||||
|
idx: usize,
|
||||||
|
checkpoint: DecommissionProgressCheckpoint,
|
||||||
|
retry_after: OffsetDateTime,
|
||||||
|
) {
|
||||||
|
let Some(pool) = self.pools.get_mut(idx) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(info) = pool.decommission.as_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if info.start_time == checkpoint.start_time
|
||||||
|
&& info.queued == checkpoint.queued
|
||||||
|
&& is_decommission_active(info.complete, info.failed, info.canceled)
|
||||||
|
{
|
||||||
|
info.progress_save_retry_after = Some(retry_after);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn load_from_config_data(&mut self, data: Vec<u8>) -> Result<()> {
|
fn load_from_config_data(&mut self, data: Vec<u8>) -> Result<()> {
|
||||||
if data.is_empty() {
|
if data.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -1984,30 +2120,9 @@ impl PoolMeta {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_after(&mut self, idx: usize, duration: Duration) -> Result<bool> {
|
pub fn update_after(&mut self, idx: usize, duration: Duration) -> Result<bool> {
|
||||||
let pool_count = self.pools.len();
|
Ok(self
|
||||||
ensure_valid_decommission_pool_index(pool_count, idx)?;
|
.decommission_progress_checkpoint(idx, duration, OffsetDateTime::now_utc())?
|
||||||
|
.is_some())
|
||||||
let (last_update, item_threshold_reached) = match self.pools.get(idx) {
|
|
||||||
Some(pool) if let Some(info) = pool.decommission.as_ref() => (
|
|
||||||
pool.last_update,
|
|
||||||
info.items_since_last_progress_save() >= DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD,
|
|
||||||
),
|
|
||||||
Some(_) => {
|
|
||||||
return Err(decommission_metadata_not_initialized_error("update decommission metadata timestamp"));
|
|
||||||
}
|
|
||||||
None => return Err(invalid_decommission_pool_index_error(pool_count, idx)),
|
|
||||||
};
|
|
||||||
let now = OffsetDateTime::now_utc();
|
|
||||||
|
|
||||||
if now.unix_timestamp() - last_update.unix_timestamp() >= duration.whole_seconds() || item_threshold_reached {
|
|
||||||
let Some(pool) = self.pools.get_mut(idx) else {
|
|
||||||
return Err(invalid_decommission_pool_index_error(pool_count, idx));
|
|
||||||
};
|
|
||||||
pool.last_update = now;
|
|
||||||
return Ok(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn validate(&self, pools: Vec<Arc<Sets>>) -> Result<bool> {
|
pub fn validate(&self, pools: Vec<Arc<Sets>>) -> Result<bool> {
|
||||||
@@ -2148,6 +2263,16 @@ pub struct PoolDecommissionInfo {
|
|||||||
pub terminal_reload_failures: Vec<String>,
|
pub terminal_reload_failures: Vec<String>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub progress_save_item_baseline: usize,
|
pub progress_save_item_baseline: usize,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub progress_save_retry_after: Option<OffsetDateTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
struct DecommissionProgressCheckpoint {
|
||||||
|
start_time: Option<OffsetDateTime>,
|
||||||
|
queued: bool,
|
||||||
|
counted_items: usize,
|
||||||
|
checkpoint_at: OffsetDateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PoolDecommissionInfo {
|
impl PoolDecommissionInfo {
|
||||||
@@ -2182,6 +2307,7 @@ impl PoolDecommissionInfo {
|
|||||||
|
|
||||||
fn mark_progress_saved(&mut self) {
|
fn mark_progress_saved(&mut self) {
|
||||||
self.progress_save_item_baseline = self.counted_items();
|
self.progress_save_item_baseline = self.counted_items();
|
||||||
|
self.progress_save_retry_after = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bucket_push(&mut self, bucket: &DecomBucketInfo) {
|
pub fn bucket_push(&mut self, bucket: &DecomBucketInfo) {
|
||||||
@@ -2486,6 +2612,40 @@ impl ECStore {
|
|||||||
snapshot.save(self.pools.clone()).await
|
snapshot.save(self.pools.clone()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn save_decommission_progress_checkpoint(&self, idx: usize) -> Result<bool> {
|
||||||
|
// Lock order: save gate, then the short pool metadata read/write sections. Peer
|
||||||
|
// reloads are intentionally performed by the caller after both locks are released.
|
||||||
|
let _save_guard = self.pool_meta_save_gate.lock().await;
|
||||||
|
let (snapshot, checkpoint) = {
|
||||||
|
let pool_meta = self.pool_meta.read().await;
|
||||||
|
let Some(checkpoint) = pool_meta.decommission_progress_checkpoint(
|
||||||
|
idx,
|
||||||
|
DECOMMISSION_PROGRESS_SAVE_INTERVAL,
|
||||||
|
OffsetDateTime::now_utc(),
|
||||||
|
)?
|
||||||
|
else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut snapshot = pool_meta.clone();
|
||||||
|
let Some(pool) = snapshot.pools.get_mut(idx) else {
|
||||||
|
return Err(invalid_decommission_pool_index_error(snapshot.pools.len(), idx));
|
||||||
|
};
|
||||||
|
pool.last_update = checkpoint.checkpoint_at;
|
||||||
|
(snapshot, checkpoint)
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(err) = snapshot.save(self.pools.clone()).await {
|
||||||
|
let retry_after = OffsetDateTime::now_utc() + DECOMMISSION_PROGRESS_SAVE_RETRY_BACKOFF;
|
||||||
|
let mut pool_meta = self.pool_meta.write().await;
|
||||||
|
pool_meta.defer_decommission_progress_checkpoint(idx, checkpoint, retry_after);
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pool_meta = self.pool_meta.write().await;
|
||||||
|
Ok(pool_meta.commit_decommission_progress_checkpoint(idx, checkpoint))
|
||||||
|
}
|
||||||
|
|
||||||
async fn save_current_pool_meta_for_decommission_start(
|
async fn save_current_pool_meta_for_decommission_start(
|
||||||
&self,
|
&self,
|
||||||
indices: &[usize],
|
indices: &[usize],
|
||||||
@@ -2868,7 +3028,7 @@ impl ECStore {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn save_decommission_entry_progress_stage(
|
async fn track_decommission_entry_progress_stage(
|
||||||
&self,
|
&self,
|
||||||
idx: usize,
|
idx: usize,
|
||||||
bucket: &str,
|
bucket: &str,
|
||||||
@@ -2879,22 +3039,6 @@ impl ECStore {
|
|||||||
let mut pool_meta = self.pool_meta.write().await;
|
let mut pool_meta = self.pool_meta.write().await;
|
||||||
track_decommission_current_object_stage(&mut pool_meta, idx, bucket, object, stage)
|
track_decommission_current_object_stage(&mut pool_meta, idx, bucket, object, stage)
|
||||||
.map_err(|err| with_decommission_entry_context(stage, bucket, object, err))?;
|
.map_err(|err| with_decommission_entry_context(stage, bucket, object, err))?;
|
||||||
touch_decommission_progress(&mut pool_meta, idx)
|
|
||||||
.map_err(|err| with_decommission_entry_context(stage, bucket, object, err))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(err) = resolve_decommission_progress_save_result(self.save_current_pool_meta().await) {
|
|
||||||
warn!(
|
|
||||||
event = EVENT_DECOMMISSION_ENTRY,
|
|
||||||
component = LOG_COMPONENT_ECSTORE,
|
|
||||||
subsystem = LOG_SUBSYSTEM_POOLS,
|
|
||||||
pool_index = idx,
|
|
||||||
bucket = %bucket,
|
|
||||||
object = %object,
|
|
||||||
stage,
|
|
||||||
error = ?err,
|
|
||||||
"Decommission progress stage save failed"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -3162,7 +3306,7 @@ impl ECStore {
|
|||||||
let bucket_name = bucket.clone();
|
let bucket_name = bucket.clone();
|
||||||
let object_name = rd.object_info.name.clone();
|
let object_name = rd.object_info.name.clone();
|
||||||
|
|
||||||
self.save_decommission_entry_progress_stage(
|
self.track_decommission_entry_progress_stage(
|
||||||
idx,
|
idx,
|
||||||
bucket_name.as_str(),
|
bucket_name.as_str(),
|
||||||
object_name.as_str(),
|
object_name.as_str(),
|
||||||
@@ -3256,7 +3400,7 @@ impl ECStore {
|
|||||||
}
|
}
|
||||||
decommission_cancel_signal_result(rx.is_cancelled())?;
|
decommission_cancel_signal_result(rx.is_cancelled())?;
|
||||||
|
|
||||||
self.save_decommission_entry_progress_stage(
|
self.track_decommission_entry_progress_stage(
|
||||||
idx,
|
idx,
|
||||||
bucket.as_str(),
|
bucket.as_str(),
|
||||||
entry.name.as_str(),
|
entry.name.as_str(),
|
||||||
@@ -3264,7 +3408,7 @@ impl ECStore {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.save_decommission_entry_progress_stage(
|
self.track_decommission_entry_progress_stage(
|
||||||
idx,
|
idx,
|
||||||
bucket.as_str(),
|
bucket.as_str(),
|
||||||
entry.name.as_str(),
|
entry.name.as_str(),
|
||||||
@@ -3331,34 +3475,42 @@ impl ECStore {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
self.save_decommission_entry_progress_stage(idx, bucket.as_str(), entry.name.as_str(), DECOMMISSION_STAGE_ENTRY_FINISHED)
|
self.track_decommission_entry_progress_stage(
|
||||||
.await?;
|
idx,
|
||||||
|
bucket.as_str(),
|
||||||
|
entry.name.as_str(),
|
||||||
|
DECOMMISSION_STAGE_ENTRY_FINISHED,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
if should_save_progress {
|
if should_save_progress {
|
||||||
let save_result = self.save_current_pool_meta().await;
|
match self.save_decommission_progress_checkpoint(idx).await {
|
||||||
if let Some(err) = resolve_decommission_progress_save_result(save_result) {
|
Ok(true) => {
|
||||||
warn!(
|
if let Some(notification_sys) = runtime_sources::notification_sys()
|
||||||
event = EVENT_DECOMMISSION_ENTRY,
|
&& let Err(err) = resolve_decommission_entry_reload_result(
|
||||||
component = LOG_COMPONENT_ECSTORE,
|
notification_sys.reload_pool_meta().await,
|
||||||
subsystem = LOG_SUBSYSTEM_POOLS,
|
bucket.as_str(),
|
||||||
pool_index = idx,
|
entry.name.as_str(),
|
||||||
bucket = %bucket,
|
)
|
||||||
object = %entry.name,
|
{
|
||||||
state = "progress_save_failed",
|
warn!("{err}");
|
||||||
error = %err,
|
}
|
||||||
"Decommission progress save failed; continuing and will retry at the next checkpoint"
|
}
|
||||||
);
|
Ok(false) => {}
|
||||||
} else {
|
Err(err) => {
|
||||||
let mut pool_meta = self.pool_meta.write().await;
|
if let Some(err) = resolve_decommission_progress_save_result(Err(err)) {
|
||||||
pool_meta.mark_decommission_progress_saved();
|
warn!(
|
||||||
if let Some(notification_sys) = runtime_sources::notification_sys()
|
event = EVENT_DECOMMISSION_ENTRY,
|
||||||
&& let Err(err) = resolve_decommission_entry_reload_result(
|
component = LOG_COMPONENT_ECSTORE,
|
||||||
notification_sys.reload_pool_meta().await,
|
subsystem = LOG_SUBSYSTEM_POOLS,
|
||||||
bucket.as_str(),
|
pool_index = idx,
|
||||||
entry.name.as_str(),
|
bucket = %bucket,
|
||||||
)
|
object = %entry.name,
|
||||||
{
|
state = "progress_save_failed",
|
||||||
warn!("{err}");
|
error = %err,
|
||||||
|
"Decommission progress save failed; continuing and will retry at the next checkpoint"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3535,6 +3687,7 @@ impl ECStore {
|
|||||||
let rx_clone = rx.clone();
|
let rx_clone = rx.clone();
|
||||||
let bi = bi.clone();
|
let bi = bi.clone();
|
||||||
let set_id = set_idx;
|
let set_id = set_idx;
|
||||||
|
let listing_entry_error = entry_error.clone();
|
||||||
let worker = tokio::spawn(async move {
|
let worker = tokio::spawn(async move {
|
||||||
let _listing_permit = listing_permit;
|
let _listing_permit = listing_permit;
|
||||||
run_decommission_listing_with_retry(
|
run_decommission_listing_with_retry(
|
||||||
@@ -3548,7 +3701,11 @@ impl ECStore {
|
|||||||
let set = set.clone();
|
let set = set.clone();
|
||||||
let rx = rx_clone.clone();
|
let rx = rx_clone.clone();
|
||||||
let bucket = bi.clone();
|
let bucket = bi.clone();
|
||||||
async move { set.list_objects_to_decommission(rx, bucket, callback).await }
|
let entry_error = listing_entry_error.clone();
|
||||||
|
async move {
|
||||||
|
set.list_objects_to_decommission(rx, bucket, callback, entry_error.clone(), idx, set_id)
|
||||||
|
.await
|
||||||
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -3578,11 +3735,7 @@ impl ECStore {
|
|||||||
|
|
||||||
wait_decommission_worker_drain(&workers, worker_limit).await?;
|
wait_decommission_worker_drain(&workers, worker_limit).await?;
|
||||||
|
|
||||||
if let Some(err) = listing_worker_error {
|
if let Some(err) = resolve_decommission_listing_error(listing_worker_error, entry_error.lock().await.clone()) {
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(err) = entry_error.lock().await.clone() {
|
|
||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4188,7 +4341,7 @@ impl ECStore {
|
|||||||
let buckets = self.get_buckets_to_decommission().await?;
|
let buckets = self.get_buckets_to_decommission().await?;
|
||||||
let pool = self.pools[idx].clone();
|
let pool = self.pools[idx].clone();
|
||||||
|
|
||||||
for set in &pool.disk_set {
|
for (set_index, set) in pool.disk_set.iter().enumerate() {
|
||||||
for bucket_info in &buckets {
|
for bucket_info in &buckets {
|
||||||
let mut lifecycle_config = None;
|
let mut lifecycle_config = None;
|
||||||
let mut object_lock_config = None;
|
let mut object_lock_config = None;
|
||||||
@@ -4283,7 +4436,7 @@ impl ECStore {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let list_result = set
|
let list_result = set
|
||||||
.list_objects_to_decommission(callback_rx, bucket_info.clone(), callback)
|
.list_objects_to_decommission(callback_rx, bucket_info.clone(), callback, entry_error.clone(), idx, set_index)
|
||||||
.await;
|
.await;
|
||||||
let entry_error = entry_error.lock().await.clone();
|
let entry_error = entry_error.lock().await.clone();
|
||||||
resolve_decommission_check_after_list_result(list_result, entry_error)?;
|
resolve_decommission_check_after_list_result(list_result, entry_error)?;
|
||||||
@@ -5018,12 +5171,15 @@ mod tests {
|
|||||||
pub type ListCallback = Arc<dyn Fn(MetaCacheEntry) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
|
pub type ListCallback = Arc<dyn Fn(MetaCacheEntry) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
|
||||||
|
|
||||||
impl SetDisks {
|
impl SetDisks {
|
||||||
#[tracing::instrument(skip(self, rx, cb_func))]
|
#[tracing::instrument(skip(self, rx, cb_func, entry_error))]
|
||||||
async fn list_objects_to_decommission(
|
async fn list_objects_to_decommission(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
rx: CancellationToken,
|
rx: CancellationToken,
|
||||||
bucket_info: DecomBucketInfo,
|
bucket_info: DecomBucketInfo,
|
||||||
cb_func: ListCallback,
|
cb_func: ListCallback,
|
||||||
|
entry_error: Arc<tokio::sync::Mutex<Option<Error>>>,
|
||||||
|
pool_index: usize,
|
||||||
|
set_index: usize,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let (disks, _) = self.get_online_disks_with_healing(false).await;
|
let (disks, _) = self.get_online_disks_with_healing(false).await;
|
||||||
ensure_decommission_listing_disks_available(!disks.is_empty(), &bucket_info.name)?;
|
ensure_decommission_listing_disks_available(!disks.is_empty(), &bucket_info.name)?;
|
||||||
@@ -5038,6 +5194,12 @@ impl SetDisks {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let cb1 = cb_func.clone();
|
let cb1 = cb_func.clone();
|
||||||
|
let unresolved_error = entry_error.clone();
|
||||||
|
let unresolved_rx = rx.clone();
|
||||||
|
let unresolved_bucket = bucket_info.name.clone();
|
||||||
|
let unresolved_prefix = bucket_info.prefix.clone();
|
||||||
|
let unresolved_pool_index = pool_index;
|
||||||
|
let unresolved_set_index = set_index;
|
||||||
|
|
||||||
list_path_raw(
|
list_path_raw(
|
||||||
rx,
|
rx,
|
||||||
@@ -5047,21 +5209,54 @@ impl SetDisks {
|
|||||||
path: bucket_info.prefix.clone(),
|
path: bucket_info.prefix.clone(),
|
||||||
recursive: true,
|
recursive: true,
|
||||||
min_disks: listing_quorum,
|
min_disks: listing_quorum,
|
||||||
|
skip_walkdir_total_timeout: true,
|
||||||
|
walkdir_stall_timeout: Some(DECOMMISSION_BACKGROUND_WALKDIR_STALL_TIMEOUT),
|
||||||
agreed: Some(Box::new(move |entry: MetaCacheEntry| Box::pin(cb1(entry)))),
|
agreed: Some(Box::new(move |entry: MetaCacheEntry| Box::pin(cb1(entry)))),
|
||||||
partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
|
partial: Some(Box::new(move |entries: MetaCacheEntries, errs: &[Option<DiskError>]| {
|
||||||
let resolver = resolver.clone();
|
let resolver = resolver.clone();
|
||||||
let cb_func = cb_func.clone();
|
let cb_func = cb_func.clone();
|
||||||
match entries.resolve(resolver) {
|
let bucket = unresolved_bucket.clone();
|
||||||
Some(entry) => {
|
let prefix = unresolved_prefix.clone();
|
||||||
|
let unresolved_error = unresolved_error.clone();
|
||||||
|
let unresolved_rx = unresolved_rx.clone();
|
||||||
|
let pool_index = unresolved_pool_index;
|
||||||
|
let set_index = unresolved_set_index;
|
||||||
|
let disk_error_count = errs.iter().flatten().count();
|
||||||
|
if unresolved_rx.is_cancelled() {
|
||||||
|
return Box::pin(async {});
|
||||||
|
}
|
||||||
|
|
||||||
|
match resolve_decommission_partial_listing_entry(
|
||||||
|
entries,
|
||||||
|
resolver,
|
||||||
|
&bucket,
|
||||||
|
&prefix,
|
||||||
|
disk_error_count,
|
||||||
|
pool_index,
|
||||||
|
set_index,
|
||||||
|
) {
|
||||||
|
Ok(entry) => {
|
||||||
warn!("decommission_pool: list_objects_to_decommission get {}", &entry.name);
|
warn!("decommission_pool: list_objects_to_decommission get {}", &entry.name);
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
cb_func(entry).await;
|
cb_func(entry).await;
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
None => {
|
Err(err) => Box::pin(async move {
|
||||||
warn!("decommission_pool: list_objects_to_decommission get none");
|
if unresolved_rx.is_cancelled() {
|
||||||
Box::pin(async {})
|
return;
|
||||||
}
|
}
|
||||||
|
warn!(
|
||||||
|
event = EVENT_DECOMMISSION_BUCKET,
|
||||||
|
component = LOG_COMPONENT_ECSTORE,
|
||||||
|
subsystem = LOG_SUBSYSTEM_POOLS,
|
||||||
|
bucket = %bucket,
|
||||||
|
prefix = %prefix,
|
||||||
|
state = "unresolved_entry",
|
||||||
|
error = %err,
|
||||||
|
"Decommission listing failed closed on unresolved metadata"
|
||||||
|
);
|
||||||
|
record_decommission_entry_error(&unresolved_error, &unresolved_rx, err).await;
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
})),
|
})),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -5069,6 +5264,10 @@ impl SetDisks {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
if let Some(err) = entry_error.lock().await.clone() {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5259,11 +5458,11 @@ pub(crate) fn fallback_free_capacity_dedup(disks: &[rustfs_madmin::Disk]) -> usi
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod pools_tests {
|
mod pools_tests {
|
||||||
use super::{
|
use super::{
|
||||||
DECOMMISSION_PROGRESS_SAVE_INTERVAL, DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD, DecomBucketInfo,
|
DECOMMISSION_PROGRESS_SAVE_INTERVAL, DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD, DECOMMISSION_PROGRESS_SAVE_RETRY_BACKOFF,
|
||||||
DecommissionStartPoolState, DecommissionTerminalState, ListCallback, PoolDecommissionInfo, PoolMeta, PoolSpaceInfo,
|
DecomBucketInfo, DecommissionStartPoolState, DecommissionTerminalState, ListCallback, PoolDecommissionInfo, PoolMeta,
|
||||||
PoolStatus, apply_decommission_status_space_info, bind_decommission_cancelers, bind_missing_decommission_cancelers,
|
PoolSpaceInfo, PoolStatus, apply_decommission_status_space_info, bind_decommission_cancelers,
|
||||||
cancel_decommission_canceler, classify_decommission_terminal_state, count_decommission_item,
|
bind_missing_decommission_cancelers, cancel_decommission_canceler, classify_decommission_terminal_state,
|
||||||
decommission_cancel_signal_result, decommission_item_size, decommission_meta_bucket_options,
|
count_decommission_item, decommission_cancel_signal_result, decommission_item_size, decommission_meta_bucket_options,
|
||||||
decommission_start_pool_state, dedup_indices, default_decommission_bucket_concurrency,
|
decommission_start_pool_state, dedup_indices, default_decommission_bucket_concurrency,
|
||||||
ensure_decommission_cancel_allowed, ensure_decommission_clear_allowed, ensure_decommission_listing_disks_available,
|
ensure_decommission_cancel_allowed, ensure_decommission_clear_allowed, ensure_decommission_listing_disks_available,
|
||||||
ensure_decommission_not_rebalancing, ensure_decommission_start_allowed, ensure_decommission_start_keeps_active_pool,
|
ensure_decommission_not_rebalancing, ensure_decommission_start_allowed, ensure_decommission_start_keeps_active_pool,
|
||||||
@@ -5274,11 +5473,12 @@ mod pools_tests {
|
|||||||
has_active_decommission_canceler, is_decommission_active, is_decommission_cancel_requested,
|
has_active_decommission_canceler, is_decommission_active, is_decommission_cancel_requested,
|
||||||
load_decommission_entry_versions, local_decommission_queue_prefix, mark_decommission_bucket_done,
|
load_decommission_entry_versions, local_decommission_queue_prefix, mark_decommission_bucket_done,
|
||||||
merge_pool_status_refresh, missing_decommission_worker_prefix, observe_decommission_terminal_reload_result,
|
merge_pool_status_refresh, missing_decommission_worker_prefix, observe_decommission_terminal_reload_result,
|
||||||
pool_meta_has_active_decommission, require_decommission_store, resolve_decommission_bucket_done_save_result,
|
pool_meta_has_active_decommission, record_decommission_entry_error, require_decommission_store,
|
||||||
resolve_decommission_bucket_state, resolve_decommission_check_after_list_result,
|
resolve_decommission_bucket_done_save_result, resolve_decommission_bucket_state,
|
||||||
resolve_decommission_entry_cleanup_delete_result, resolve_decommission_entry_exact_versions,
|
resolve_decommission_check_after_list_result, resolve_decommission_entry_cleanup_delete_result,
|
||||||
resolve_decommission_entry_reload_result, resolve_decommission_listing_worker_result,
|
resolve_decommission_entry_exact_versions, resolve_decommission_entry_reload_result, resolve_decommission_listing_error,
|
||||||
resolve_decommission_optional_bucket_config_result, resolve_decommission_pool_meta_reload_result,
|
resolve_decommission_listing_worker_result, resolve_decommission_optional_bucket_config_result,
|
||||||
|
resolve_decommission_partial_listing_entry, resolve_decommission_pool_meta_reload_result,
|
||||||
resolve_decommission_preflight_heal_result, resolve_decommission_progress_save_result,
|
resolve_decommission_preflight_heal_result, resolve_decommission_progress_save_result,
|
||||||
resolve_decommission_spawn_failure_result, resolve_decommission_terminal_mark_after_error_result,
|
resolve_decommission_spawn_failure_result, resolve_decommission_terminal_mark_after_error_result,
|
||||||
resolve_decommission_terminal_mark_result, resolve_decommission_update_after_result,
|
resolve_decommission_terminal_mark_result, resolve_decommission_update_after_result,
|
||||||
@@ -5288,16 +5488,17 @@ mod pools_tests {
|
|||||||
should_preserve_decommission_canceled_state, should_reject_decommission_cancel_as_terminal,
|
should_preserve_decommission_canceled_state, should_reject_decommission_cancel_as_terminal,
|
||||||
should_retry_decommission_cancel_reload, should_retry_decommission_listing, should_skip_canceled_decommission_routine,
|
should_retry_decommission_cancel_reload, should_retry_decommission_listing, should_skip_canceled_decommission_routine,
|
||||||
split_decommission_buckets, take_and_cancel_decommission_canceler, take_decommission_canceler,
|
split_decommission_buckets, take_and_cancel_decommission_canceler, take_decommission_canceler,
|
||||||
touch_decommission_progress, track_decommission_current_object, track_decommission_current_object_stage,
|
track_decommission_current_object, track_decommission_current_object_stage, validate_start_decommission_request,
|
||||||
validate_start_decommission_request, wait_decommission_listing_retry, wait_decommission_worker_drain,
|
wait_decommission_listing_retry, wait_decommission_worker_drain, with_decommission_entry_context,
|
||||||
with_decommission_entry_context,
|
|
||||||
};
|
};
|
||||||
use crate::data_movement;
|
use crate::data_movement;
|
||||||
use crate::disk::endpoint::Endpoint;
|
use crate::disk::endpoint::Endpoint;
|
||||||
use crate::error::{Error, StorageError};
|
use crate::error::{Error, StorageError};
|
||||||
use crate::layout::endpoints::{EndpointServerPools, Endpoints, PoolEndpoints};
|
use crate::layout::endpoints::{EndpointServerPools, Endpoints, PoolEndpoints};
|
||||||
use crate::services::rebalance::{RebalStatus, RebalanceInfo, RebalanceMeta, RebalanceStats};
|
use crate::services::rebalance::{RebalStatus, RebalanceInfo, RebalanceMeta, RebalanceStats};
|
||||||
use rustfs_filemeta::{FileInfo, FileInfoVersions, MetaCacheEntry, ObjectPartInfo};
|
use rustfs_filemeta::{
|
||||||
|
FileInfo, FileInfoVersions, MetaCacheEntries, MetaCacheEntry, MetadataResolutionParams, ObjectPartInfo,
|
||||||
|
};
|
||||||
use rustfs_rio::Index;
|
use rustfs_rio::Index;
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
Arc,
|
Arc,
|
||||||
@@ -6316,6 +6517,65 @@ mod pools_tests {
|
|||||||
assert!(matches!(err, Error::SlowDown));
|
assert!(matches!(err, Error::SlowDown));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_resolve_decommission_partial_listing_entry_rejects_unresolved_metadata() {
|
||||||
|
let err = resolve_decommission_partial_listing_entry(
|
||||||
|
MetaCacheEntries(vec![None]),
|
||||||
|
MetadataResolutionParams {
|
||||||
|
dir_quorum: 2,
|
||||||
|
obj_quorum: 2,
|
||||||
|
bucket: "bucket-a".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
"bucket-a",
|
||||||
|
"prefix/",
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
)
|
||||||
|
.expect_err("unresolved partial listing must fail closed");
|
||||||
|
|
||||||
|
let message = err.to_string();
|
||||||
|
assert!(message.contains("decommission listing could not resolve metadata"));
|
||||||
|
assert!(message.contains("bucket-a/prefix/"));
|
||||||
|
assert!(message.contains("pool 2 set 3"));
|
||||||
|
assert!(message.contains("1 disk error(s)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_record_decommission_entry_error_cancels_listing_and_preserves_first_error() {
|
||||||
|
let entry_error = Arc::new(tokio::sync::Mutex::new(None));
|
||||||
|
let rx = CancellationToken::new();
|
||||||
|
|
||||||
|
record_decommission_entry_error(&entry_error, &rx, Error::SlowDown).await;
|
||||||
|
record_decommission_entry_error(&entry_error, &rx, Error::OperationCanceled).await;
|
||||||
|
|
||||||
|
assert!(rx.is_cancelled());
|
||||||
|
assert!(matches!(*entry_error.lock().await, Some(Error::SlowDown)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_record_decommission_entry_error_ignores_already_canceled_listing() {
|
||||||
|
let entry_error = Arc::new(tokio::sync::Mutex::new(None));
|
||||||
|
let rx = CancellationToken::new();
|
||||||
|
rx.cancel();
|
||||||
|
|
||||||
|
record_decommission_entry_error(&entry_error, &rx, Error::SlowDown).await;
|
||||||
|
|
||||||
|
assert!(entry_error.lock().await.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_resolve_decommission_listing_error_preserves_real_listing_failure() {
|
||||||
|
let err = resolve_decommission_listing_error(Some(Error::SlowDown), Some(Error::OperationCanceled))
|
||||||
|
.expect("listing failure should be returned");
|
||||||
|
assert!(matches!(err, Error::SlowDown));
|
||||||
|
|
||||||
|
let err = resolve_decommission_listing_error(Some(Error::OperationCanceled), Some(Error::SlowDown))
|
||||||
|
.expect("entry failure should be returned");
|
||||||
|
assert!(matches!(err, Error::SlowDown));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_resolve_decommission_check_after_list_result_returns_list_result_without_entry_error() {
|
fn test_resolve_decommission_check_after_list_result_returns_list_result_without_entry_error() {
|
||||||
let err = resolve_decommission_check_after_list_result(Err(Error::OperationCanceled), None)
|
let err = resolve_decommission_check_after_list_result(Err(Error::OperationCanceled), None)
|
||||||
@@ -6533,7 +6793,7 @@ mod pools_tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_touch_decommission_progress_updates_last_update_and_save_baseline() {
|
fn test_track_decommission_stage_does_not_advance_checkpoint_state() {
|
||||||
let mut meta = PoolMeta {
|
let mut meta = PoolMeta {
|
||||||
pools: vec![PoolStatus {
|
pools: vec![PoolStatus {
|
||||||
id: 0,
|
id: 0,
|
||||||
@@ -6548,11 +6808,13 @@ mod pools_tests {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
touch_decommission_progress(&mut meta, 0).expect("valid decommission progress should be touched");
|
track_decommission_current_object_stage(&mut meta, 0, "bucket", "object", "migrate_object")
|
||||||
|
.expect("valid decommission progress should be tracked");
|
||||||
|
|
||||||
assert!(meta.pools[0].last_update > OffsetDateTime::UNIX_EPOCH);
|
assert_eq!(meta.pools[0].last_update, OffsetDateTime::UNIX_EPOCH);
|
||||||
let info = meta.pools[0].decommission.as_ref().expect("decommission info should exist");
|
let info = meta.pools[0].decommission.as_ref().expect("decommission info should exist");
|
||||||
assert_eq!(info.items_since_last_progress_save(), 0);
|
assert_eq!(info.items_since_last_progress_save(), 5);
|
||||||
|
assert_eq!(info.stage, "migrate_object");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -6627,6 +6889,134 @@ mod pools_tests {
|
|||||||
assert_eq!(info.items_since_last_progress_save(), 1);
|
assert_eq!(info.items_since_last_progress_save(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_pool_meta_update_after_does_not_advance_last_update_before_save() {
|
||||||
|
let last_update = OffsetDateTime::UNIX_EPOCH;
|
||||||
|
let mut meta = PoolMeta {
|
||||||
|
pools: vec![PoolStatus {
|
||||||
|
id: 0,
|
||||||
|
cmd_line: "pool-0".to_string(),
|
||||||
|
last_update,
|
||||||
|
decommission: Some(PoolDecommissionInfo {
|
||||||
|
start_time: Some(last_update),
|
||||||
|
items_decommissioned: DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
meta.update_after(0, DECOMMISSION_PROGRESS_SAVE_INTERVAL)
|
||||||
|
.expect("item threshold should request a checkpoint")
|
||||||
|
);
|
||||||
|
assert_eq!(meta.pools[0].last_update, last_update);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decommission_progress_checkpoint_commits_exact_snapshot_watermark() {
|
||||||
|
let start_time = OffsetDateTime::UNIX_EPOCH;
|
||||||
|
let checkpoint_at = start_time + Duration::seconds(30);
|
||||||
|
let mut meta = PoolMeta {
|
||||||
|
pools: vec![PoolStatus {
|
||||||
|
id: 0,
|
||||||
|
cmd_line: "pool-0".to_string(),
|
||||||
|
last_update: start_time,
|
||||||
|
decommission: Some(PoolDecommissionInfo {
|
||||||
|
start_time: Some(start_time),
|
||||||
|
items_decommissioned: DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let checkpoint = meta
|
||||||
|
.decommission_progress_checkpoint(0, DECOMMISSION_PROGRESS_SAVE_INTERVAL, checkpoint_at)
|
||||||
|
.expect("valid decommission state should produce a checkpoint")
|
||||||
|
.expect("item threshold should produce a checkpoint");
|
||||||
|
meta.count_item(0, 1, false);
|
||||||
|
|
||||||
|
assert!(meta.commit_decommission_progress_checkpoint(0, checkpoint));
|
||||||
|
let info = meta.pools[0].decommission.as_ref().expect("decommission info should exist");
|
||||||
|
assert_eq!(info.progress_save_item_baseline, checkpoint.counted_items);
|
||||||
|
assert_eq!(info.items_since_last_progress_save(), 1);
|
||||||
|
assert_eq!(meta.pools[0].last_update, checkpoint_at);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decommission_progress_checkpoint_backoff_does_not_advance_baseline() {
|
||||||
|
let start_time = OffsetDateTime::UNIX_EPOCH;
|
||||||
|
let checkpoint_at = start_time + Duration::seconds(30);
|
||||||
|
let retry_after = checkpoint_at + DECOMMISSION_PROGRESS_SAVE_RETRY_BACKOFF;
|
||||||
|
let mut meta = PoolMeta {
|
||||||
|
pools: vec![PoolStatus {
|
||||||
|
id: 0,
|
||||||
|
cmd_line: "pool-0".to_string(),
|
||||||
|
last_update: start_time,
|
||||||
|
decommission: Some(PoolDecommissionInfo {
|
||||||
|
start_time: Some(start_time),
|
||||||
|
items_decommissioned: DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let checkpoint = meta
|
||||||
|
.decommission_progress_checkpoint(0, DECOMMISSION_PROGRESS_SAVE_INTERVAL, checkpoint_at)
|
||||||
|
.expect("valid decommission state should produce a checkpoint")
|
||||||
|
.expect("item threshold should produce a checkpoint");
|
||||||
|
meta.defer_decommission_progress_checkpoint(0, checkpoint, retry_after);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
meta.decommission_progress_checkpoint(0, DECOMMISSION_PROGRESS_SAVE_INTERVAL, checkpoint_at)
|
||||||
|
.expect("retry backoff check should succeed")
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
assert_eq!(meta.pools[0].last_update, start_time);
|
||||||
|
assert_eq!(
|
||||||
|
meta.pools[0]
|
||||||
|
.decommission
|
||||||
|
.as_ref()
|
||||||
|
.expect("decommission info should exist")
|
||||||
|
.progress_save_item_baseline,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decommission_progress_checkpoint_count_scales_with_threshold() {
|
||||||
|
let start_time = OffsetDateTime::UNIX_EPOCH;
|
||||||
|
let checkpoint_at = start_time;
|
||||||
|
let mut meta = PoolMeta {
|
||||||
|
pools: vec![PoolStatus {
|
||||||
|
id: 0,
|
||||||
|
cmd_line: "pool-0".to_string(),
|
||||||
|
last_update: start_time,
|
||||||
|
decommission: Some(PoolDecommissionInfo {
|
||||||
|
start_time: Some(start_time),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut checkpoint_count = 0;
|
||||||
|
|
||||||
|
for _ in 0..(DECOMMISSION_PROGRESS_SAVE_ITEM_THRESHOLD * 10) {
|
||||||
|
meta.count_item(0, 1, false);
|
||||||
|
if let Some(checkpoint) = meta
|
||||||
|
.decommission_progress_checkpoint(0, DECOMMISSION_PROGRESS_SAVE_INTERVAL, checkpoint_at)
|
||||||
|
.expect("valid decommission state should produce a checkpoint")
|
||||||
|
{
|
||||||
|
checkpoint_count += 1;
|
||||||
|
assert!(meta.commit_decommission_progress_checkpoint(0, checkpoint));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(checkpoint_count, 10);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ensure_decommission_not_rebalancing_rejects_running_rebalance() {
|
fn test_ensure_decommission_not_rebalancing_rejects_running_rebalance() {
|
||||||
let err = ensure_decommission_not_rebalancing(true).expect_err("rebalance running should be rejected");
|
let err = ensure_decommission_not_rebalancing(true).expect_err("rebalance running should be rejected");
|
||||||
|
|||||||
@@ -249,7 +249,7 @@ impl Sets {
|
|||||||
|
|
||||||
self.connect_disks().await;
|
self.connect_disks().await;
|
||||||
|
|
||||||
// TODO: config interval
|
// TODO(backlog): make monitor_and_connect interval configurable instead of hardcoded 15s
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(15));
|
let mut interval = tokio::time::interval(Duration::from_secs(15));
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
|
|||||||
@@ -5215,8 +5215,8 @@ impl LocalDisk {
|
|||||||
|
|
||||||
let cache = Cache::new(update_fn, Duration::from_secs(1), Opts::default());
|
let cache = Cache::new(update_fn, Duration::from_secs(1), Opts::default());
|
||||||
|
|
||||||
// TODO: DIRECT support
|
// TODO(backlog): add O_DIRECT I/O support for performance-critical paths
|
||||||
// TODD: DiskInfo
|
// TODO(backlog): populate DiskInfo in constructor
|
||||||
let mut disk = Self {
|
let mut disk = Self {
|
||||||
root: root.clone(),
|
root: root.clone(),
|
||||||
publication_root,
|
publication_root,
|
||||||
@@ -5751,7 +5751,7 @@ impl LocalDisk {
|
|||||||
|
|
||||||
// return Ok(());
|
// return Ok(());
|
||||||
|
|
||||||
// TODO: async notifications for disk space checks and trash cleanup
|
// TODO(backlog): make disk space checks and trash cleanup event-driven instead of poll-based
|
||||||
|
|
||||||
let trash_path = self.io_get_object_path(RUSTFS_META_TMP_DELETED_BUCKET, Uuid::new_v4().to_string().as_str())?;
|
let trash_path = self.io_get_object_path(RUSTFS_META_TMP_DELETED_BUCKET, Uuid::new_v4().to_string().as_str())?;
|
||||||
// if let Some(parent) = trash_path.parent() {
|
// if let Some(parent) = trash_path.parent() {
|
||||||
@@ -5997,7 +5997,7 @@ impl LocalDisk {
|
|||||||
|
|
||||||
#[hotpath::measure(impl_type = "LocalDisk")]
|
#[hotpath::measure(impl_type = "LocalDisk")]
|
||||||
async fn read_all_data(&self, volume: &str, volume_dir: impl AsRef<Path>, file_path: impl AsRef<Path>) -> Result<Vec<u8>> {
|
async fn read_all_data(&self, volume: &str, volume_dir: impl AsRef<Path>, file_path: impl AsRef<Path>) -> Result<Vec<u8>> {
|
||||||
// TODO: timeout support
|
// TODO(backlog): add configurable timeout for read_all_data operations
|
||||||
let (data, _) = self.read_all_data_with_dmtime(volume, volume_dir, file_path).await?;
|
let (data, _) = self.read_all_data_with_dmtime(volume, volume_dir, file_path).await?;
|
||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
@@ -6674,7 +6674,7 @@ impl LocalDisk {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: add lock
|
// TODO(backlog): add directory listing lock to prevent concurrent enumeration
|
||||||
|
|
||||||
let stall = opts.stall_timeout_duration();
|
let stall = opts.stall_timeout_duration();
|
||||||
|
|
||||||
@@ -8796,7 +8796,7 @@ impl DiskAPI for LocalDisk {
|
|||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: TODO: io.writer TODO cancel
|
// TODO(backlog): support io.writer cancellation and early termination in walk_dir
|
||||||
#[tracing::instrument(level = "trace", skip_all)]
|
#[tracing::instrument(level = "trace", skip_all)]
|
||||||
async fn walk_dir<W: AsyncWrite + Unpin + Send>(&self, opts: WalkDirOptions, wr: &mut W) -> Result<()> {
|
async fn walk_dir<W: AsyncWrite + Unpin + Send>(&self, opts: WalkDirOptions, wr: &mut W) -> Result<()> {
|
||||||
self.wait_for_startup_cleanup().await;
|
self.wait_for_startup_cleanup().await;
|
||||||
@@ -9880,7 +9880,7 @@ impl DiskAPI for LocalDisk {
|
|||||||
);
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
// TODO: health check
|
// TODO(backlog): add post-setup disk health verification
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use std::{
|
|||||||
io,
|
io,
|
||||||
path::{Component, Path, PathBuf},
|
path::{Component, Path, PathBuf},
|
||||||
sync::{Arc, LazyLock, Weak},
|
sync::{Arc, LazyLock, Weak},
|
||||||
time::Instant,
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
use tokio::sync::{
|
use tokio::sync::{
|
||||||
@@ -315,7 +315,7 @@ pub async fn fsync_dir(dir: impl AsRef<Path>) -> io::Result<()> {
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
let dir = dir.as_ref().to_path_buf();
|
let dir = dir.as_ref().to_path_buf();
|
||||||
tokio::task::spawn_blocking(move || fsync_dir_std(dir)).await?
|
fsync_spawn_blocking(move || fsync_dir_std(dir)).await?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
#[cfg(not(unix))]
|
||||||
@@ -328,6 +328,9 @@ const ENV_DST_DIR_FSYNC_GROUP_COMMIT_ENABLE: &str = "RUSTFS_EXPERIMENTAL_DST_DIR
|
|||||||
const DEFAULT_DST_DIR_FSYNC_GROUP_COMMIT_ENABLE: bool = false;
|
const DEFAULT_DST_DIR_FSYNC_GROUP_COMMIT_ENABLE: bool = false;
|
||||||
const ENV_FILE_FDATASYNC_GROUP_COMMIT_ENABLE: &str = "RUSTFS_EXPERIMENTAL_FILE_FDATASYNC_GROUP_COMMIT_ENABLE";
|
const ENV_FILE_FDATASYNC_GROUP_COMMIT_ENABLE: &str = "RUSTFS_EXPERIMENTAL_FILE_FDATASYNC_GROUP_COMMIT_ENABLE";
|
||||||
const DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_ENABLE: bool = false;
|
const DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_ENABLE: bool = false;
|
||||||
|
const ENV_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS: &str = "RUSTFS_EXPERIMENTAL_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS";
|
||||||
|
const DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS: u64 = 0;
|
||||||
|
const MAX_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS: u64 = 1_000;
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
const MAX_DST_DIR_FSYNC_GROUPS: usize = 1024;
|
const MAX_DST_DIR_FSYNC_GROUPS: usize = 1024;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -354,6 +357,16 @@ static DST_DIR_FSYNC_GROUP_COMMIT_ENABLED: LazyLock<bool> = LazyLock::new(|| {
|
|||||||
static FILE_FDATASYNC_GROUP_COMMIT_ENABLED: LazyLock<bool> = LazyLock::new(|| {
|
static FILE_FDATASYNC_GROUP_COMMIT_ENABLED: LazyLock<bool> = LazyLock::new(|| {
|
||||||
rustfs_utils::get_env_bool(ENV_FILE_FDATASYNC_GROUP_COMMIT_ENABLE, DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_ENABLE)
|
rustfs_utils::get_env_bool(ENV_FILE_FDATASYNC_GROUP_COMMIT_ENABLE, DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_ENABLE)
|
||||||
});
|
});
|
||||||
|
fn file_fdatasync_group_commit_wait_duration(wait_micros: u64) -> Duration {
|
||||||
|
Duration::from_micros(wait_micros.min(MAX_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS))
|
||||||
|
}
|
||||||
|
|
||||||
|
static FILE_FDATASYNC_GROUP_COMMIT_WAIT: LazyLock<Duration> = LazyLock::new(|| {
|
||||||
|
file_fdatasync_group_commit_wait_duration(rustfs_utils::get_env_u64(
|
||||||
|
ENV_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS,
|
||||||
|
DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS,
|
||||||
|
))
|
||||||
|
});
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod dst_dir_fsync_group_commit_override {
|
mod dst_dir_fsync_group_commit_override {
|
||||||
@@ -402,6 +415,7 @@ mod file_fdatasync_group_commit_override {
|
|||||||
use std::sync::{Mutex, MutexGuard, PoisonError, RwLock};
|
use std::sync::{Mutex, MutexGuard, PoisonError, RwLock};
|
||||||
|
|
||||||
static OVERRIDE: RwLock<Option<bool>> = RwLock::new(None);
|
static OVERRIDE: RwLock<Option<bool>> = RwLock::new(None);
|
||||||
|
static WAIT_OVERRIDE_MICROS: RwLock<Option<u64>> = RwLock::new(None);
|
||||||
static SERIAL: Mutex<()> = Mutex::new(());
|
static SERIAL: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
pub(crate) fn get() -> Option<bool> {
|
pub(crate) fn get() -> Option<bool> {
|
||||||
@@ -415,6 +429,7 @@ mod file_fdatasync_group_commit_override {
|
|||||||
impl Drop for OverrideGuard {
|
impl Drop for OverrideGuard {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
*OVERRIDE.write().unwrap_or_else(PoisonError::into_inner) = None;
|
*OVERRIDE.write().unwrap_or_else(PoisonError::into_inner) = None;
|
||||||
|
*WAIT_OVERRIDE_MICROS.write().unwrap_or_else(PoisonError::into_inner) = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,6 +438,14 @@ mod file_fdatasync_group_commit_override {
|
|||||||
*OVERRIDE.write().unwrap_or_else(PoisonError::into_inner) = Some(enabled);
|
*OVERRIDE.write().unwrap_or_else(PoisonError::into_inner) = Some(enabled);
|
||||||
OverrideGuard { _serial: serial }
|
OverrideGuard { _serial: serial }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_wait_micros(wait_micros: u64) {
|
||||||
|
*WAIT_OVERRIDE_MICROS.write().unwrap_or_else(PoisonError::into_inner) = Some(wait_micros);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn wait_micros() -> Option<u64> {
|
||||||
|
*WAIT_OVERRIDE_MICROS.read().unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -430,6 +453,11 @@ pub(crate) fn set_file_fdatasync_group_commit_for_test(enabled: bool) -> file_fd
|
|||||||
file_fdatasync_group_commit_override::set(enabled)
|
file_fdatasync_group_commit_override::set(enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn set_file_fdatasync_group_commit_wait_for_test(wait_micros: u64) {
|
||||||
|
file_fdatasync_group_commit_override::set_wait_micros(wait_micros);
|
||||||
|
}
|
||||||
|
|
||||||
fn file_fdatasync_group_commit_enabled() -> bool {
|
fn file_fdatasync_group_commit_enabled() -> bool {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
if let Some(enabled) = file_fdatasync_group_commit_override::get() {
|
if let Some(enabled) = file_fdatasync_group_commit_override::get() {
|
||||||
@@ -439,6 +467,15 @@ fn file_fdatasync_group_commit_enabled() -> bool {
|
|||||||
*FILE_FDATASYNC_GROUP_COMMIT_ENABLED
|
*FILE_FDATASYNC_GROUP_COMMIT_ENABLED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn file_fdatasync_group_commit_wait() -> Duration {
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(wait_micros) = file_fdatasync_group_commit_override::wait_micros() {
|
||||||
|
return file_fdatasync_group_commit_wait_duration(wait_micros);
|
||||||
|
}
|
||||||
|
|
||||||
|
*FILE_FDATASYNC_GROUP_COMMIT_WAIT
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Eq, Hash, PartialEq)]
|
#[derive(Clone, Eq, Hash, PartialEq)]
|
||||||
struct DstDirFsyncGroupKey {
|
struct DstDirFsyncGroupKey {
|
||||||
canonical_path: PathBuf,
|
canonical_path: PathBuf,
|
||||||
@@ -646,7 +683,7 @@ async fn fsync_open_dst_dir_group(group: &DstDirFsyncGroup) -> io::Result<()> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
let dir = group.dir.clone();
|
let dir = group.dir.clone();
|
||||||
let dir_file = group.dir_file.clone();
|
let dir_file = group.dir_file.clone();
|
||||||
tokio::task::spawn_blocking(move || {
|
fsync_spawn_blocking(move || {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
{
|
{
|
||||||
if let Some(kind) = fsync_dir_recorder::take_grouped_failure(&dir) {
|
if let Some(kind) = fsync_dir_recorder::take_grouped_failure(&dir) {
|
||||||
@@ -934,6 +971,10 @@ async fn run_file_fdatasync_group_worker(group: Arc<FileFdatasyncGroup>) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
file_sync_probe::run_before_group_batch();
|
file_sync_probe::run_before_group_batch();
|
||||||
tokio::task::yield_now().await;
|
tokio::task::yield_now().await;
|
||||||
|
let wait = file_fdatasync_group_commit_wait();
|
||||||
|
if !wait.is_zero() {
|
||||||
|
tokio::time::sleep(wait).await;
|
||||||
|
}
|
||||||
let (batch, batch_file_count): (Vec<FileFdatasyncWaiter>, usize) = {
|
let (batch, batch_file_count): (Vec<FileFdatasyncWaiter>, usize) = {
|
||||||
let mut group_state = group.inner.lock();
|
let mut group_state = group.inner.lock();
|
||||||
let batch_file_count = group_state.pending_files;
|
let batch_file_count = group_state.pending_files;
|
||||||
@@ -1039,6 +1080,44 @@ const TEST_GLOBAL_FILE_SYNCS: usize = 64;
|
|||||||
|
|
||||||
static FILE_SYNC_PERMITS: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(global_file_sync_limit()));
|
static FILE_SYNC_PERMITS: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(global_file_sync_limit()));
|
||||||
static DISK_FILE_SYNC_LIMITERS: LazyLock<Mutex<HashMap<PathBuf, Weak<Semaphore>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
static DISK_FILE_SYNC_LIMITERS: LazyLock<Mutex<HashMap<PathBuf, Weak<Semaphore>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
/// Dedicated tokio runtime for fsync/fdatasync blocking operations. When
|
||||||
|
/// configured with >1 threads, isolates device-bound fsync from the main
|
||||||
|
/// blocking pool so reads (pread/stat/open) are not starved. `None` means
|
||||||
|
/// fall back to the main runtime (zero behavior change).
|
||||||
|
static FSYNC_RUNTIME: LazyLock<Option<tokio::runtime::Runtime>> = LazyLock::new(|| {
|
||||||
|
let threads =
|
||||||
|
rustfs_utils::get_env_usize(rustfs_config::ENV_FSYNC_BLOCKING_THREADS, rustfs_config::DEFAULT_FSYNC_BLOCKING_THREADS);
|
||||||
|
if threads <= 1 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut builder = tokio::runtime::Builder::new_multi_thread();
|
||||||
|
builder
|
||||||
|
.worker_threads(num_cpus::get().min(8))
|
||||||
|
.max_blocking_threads(threads)
|
||||||
|
.thread_name("rustfs-fsync")
|
||||||
|
.thread_stack_size(512 * 1024)
|
||||||
|
.enable_all();
|
||||||
|
match builder.build() {
|
||||||
|
Ok(rt) => {
|
||||||
|
tracing::info!(threads, "fsync dedicated blocking pool enabled");
|
||||||
|
Some(rt)
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
tracing::warn!(%err, "failed to build fsync runtime, falling back to main pool");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Spawn a blocking task on the fsync-dedicated runtime if configured,
|
||||||
|
/// otherwise fall back to the main tokio blocking pool.
|
||||||
|
fn fsync_spawn_blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> tokio::task::JoinHandle<T> {
|
||||||
|
match FSYNC_RUNTIME.as_ref() {
|
||||||
|
Some(rt) => rt.spawn_blocking(f),
|
||||||
|
None => tokio::task::spawn_blocking(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
static DISK_VOLUME_MUTATION_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Weak<RwLock<()>>>>> =
|
static DISK_VOLUME_MUTATION_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Weak<RwLock<()>>>>> =
|
||||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
type NamespaceMutationLock = AsyncMutex<()>;
|
type NamespaceMutationLock = AsyncMutex<()>;
|
||||||
@@ -1176,7 +1255,7 @@ where
|
|||||||
F: FnOnce() -> io::Result<T> + Send + 'static,
|
F: FnOnce() -> io::Result<T> + Send + 'static,
|
||||||
{
|
{
|
||||||
let (disk_permit, global_permit) = acquire_file_sync_permits(disk_permits).await?;
|
let (disk_permit, global_permit) = acquire_file_sync_permits(disk_permits).await?;
|
||||||
let result = tokio::task::spawn_blocking(move || {
|
let result = fsync_spawn_blocking(move || {
|
||||||
let _disk_permit = disk_permit;
|
let _disk_permit = disk_permit;
|
||||||
work()
|
work()
|
||||||
})
|
})
|
||||||
@@ -2105,7 +2184,7 @@ async fn run_blocking_namespace_file_sync_operation_with_global<T: Send + 'stati
|
|||||||
wait_started,
|
wait_started,
|
||||||
);
|
);
|
||||||
let disk_permit = admission.disk_permit.clone();
|
let disk_permit = admission.disk_permit.clone();
|
||||||
let result = tokio::task::spawn_blocking(move || {
|
let result = fsync_spawn_blocking(move || {
|
||||||
let _lease = lease;
|
let _lease = lease;
|
||||||
let _disk_permit = disk_permit;
|
let _disk_permit = disk_permit;
|
||||||
operation()
|
operation()
|
||||||
@@ -6075,6 +6154,7 @@ mod tests {
|
|||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
|
|
||||||
let _group_commit = set_file_fdatasync_group_commit_for_test(true);
|
let _group_commit = set_file_fdatasync_group_commit_for_test(true);
|
||||||
|
set_file_fdatasync_group_commit_wait_for_test(0);
|
||||||
clear_file_fdatasync_group_commit_for_test();
|
clear_file_fdatasync_group_commit_for_test();
|
||||||
let temp_dir = tempdir().expect("create temp dir");
|
let temp_dir = tempdir().expect("create temp dir");
|
||||||
let first_dir = temp_dir.path().join("first");
|
let first_dir = temp_dir.path().join("first");
|
||||||
@@ -6141,12 +6221,105 @@ mod tests {
|
|||||||
assert_eq!(file_fdatasync_group_commit_counts_for_test(), (0, 0, 0));
|
assert_eq!(file_fdatasync_group_commit_counts_for_test(), (0, 0, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn file_fdatasync_group_commit_wait_duration_uses_default_and_cap() {
|
||||||
|
assert_eq!(DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS, 0);
|
||||||
|
assert_eq!(
|
||||||
|
file_fdatasync_group_commit_wait_duration(DEFAULT_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS),
|
||||||
|
Duration::ZERO
|
||||||
|
);
|
||||||
|
assert_eq!(file_fdatasync_group_commit_wait_duration(250), Duration::from_micros(250));
|
||||||
|
assert_eq!(
|
||||||
|
file_fdatasync_group_commit_wait_duration(MAX_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS),
|
||||||
|
Duration::from_micros(MAX_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
file_fdatasync_group_commit_wait_duration(u64::MAX),
|
||||||
|
Duration::from_micros(MAX_FILE_FDATASYNC_GROUP_COMMIT_WAIT_MICROS)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "current_thread", start_paused = true)]
|
||||||
|
#[serial_test::serial(file_sync_probe)]
|
||||||
|
async fn file_fdatasync_group_commit_wait_budget_batches_late_follower() {
|
||||||
|
use std::sync::mpsc;
|
||||||
|
|
||||||
|
let _group_commit = set_file_fdatasync_group_commit_for_test(true);
|
||||||
|
let wait_budget_micros = 1_000;
|
||||||
|
let wait_budget = file_fdatasync_group_commit_wait_duration(wait_budget_micros);
|
||||||
|
set_file_fdatasync_group_commit_wait_for_test(wait_budget_micros);
|
||||||
|
clear_file_fdatasync_group_commit_for_test();
|
||||||
|
let temp_dir = tempdir().expect("create temp dir");
|
||||||
|
let first_dir = temp_dir.path().join("first");
|
||||||
|
let second_dir = temp_dir.path().join("second");
|
||||||
|
std::fs::create_dir(&first_dir).expect("create first dir");
|
||||||
|
std::fs::create_dir(&second_dir).expect("create second dir");
|
||||||
|
std::fs::write(first_dir.join("part.1"), b"first").expect("write first part");
|
||||||
|
std::fs::write(second_dir.join("part.1"), b"second").expect("write second part");
|
||||||
|
let _probe = file_sync_probe::set_blocking(temp_dir.path());
|
||||||
|
let (entered_tx, entered_rx) = mpsc::channel();
|
||||||
|
file_sync_probe::set_before_group_batch(move || {
|
||||||
|
entered_tx.send(()).expect("signal first file fdatasync group worker");
|
||||||
|
});
|
||||||
|
|
||||||
|
let limiter = file_sync_limiter();
|
||||||
|
let first_limiter = limiter.clone();
|
||||||
|
let first_path = first_dir.clone();
|
||||||
|
let first = tokio::spawn(async move { sync_dir_files_with_limiter(first_path, first_limiter).await });
|
||||||
|
tokio::task::spawn_blocking(move || entered_rx.recv_timeout(Duration::from_secs(30)))
|
||||||
|
.await
|
||||||
|
.expect("group worker hook waiter should run")
|
||||||
|
.expect("first file fdatasync group worker should start");
|
||||||
|
|
||||||
|
let second_limiter = limiter.clone();
|
||||||
|
let second_path = second_dir.clone();
|
||||||
|
let second = tokio::spawn(async move { sync_dir_files_with_limiter(second_path, second_limiter).await });
|
||||||
|
tokio::time::timeout(Duration::from_secs(30), async {
|
||||||
|
loop {
|
||||||
|
if file_fdatasync_group_commit_counts_for_test().1 == 2 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("second waiter should enqueue during the configured wait budget");
|
||||||
|
tokio::time::advance(wait_budget).await;
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
file_sync_probe::wait_for_active(1).await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
file_sync_probe::group_batches(),
|
||||||
|
vec![2],
|
||||||
|
"configured wait budget should let a follower join the leader's batch"
|
||||||
|
);
|
||||||
|
file_sync_probe::release();
|
||||||
|
first
|
||||||
|
.await
|
||||||
|
.expect("join first wait-budget file sync")
|
||||||
|
.expect("first wait-budget file sync must succeed");
|
||||||
|
second
|
||||||
|
.await
|
||||||
|
.expect("join second wait-budget file sync")
|
||||||
|
.expect("second wait-budget file sync must succeed");
|
||||||
|
assert!(
|
||||||
|
fsync_dir_recorder::was_fsynced(&first_dir),
|
||||||
|
"first source directory must still be fsynced"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
fsync_dir_recorder::was_fsynced(&second_dir),
|
||||||
|
"second source directory must still be fsynced"
|
||||||
|
);
|
||||||
|
assert_eq!(file_fdatasync_group_commit_counts_for_test(), (0, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||||
#[serial_test::serial(file_sync_probe)]
|
#[serial_test::serial(file_sync_probe)]
|
||||||
async fn file_fdatasync_group_commit_failure_fails_all_waiters_before_dir_fsync() {
|
async fn file_fdatasync_group_commit_failure_fails_all_waiters_before_dir_fsync() {
|
||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
|
|
||||||
let _group_commit = set_file_fdatasync_group_commit_for_test(true);
|
let _group_commit = set_file_fdatasync_group_commit_for_test(true);
|
||||||
|
set_file_fdatasync_group_commit_wait_for_test(0);
|
||||||
clear_file_fdatasync_group_commit_for_test();
|
clear_file_fdatasync_group_commit_for_test();
|
||||||
let temp_dir = tempdir().expect("create temp dir");
|
let temp_dir = tempdir().expect("create temp dir");
|
||||||
let first_dir = temp_dir.path().join("first");
|
let first_dir = temp_dir.path().join("first");
|
||||||
|
|||||||
@@ -249,7 +249,7 @@ impl PoolEndpointList {
|
|||||||
endpoint.set_set_index(0);
|
endpoint.set_set_index(0);
|
||||||
endpoint.set_disk_index(0);
|
endpoint.set_disk_index(0);
|
||||||
|
|
||||||
// TODO Check for cross device mounts if any.
|
// TODO(backlog): check for cross-device mounts in single-drive setup
|
||||||
|
|
||||||
return Ok(Self {
|
return Ok(Self {
|
||||||
inner: vec![Endpoints::from(vec![endpoint])],
|
inner: vec![Endpoints::from(vec![endpoint])],
|
||||||
@@ -264,7 +264,7 @@ impl PoolEndpointList {
|
|||||||
// Convert args to endpoints
|
// Convert args to endpoints
|
||||||
let mut eps = Endpoints::try_from(set_layout.as_slice())?;
|
let mut eps = Endpoints::try_from(set_layout.as_slice())?;
|
||||||
|
|
||||||
// TODO Check for cross device mounts if any.
|
// TODO(backlog): check for cross-device mounts in multi-pool setup
|
||||||
|
|
||||||
for (disk_idx, ep) in eps.as_mut().iter_mut().enumerate() {
|
for (disk_idx, ep) in eps.as_mut().iter_mut().enumerate() {
|
||||||
ep.set_pool_index(pool_idx);
|
ep.set_pool_index(pool_idx);
|
||||||
|
|||||||
@@ -719,14 +719,23 @@ impl ObjectInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
|
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
|
||||||
let name = decode_dir_object(object);
|
|
||||||
|
|
||||||
let mut version_id = fi.version_id;
|
let mut version_id = fi.version_id;
|
||||||
|
|
||||||
if versioned && version_id.is_none() {
|
if versioned && version_id.is_none() {
|
||||||
version_id = Some(Uuid::nil())
|
version_id = Some(Uuid::nil())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Self::from_file_info_with_version_id(fi, bucket, object, version_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_file_info_with_version_id(
|
||||||
|
fi: &FileInfo,
|
||||||
|
bucket: &str,
|
||||||
|
object: &str,
|
||||||
|
version_id: Option<Uuid>,
|
||||||
|
) -> ObjectInfo {
|
||||||
|
let name = decode_dir_object(object);
|
||||||
|
|
||||||
// etag
|
// etag
|
||||||
let (content_type, content_encoding, etag) = {
|
let (content_type, content_encoding, etag) = {
|
||||||
let content_type = fi.metadata.get("content-type").cloned();
|
let content_type = fi.metadata.get("content-type").cloned();
|
||||||
@@ -1082,7 +1091,7 @@ impl ObjectInfo {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO:VersionPurgeStatus
|
// TODO(backlog): handle VersionPurgeStatus in object listing
|
||||||
let versioned = vcfg.clone().map(|v| v.0.versioned(&entry.name)).unwrap_or_default();
|
let versioned = vcfg.clone().map(|v| v.0.versioned(&entry.name)).unwrap_or_default();
|
||||||
objects.push(ObjectInfo::from_file_info(&fi, bucket, &entry.name, versioned));
|
objects.push(ObjectInfo::from_file_info(&fi, bucket, &entry.name, versioned));
|
||||||
|
|
||||||
@@ -1640,6 +1649,18 @@ mod tests {
|
|||||||
assert_eq!(info.replication_decision, "arn=true;false;arn:replication::1:dest;rule-id");
|
assert_eq!(info.replication_decision, "arn=true;false;arn:replication::1:dest;rule-id");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_file_info_with_version_id_keeps_normalized_absent_version() {
|
||||||
|
let fi = FileInfo {
|
||||||
|
version_id: Some(Uuid::new_v4()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let info = ObjectInfo::from_file_info_with_version_id(&fi, "bucket", "object", None);
|
||||||
|
|
||||||
|
assert_eq!(info.version_id, None, "a normalized absent version must not be rewritten to nil");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn from_file_info_reports_effective_storage_class_for_legacy_metadata() {
|
fn from_file_info_reports_effective_storage_class_for_legacy_metadata() {
|
||||||
for legacy_label in [
|
for legacy_label in [
|
||||||
|
|||||||
@@ -657,7 +657,7 @@ where
|
|||||||
prefix,
|
prefix,
|
||||||
marker,
|
marker,
|
||||||
None,
|
None,
|
||||||
i32::try_from(limit).map_or(i32::MAX, |value| value),
|
i32::try_from(limit).unwrap_or(i32::MAX),
|
||||||
false,
|
false,
|
||||||
None,
|
None,
|
||||||
false,
|
false,
|
||||||
|
|||||||
@@ -922,14 +922,10 @@ mod prepared_get_object_metadata_tests {
|
|||||||
.expect("test should find an object whose initial fanout covers both data shards")
|
.expect("test should find an object whose initial fanout covers both data shards")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(
|
fn bounded_initial_parity_disk_index(bucket: &str, object: &str) -> usize {
|
||||||
dead_code,
|
|
||||||
reason = "test fixture no assertion in this module uses today; the live namesake lives in io_primitives tests (backlog#1823)"
|
|
||||||
)]
|
|
||||||
fn bounded_spare_disk_index(bucket: &str, object: &str) -> usize {
|
|
||||||
*bounded_metadata_fanout_order(bucket, object, 4, 2)
|
*bounded_metadata_fanout_order(bucket, object, 4, 2)
|
||||||
.get(3)
|
.get(2)
|
||||||
.expect("4-disk test geometry should leave one bounded spare disk")
|
.expect("4-disk test geometry should schedule one parity disk initially")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -1087,7 +1083,7 @@ mod prepared_get_object_metadata_tests {
|
|||||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
|
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
|
||||||
],
|
],
|
||||||
async {
|
async {
|
||||||
let slow_parity_disk = bounded_spare_disk_index(bucket, &object);
|
let slow_parity_disk = bounded_initial_parity_disk_index(bucket, &object);
|
||||||
let barrier =
|
let barrier =
|
||||||
rename_fanout_barrier::arm(&object, slow_parity_disk, rename_fanout_barrier::PHASE_READ_VERSION);
|
rename_fanout_barrier::arm(&object, slow_parity_disk, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||||
let calls = disk_call_counters::observe(&object);
|
let calls = disk_call_counters::observe(&object);
|
||||||
@@ -1501,6 +1497,102 @@ pub fn get_lock_acquire_timeout() -> Duration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_put_object_commit_lock_acquire_timeout_override_ms() -> u64 {
|
||||||
|
#[cfg(test)]
|
||||||
|
{
|
||||||
|
rustfs_utils::get_env_u64(
|
||||||
|
rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS,
|
||||||
|
rustfs_config::DEFAULT_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
#[cfg(not(test))]
|
||||||
|
{
|
||||||
|
static CACHED: OnceLock<u64> = OnceLock::new();
|
||||||
|
*CACHED.get_or_init(|| {
|
||||||
|
rustfs_utils::get_env_u64(
|
||||||
|
rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS,
|
||||||
|
rustfs_config::DEFAULT_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_put_object_commit_lock_acquire_timeout(op: &'static str) -> Duration {
|
||||||
|
let default_timeout = get_lock_acquire_timeout();
|
||||||
|
if op != "put_object_commit" {
|
||||||
|
return default_timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
let timeout_ms = get_put_object_commit_lock_acquire_timeout_override_ms();
|
||||||
|
if timeout_ms == 0 {
|
||||||
|
default_timeout
|
||||||
|
} else {
|
||||||
|
Duration::from_millis(timeout_ms)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_object_commit_lock_timeout_override_enabled(op: &'static str) -> bool {
|
||||||
|
op == "put_object_commit" && get_put_object_commit_lock_acquire_timeout_override_ms() != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_object_commit_lock_admission_budget_label() -> &'static str {
|
||||||
|
match get_put_object_commit_lock_acquire_timeout_override_ms() {
|
||||||
|
0 => rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_DISABLED,
|
||||||
|
1..=250 => rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS,
|
||||||
|
251..=500 => rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_500MS,
|
||||||
|
501..=1000 => rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_1000MS,
|
||||||
|
_ => rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_GT_1000MS,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_put_object_commit_lock_admission(op: &'static str, outcome: &'static str) {
|
||||||
|
if op != "put_object_commit" || !rustfs_io_metrics::put_stage_metrics_enabled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rustfs_io_metrics::record_put_object_commit_lock_admission(put_object_commit_lock_admission_budget_label(), outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_object_commit_lock_acquire_error_outcome(op: &'static str, err: &rustfs_lock::error::LockError) -> &'static str {
|
||||||
|
if put_object_commit_lock_timeout_override_enabled(op) && matches!(err, rustfs_lock::error::LockError::Timeout { .. }) {
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_TIMEOUT_SLOWDOWN
|
||||||
|
} else {
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_LOCK_ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_put_object_commit_lock_acquire_result(
|
||||||
|
set: &SetDisks,
|
||||||
|
op: &'static str,
|
||||||
|
bucket: &str,
|
||||||
|
object: &str,
|
||||||
|
result: std::result::Result<rustfs_lock::namespace::NamespaceLockGuard, rustfs_lock::error::LockError>,
|
||||||
|
) -> Result<rustfs_lock::namespace::NamespaceLockGuard> {
|
||||||
|
match result {
|
||||||
|
Ok(guard) => {
|
||||||
|
record_put_object_commit_lock_admission(op, rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_ACQUIRED);
|
||||||
|
Ok(guard)
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
record_put_object_commit_lock_admission(op, put_object_commit_lock_acquire_error_outcome(op, &err));
|
||||||
|
Err(map_put_object_commit_lock_acquire_error(set, op, bucket, object, err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_put_object_commit_lock_acquire_error(
|
||||||
|
set: &SetDisks,
|
||||||
|
op: &'static str,
|
||||||
|
bucket: &str,
|
||||||
|
object: &str,
|
||||||
|
err: rustfs_lock::error::LockError,
|
||||||
|
) -> StorageError {
|
||||||
|
if put_object_commit_lock_timeout_override_enabled(op) && matches!(err, rustfs_lock::error::LockError::Timeout { .. }) {
|
||||||
|
StorageError::SlowDown
|
||||||
|
} else {
|
||||||
|
set.map_namespace_lock_error(bucket, object, "write", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_object_lock_diag_enabled() -> bool {
|
pub fn is_object_lock_diag_enabled() -> bool {
|
||||||
*OBJECT_LOCK_DIAG_ENABLED.get_or_init(|| {
|
*OBJECT_LOCK_DIAG_ENABLED.get_or_init(|| {
|
||||||
let enabled = rustfs_utils::get_env_bool(
|
let enabled = rustfs_utils::get_env_bool(
|
||||||
@@ -3302,10 +3394,14 @@ impl SetDisks {
|
|||||||
let diag_enabled = is_object_lock_diag_enabled();
|
let diag_enabled = is_object_lock_diag_enabled();
|
||||||
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
||||||
let acquire_start = Instant::now();
|
let acquire_start = Instant::now();
|
||||||
let guard = ns_lock
|
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
|
||||||
.get_write_lock(get_lock_acquire_timeout())
|
let guard = resolve_put_object_commit_lock_acquire_result(
|
||||||
.await
|
self,
|
||||||
.map_err(|e| self.map_namespace_lock_error(bucket, object, "write", e))?;
|
op,
|
||||||
|
bucket,
|
||||||
|
object,
|
||||||
|
ns_lock.get_write_lock(acquire_timeout).await,
|
||||||
|
)?;
|
||||||
Self::record_put_object_commit_namespace_lock_wait(op, acquire_start);
|
Self::record_put_object_commit_namespace_lock_wait(op, acquire_start);
|
||||||
let owner = diag_enabled.then(|| ns_lock.owner().to_string());
|
let owner = diag_enabled.then(|| ns_lock.owner().to_string());
|
||||||
self.log_object_lock_acquire_if_slow(
|
self.log_object_lock_acquire_if_slow(
|
||||||
@@ -3340,20 +3436,26 @@ impl SetDisks {
|
|||||||
let diag_enabled = is_object_lock_diag_enabled();
|
let diag_enabled = is_object_lock_diag_enabled();
|
||||||
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
||||||
let acquire_start = Instant::now();
|
let acquire_start = Instant::now();
|
||||||
let acquire = ns_lock.get_write_lock(get_lock_acquire_timeout());
|
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
|
||||||
|
let acquire = ns_lock.get_write_lock(acquire_timeout);
|
||||||
tokio::pin!(acquire);
|
tokio::pin!(acquire);
|
||||||
let mut on_pending = Some(on_pending);
|
let mut on_pending = Some(on_pending);
|
||||||
let guard = futures::future::poll_fn(|cx| match std::future::Future::poll(acquire.as_mut(), cx) {
|
let guard = resolve_put_object_commit_lock_acquire_result(
|
||||||
std::task::Poll::Pending => {
|
self,
|
||||||
if let Some(on_pending) = on_pending.take() {
|
op,
|
||||||
on_pending();
|
bucket,
|
||||||
|
object,
|
||||||
|
futures::future::poll_fn(|cx| match std::future::Future::poll(acquire.as_mut(), cx) {
|
||||||
|
std::task::Poll::Pending => {
|
||||||
|
if let Some(on_pending) = on_pending.take() {
|
||||||
|
on_pending();
|
||||||
|
}
|
||||||
|
std::task::Poll::Pending
|
||||||
}
|
}
|
||||||
std::task::Poll::Pending
|
std::task::Poll::Ready(result) => std::task::Poll::Ready(result),
|
||||||
}
|
})
|
||||||
std::task::Poll::Ready(result) => std::task::Poll::Ready(result),
|
.await,
|
||||||
})
|
)?;
|
||||||
.await
|
|
||||||
.map_err(|e| self.map_namespace_lock_error(bucket, object, "write", e))?;
|
|
||||||
Self::record_put_object_commit_namespace_lock_wait(op, acquire_start);
|
Self::record_put_object_commit_namespace_lock_wait(op, acquire_start);
|
||||||
let owner = diag_enabled.then(|| ns_lock.owner().to_string());
|
let owner = diag_enabled.then(|| ns_lock.owner().to_string());
|
||||||
self.log_object_lock_acquire_if_slow(
|
self.log_object_lock_acquire_if_slow(
|
||||||
@@ -5717,8 +5819,8 @@ mod tests {
|
|||||||
.filter(|(composite, _, _, _)| {
|
.filter(|(composite, _, _, _)| {
|
||||||
composite.key().name() == "rustfs_s3_put_object_stage_duration_ms"
|
composite.key().name() == "rustfs_s3_put_object_stage_duration_ms"
|
||||||
&& composite.key().labels().any(|label| {
|
&& composite.key().labels().any(|label| {
|
||||||
label.key().to_string() == "stage"
|
label.key() == "stage"
|
||||||
&& label.value().to_string() == rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_WAIT
|
&& label.value() == rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_WAIT
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.map(|(_, _, _, value)| match value {
|
.map(|(_, _, _, value)| match value {
|
||||||
@@ -5728,6 +5830,81 @@ mod tests {
|
|||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn put_object_commit_lock_admission_count(
|
||||||
|
rows: &[(
|
||||||
|
metrics_util::CompositeKey,
|
||||||
|
Option<metrics::Unit>,
|
||||||
|
Option<metrics::SharedString>,
|
||||||
|
DebugValue,
|
||||||
|
)],
|
||||||
|
budget: &'static str,
|
||||||
|
outcome: &'static str,
|
||||||
|
) -> u64 {
|
||||||
|
rows.iter()
|
||||||
|
.filter(|(composite, _, _, _)| {
|
||||||
|
composite.key().name() == "rustfs_s3_put_object_commit_namespace_lock_admission_total"
|
||||||
|
&& composite
|
||||||
|
.key()
|
||||||
|
.labels()
|
||||||
|
.any(|label| label.key() == "budget" && label.value() == budget)
|
||||||
|
&& composite
|
||||||
|
.key()
|
||||||
|
.labels()
|
||||||
|
.any(|label| label.key() == "outcome" && label.value() == outcome)
|
||||||
|
})
|
||||||
|
.map(|(_, _, _, value)| match value {
|
||||||
|
DebugValue::Counter(count) => *count,
|
||||||
|
_ => 0,
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_budget_labels_are_bounded() {
|
||||||
|
let cases = [
|
||||||
|
("0", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_DISABLED),
|
||||||
|
("250", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS),
|
||||||
|
("251", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_500MS),
|
||||||
|
("500", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_500MS),
|
||||||
|
("501", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_1000MS),
|
||||||
|
("1000", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_1000MS),
|
||||||
|
("1001", rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_GT_1000MS),
|
||||||
|
];
|
||||||
|
for (timeout_ms, expected) in cases {
|
||||||
|
temp_env::with_vars(
|
||||||
|
[(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some(timeout_ms))],
|
||||||
|
|| {
|
||||||
|
assert_eq!(put_object_commit_lock_admission_budget_label(), expected);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_error_outcomes_are_bounded() {
|
||||||
|
let timeout = LockError::timeout("bucket/object", Duration::from_millis(1));
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("1"))], || {
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_acquire_error_outcome("put_object_commit", &timeout),
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_TIMEOUT_SLOWDOWN
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_acquire_error_outcome("complete_multipart_upload_commit", &timeout),
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_LOCK_ERROR
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
let internal = LockError::internal("simulated lock manager error");
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("1"))], || {
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_acquire_error_outcome("put_object_commit", &internal),
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_LOCK_ERROR
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[serial]
|
#[serial]
|
||||||
fn put_object_commit_namespace_lock_wait_metric_is_wired_to_both_write_lock_paths() {
|
fn put_object_commit_namespace_lock_wait_metric_is_wired_to_both_write_lock_paths() {
|
||||||
@@ -5793,6 +5970,289 @@ mod tests {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_timeout_override_only_applies_to_put_commit() {
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("17"))], || {
|
||||||
|
assert_eq!(get_put_object_commit_lock_acquire_timeout("put_object_commit"), Duration::from_millis(17));
|
||||||
|
assert_eq!(
|
||||||
|
get_put_object_commit_lock_acquire_timeout("complete_multipart_upload_commit"),
|
||||||
|
get_lock_acquire_timeout()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("0"))], || {
|
||||||
|
assert_eq!(
|
||||||
|
get_put_object_commit_lock_acquire_timeout("put_object_commit"),
|
||||||
|
get_lock_acquire_timeout()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_timeout_override_bounds_contention_wait() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("1"))], || {
|
||||||
|
runtime.block_on(async {
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(Vec::new(), ctx).await;
|
||||||
|
let bucket = "bucket";
|
||||||
|
let object = "object";
|
||||||
|
|
||||||
|
let held_guard = set
|
||||||
|
.acquire_write_lock_diag("put_object_commit", bucket, object)
|
||||||
|
.await
|
||||||
|
.expect("holder acquire should succeed");
|
||||||
|
let started = Instant::now();
|
||||||
|
let err = match set.acquire_write_lock_diag("put_object_commit", bucket, object).await {
|
||||||
|
Ok(_) => panic!("contended PUT commit lock should honor the short timeout"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
started.elapsed() < Duration::from_secs(1),
|
||||||
|
"short PUT commit lock timeout should not wait for the global timeout"
|
||||||
|
);
|
||||||
|
assert!(matches!(err, StorageError::SlowDown));
|
||||||
|
|
||||||
|
drop(held_guard);
|
||||||
|
set.acquire_write_lock_diag("put_object_commit", bucket, object)
|
||||||
|
.await
|
||||||
|
.expect("permit should not leak after timeout");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_records_acquired_and_timeout() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("1"))], || {
|
||||||
|
let recorder = DebuggingRecorder::new();
|
||||||
|
let snapshotter = recorder.snapshotter();
|
||||||
|
metrics::with_local_recorder(&recorder, || {
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||||
|
runtime.block_on(async {
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(Vec::new(), ctx).await;
|
||||||
|
let held_guard = set
|
||||||
|
.acquire_write_lock_diag("put_object_commit", "bucket", "object")
|
||||||
|
.await
|
||||||
|
.expect("holder acquire should succeed");
|
||||||
|
let err = match set.acquire_write_lock_diag("put_object_commit", "bucket", "object").await {
|
||||||
|
Ok(_) => panic!("contended PUT commit acquire should return SlowDown"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
assert!(matches!(err, StorageError::SlowDown));
|
||||||
|
drop(held_guard);
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = snapshotter.snapshot().into_vec();
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_ACQUIRED,
|
||||||
|
),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_TIMEOUT_SLOWDOWN,
|
||||||
|
),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_records_disabled_budget_acquired() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("0"))], || {
|
||||||
|
let recorder = DebuggingRecorder::new();
|
||||||
|
let snapshotter = recorder.snapshotter();
|
||||||
|
metrics::with_local_recorder(&recorder, || {
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||||
|
runtime.block_on(async {
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(Vec::new(), ctx).await;
|
||||||
|
let guard = set
|
||||||
|
.acquire_write_lock_diag("put_object_commit", "bucket", "object")
|
||||||
|
.await
|
||||||
|
.expect("PUT commit acquire should succeed with default timeout");
|
||||||
|
drop(guard);
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = snapshotter.snapshot().into_vec();
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_DISABLED,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_ACQUIRED,
|
||||||
|
),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_skips_non_put_commit_ops() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("250"))], || {
|
||||||
|
let recorder = DebuggingRecorder::new();
|
||||||
|
let snapshotter = recorder.snapshotter();
|
||||||
|
metrics::with_local_recorder(&recorder, || {
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||||
|
runtime.block_on(async {
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(Vec::new(), ctx).await;
|
||||||
|
let guard = set
|
||||||
|
.acquire_write_lock_diag("complete_multipart_upload_commit", "bucket", "object")
|
||||||
|
.await
|
||||||
|
.expect("non-PUT commit acquire should succeed");
|
||||||
|
drop(guard);
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = snapshotter.snapshot().into_vec();
|
||||||
|
assert_eq!(
|
||||||
|
rows.iter()
|
||||||
|
.filter(|(composite, _, _, _)| {
|
||||||
|
composite.key().name() == "rustfs_s3_put_object_commit_namespace_lock_admission_total"
|
||||||
|
})
|
||||||
|
.count(),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_records_lock_error() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("250"))], || {
|
||||||
|
let recorder = DebuggingRecorder::new();
|
||||||
|
let snapshotter = recorder.snapshotter();
|
||||||
|
metrics::with_local_recorder(&recorder, || {
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||||
|
runtime.block_on(async {
|
||||||
|
let healthy: Arc<dyn LockClient> =
|
||||||
|
Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||||
|
let failing: Arc<dyn LockClient> = Arc::new(FailingClient);
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::DistErasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(vec![healthy, failing], ctx).await;
|
||||||
|
assert!(
|
||||||
|
set.acquire_write_lock_diag("put_object_commit", "bucket", "object")
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"one healthy locker must not satisfy the PUT commit write quorum"
|
||||||
|
);
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = snapshotter.snapshot().into_vec();
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_LOCK_ERROR,
|
||||||
|
),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_250MS,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_TIMEOUT_SLOWDOWN,
|
||||||
|
),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[serial]
|
||||||
|
fn put_object_commit_lock_admission_records_pending_hook_acquired() {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("test runtime should start");
|
||||||
|
|
||||||
|
temp_env::with_vars([(rustfs_config::ENV_PUT_COMMIT_NAMESPACE_LOCK_ACQUIRE_TIMEOUT_MS, Some("500"))], || {
|
||||||
|
let recorder = DebuggingRecorder::new();
|
||||||
|
let snapshotter = recorder.snapshotter();
|
||||||
|
metrics::with_local_recorder(&recorder, || {
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(true);
|
||||||
|
runtime.block_on(async {
|
||||||
|
let ctx = Arc::new(InstanceContext::new());
|
||||||
|
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||||
|
let set = make_test_set_disks_with_ctx(Vec::new(), ctx).await;
|
||||||
|
let held_guard = set
|
||||||
|
.acquire_write_lock_diag("put_object_commit", "bucket", "object")
|
||||||
|
.await
|
||||||
|
.expect("holder acquire should succeed");
|
||||||
|
let (pending_tx, pending_rx) = tokio::sync::oneshot::channel();
|
||||||
|
let pending_acquire =
|
||||||
|
set.acquire_write_lock_diag_with_pending_hook("put_object_commit", "bucket", "object", move || {
|
||||||
|
let _ = pending_tx.send(());
|
||||||
|
});
|
||||||
|
let release_holder = async {
|
||||||
|
pending_rx.await.expect("pending hook should fire");
|
||||||
|
drop(held_guard);
|
||||||
|
};
|
||||||
|
let (pending_guard, ()) = tokio::join!(pending_acquire, release_holder);
|
||||||
|
drop(pending_guard.expect("pending-hook PUT commit acquire should succeed"));
|
||||||
|
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let rows = snapshotter.snapshot().into_vec();
|
||||||
|
assert_eq!(
|
||||||
|
put_object_commit_lock_admission_count(
|
||||||
|
&rows,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_BUDGET_LE_500MS,
|
||||||
|
rustfs_io_metrics::PUT_COMMIT_LOCK_ADMISSION_OUTCOME_ACQUIRED,
|
||||||
|
),
|
||||||
|
2
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn new_ns_lock_shares_clients_without_changing_quorum() {
|
async fn new_ns_lock_shares_clients_without_changing_quorum() {
|
||||||
let healthy: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
let healthy: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||||
|
|||||||
@@ -124,14 +124,7 @@ impl HealWalkCollector {
|
|||||||
for fi in fiv.versions.iter().chain(fiv.free_versions.iter()) {
|
for fi in fiv.versions.iter().chain(fiv.free_versions.iter()) {
|
||||||
let version_uuid = fi.version_id.filter(|version_id| !version_id.is_nil());
|
let version_uuid = fi.version_id.filter(|version_id| !version_id.is_nil());
|
||||||
let lifecycle_object_info = if self.include_lifecycle_object_info {
|
let lifecycle_object_info = if self.include_lifecycle_object_info {
|
||||||
let mut lifecycle_fi = fi.clone();
|
Some(ObjectInfo::from_file_info_with_version_id(fi, &self.bucket, &entry.name, version_uuid))
|
||||||
lifecycle_fi.version_id = version_uuid;
|
|
||||||
Some(ObjectInfo::from_file_info(
|
|
||||||
&lifecycle_fi,
|
|
||||||
&self.bucket,
|
|
||||||
&entry.name,
|
|
||||||
version_uuid.is_some(),
|
|
||||||
))
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -198,14 +191,7 @@ impl HealWalkCollector {
|
|||||||
let vid = version_uuid.map(|u| u.to_string());
|
let vid = version_uuid.map(|u| u.to_string());
|
||||||
if seen.insert(vid.clone()) {
|
if seen.insert(vid.clone()) {
|
||||||
let lifecycle_object_info = if self.include_lifecycle_object_info {
|
let lifecycle_object_info = if self.include_lifecycle_object_info {
|
||||||
let mut lifecycle_fi = fi.clone();
|
Some(ObjectInfo::from_file_info_with_version_id(fi, &self.bucket, &entry.name, version_uuid))
|
||||||
lifecycle_fi.version_id = version_uuid;
|
|
||||||
Some(ObjectInfo::from_file_info(
|
|
||||||
&lifecycle_fi,
|
|
||||||
&self.bucket,
|
|
||||||
&entry.name,
|
|
||||||
version_uuid.is_some(),
|
|
||||||
))
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1575,7 +1575,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
|||||||
let parts_metadata = vec![fi.clone(); disks.len()];
|
let parts_metadata = vec![fi.clone(); disks.len()];
|
||||||
|
|
||||||
if !user_defined.contains_key("content-type") {
|
if !user_defined.contains_key("content-type") {
|
||||||
// TODO: get content-type
|
// TODO(backlog): detect content-type from part data when header is missing
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(sc) = user_defined.get(AMZ_STORAGE_CLASS)
|
if let Some(sc) = user_defined.get(AMZ_STORAGE_CLASS)
|
||||||
@@ -1971,7 +1971,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
|||||||
return Err(Error::InvalidPart(p.part_num, ext_part.etag.clone(), p.etag.clone().unwrap_or_default()));
|
return Err(Error::InvalidPart(p.part_num, ext_part.etag.clone(), p.etag.clone().unwrap_or_default()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: crypto
|
// TODO(backlog): integrate encryption verification during complete multipart
|
||||||
|
|
||||||
if (i < uploaded_parts.len() - 1)
|
if (i < uploaded_parts.len() - 1)
|
||||||
&& !(opts.data_movement && ext_part.actual_size < 0)
|
&& !(opts.data_movement && ext_part.actual_size < 0)
|
||||||
|
|||||||
@@ -1322,7 +1322,12 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks {
|
|||||||
let object_info = prepared_object_info
|
let object_info = prepared_object_info
|
||||||
.unwrap_or_else(|| build_get_object_info(fi, bucket, object, opts.versioned || opts.version_suspended));
|
.unwrap_or_else(|| build_get_object_info(fi, bucket, object, opts.versioned || opts.version_suspended));
|
||||||
let object_class = classify_get_codec_streaming_object_class(&range, &object_info, fi);
|
let object_class = classify_get_codec_streaming_object_class(&range, &object_info, fi);
|
||||||
let size_bucket = rustfs_io_metrics::get_object_size_bucket(object_info.size);
|
let metrics_size = if stage_metrics_enabled {
|
||||||
|
object_info.get_actual_size().unwrap_or(object_info.size)
|
||||||
|
} else {
|
||||||
|
object_info.size
|
||||||
|
};
|
||||||
|
let size_bucket = rustfs_io_metrics::get_object_size_bucket(metrics_size);
|
||||||
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_SET_DISK, GET_STAGE_OBJECT_INFO, object_info_stage_start);
|
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_SET_DISK, GET_STAGE_OBJECT_INFO, object_info_stage_start);
|
||||||
let metadata_elapsed = metadata_stage_start.elapsed().as_secs_f64();
|
let metadata_elapsed = metadata_stage_start.elapsed().as_secs_f64();
|
||||||
rustfs_io_metrics::record_get_object_metadata_phase_duration(metadata_elapsed);
|
rustfs_io_metrics::record_get_object_metadata_phase_duration(metadata_elapsed);
|
||||||
@@ -3766,7 +3771,7 @@ pub(crate) async fn complete_transition_upload<Remote, Producer>(
|
|||||||
producer: Producer,
|
producer: Producer,
|
||||||
expected_size: u64,
|
expected_size: u64,
|
||||||
consumed: Arc<AtomicU64>,
|
consumed: Arc<AtomicU64>,
|
||||||
) -> std::result::Result<TransitionUploadCompletion, TransitionUploadFailure>
|
) -> std::result::Result<TransitionUploadCompletion, Box<TransitionUploadFailure>>
|
||||||
where
|
where
|
||||||
Remote: Future<Output = std::result::Result<String, std::io::Error>>,
|
Remote: Future<Output = std::result::Result<String, std::io::Error>>,
|
||||||
Producer: Future<Output = Result<u64>>,
|
Producer: Future<Output = Result<u64>>,
|
||||||
@@ -3784,23 +3789,23 @@ where
|
|||||||
Err(_) => StorageError::Unexpected,
|
Err(_) => StorageError::Unexpected,
|
||||||
Ok(Ok(_)) => StorageError::Io(remote_error),
|
Ok(Ok(_)) => StorageError::Io(remote_error),
|
||||||
};
|
};
|
||||||
return Err(TransitionUploadFailure { error, candidate: None });
|
return Err(Box::new(TransitionUploadFailure { error, candidate: None }));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let candidate = TransitionUploadCandidate::from_put_response(remote_version);
|
let candidate = TransitionUploadCandidate::from_put_response(remote_version);
|
||||||
let produced = match producer_result {
|
let produced = match producer_result {
|
||||||
Ok(Ok(produced)) => produced,
|
Ok(Ok(produced)) => produced,
|
||||||
Ok(Err(error)) => {
|
Ok(Err(error)) => {
|
||||||
return Err(TransitionUploadFailure {
|
return Err(Box::new(TransitionUploadFailure {
|
||||||
error,
|
error,
|
||||||
candidate: Some(candidate),
|
candidate: Some(candidate),
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
return Err(TransitionUploadFailure {
|
return Err(Box::new(TransitionUploadFailure {
|
||||||
error: StorageError::Unexpected,
|
error: StorageError::Unexpected,
|
||||||
candidate: Some(candidate),
|
candidate: Some(candidate),
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let consumed = consumed.load(Ordering::Acquire);
|
let consumed = consumed.load(Ordering::Acquire);
|
||||||
@@ -3810,10 +3815,10 @@ where
|
|||||||
} else {
|
} else {
|
||||||
StorageError::MoreData
|
StorageError::MoreData
|
||||||
};
|
};
|
||||||
return Err(TransitionUploadFailure {
|
return Err(Box::new(TransitionUploadFailure {
|
||||||
error,
|
error,
|
||||||
candidate: Some(candidate),
|
candidate: Some(candidate),
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
Ok(TransitionUploadCompletion {
|
Ok(TransitionUploadCompletion {
|
||||||
candidate,
|
candidate,
|
||||||
@@ -6156,7 +6161,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
|||||||
|
|
||||||
join_all(rollback_futures).await;
|
join_all(rollback_futures).await;
|
||||||
|
|
||||||
// TODO: add_partial
|
// TODO(backlog): support partial object deletion for multi-part objects
|
||||||
|
|
||||||
if let Some(api) = opts.tier_delete_journal_api.as_ref() {
|
if let Some(api) = opts.tier_delete_journal_api.as_ref() {
|
||||||
for (idx, je) in persisted_journal_entries {
|
for (idx, je) in persisted_journal_entries {
|
||||||
@@ -6366,7 +6371,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Lifecycle
|
// TODO(backlog): integrate lifecycle evaluation before object deletion
|
||||||
|
|
||||||
let mut version_found = true;
|
let mut version_found = true;
|
||||||
// delete_object_version below derives its own majority quorum from the
|
// delete_object_version below derives its own majority quorum from the
|
||||||
@@ -6460,7 +6465,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
|||||||
mark_deleted: mark_delete,
|
mark_deleted: mark_delete,
|
||||||
mod_time: Some(mod_time),
|
mod_time: Some(mod_time),
|
||||||
replication_state_internal: opts.delete_replication.as_ref().map(replication_state_to_filemeta),
|
replication_state_internal: opts.delete_replication.as_ref().map(replication_state_to_filemeta),
|
||||||
..Default::default() // TODO: Transition
|
..Default::default() // TODO(backlog): populate transition state on delete markers
|
||||||
};
|
};
|
||||||
|
|
||||||
fi.set_tier_free_version_id(&find_vid.to_string());
|
fi.set_tier_free_version_id(&find_vid.to_string());
|
||||||
@@ -7284,7 +7289,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
|||||||
}
|
}
|
||||||
let gr = gr?;
|
let gr = gr?;
|
||||||
let reader = BufReader::new(gr.stream);
|
let reader = BufReader::new(gr.stream);
|
||||||
let hash_reader = HashReader::from_stream(reader, gr.object_info.size, gr.object_info.size, None, None, false)?;
|
let hash_reader = HashReader::from_stream(reader, gr.object_info.size, oi.get_actual_size()?, None, None, false)?;
|
||||||
let mut p_reader = PutObjReader::new(hash_reader);
|
let mut p_reader = PutObjReader::new(hash_reader);
|
||||||
return match self_.clone().put_object(bucket, object, &mut p_reader, &ropts).await {
|
return match self_.clone().put_object(bucket, object, &mut p_reader, &ropts).await {
|
||||||
Ok(restored_info) => {
|
Ok(restored_info) => {
|
||||||
@@ -8826,7 +8831,7 @@ mod transition_commit_failure_tests {
|
|||||||
use s3s::dto::RestoreRequest;
|
use s3s::dto::RestoreRequest;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
fn restore_operation_id_metadata(operation_id: Uuid) -> HashMap<String, String> {
|
pub(super) fn restore_operation_id_metadata(operation_id: Uuid) -> HashMap<String, String> {
|
||||||
let mut metadata = HashMap::new();
|
let mut metadata = HashMap::new();
|
||||||
rustfs_utils::http::metadata_compat::insert_str(
|
rustfs_utils::http::metadata_compat::insert_str(
|
||||||
&mut metadata,
|
&mut metadata,
|
||||||
@@ -8836,7 +8841,7 @@ mod transition_commit_failure_tests {
|
|||||||
metadata
|
metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
fn restore_metadata(operation_id: Uuid, ongoing: bool) -> HashMap<String, String> {
|
pub(super) fn restore_metadata(operation_id: Uuid, ongoing: bool) -> HashMap<String, String> {
|
||||||
let mut metadata = restore_operation_id_metadata(operation_id);
|
let mut metadata = restore_operation_id_metadata(operation_id);
|
||||||
metadata.insert(s3s::header::X_AMZ_RESTORE.as_str().to_string(), format!("ongoing-request=\"{ongoing}\""));
|
metadata.insert(s3s::header::X_AMZ_RESTORE.as_str().to_string(), format!("ongoing-request=\"{ongoing}\""));
|
||||||
metadata
|
metadata
|
||||||
@@ -10097,6 +10102,51 @@ mod transition_commit_failure_tests {
|
|||||||
.await
|
.await
|
||||||
.expect("operation B should replace operation A before final commit");
|
.expect("operation B should replace operation A before final commit");
|
||||||
|
|
||||||
|
let mismatch = set_disks
|
||||||
|
.finalize_restore_metadata(
|
||||||
|
bucket,
|
||||||
|
object,
|
||||||
|
&set_disks
|
||||||
|
.get_object_info(bucket, object, &ObjectOptions::default())
|
||||||
|
.await
|
||||||
|
.expect("operation B metadata should be readable"),
|
||||||
|
&ObjectOptions {
|
||||||
|
user_defined: restore_operation_id_metadata(operation_a),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect_err("operation A must not finalize operation B metadata");
|
||||||
|
assert!(matches!(
|
||||||
|
mismatch,
|
||||||
|
Error::Io(ref error)
|
||||||
|
if error.kind() == std::io::ErrorKind::Other
|
||||||
|
&& error.to_string() == "restore operation id changed before metadata finalization"
|
||||||
|
));
|
||||||
|
let current = set_disks
|
||||||
|
.get_object_info(bucket, object, &ObjectOptions::default())
|
||||||
|
.await
|
||||||
|
.expect("operation B metadata should remain after mismatched finalization");
|
||||||
|
assert_eq!(
|
||||||
|
rustfs_utils::http::metadata_compat::get_consistent_str(
|
||||||
|
current.user_defined.as_ref(),
|
||||||
|
rustfs_utils::http::metadata_compat::SUFFIX_RESTORE_OPERATION_ID,
|
||||||
|
),
|
||||||
|
Some(operation_b.to_string().as_str()),
|
||||||
|
"mismatched finalization must not remove operation B"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
parse_restore_obj_status(
|
||||||
|
current
|
||||||
|
.user_defined
|
||||||
|
.get(s3s::header::X_AMZ_RESTORE.as_str())
|
||||||
|
.expect("operation B restore header should remain pending"),
|
||||||
|
)
|
||||||
|
.expect("operation B restore header should parse")
|
||||||
|
.on_going(),
|
||||||
|
"mismatched finalization must not publish restore completion"
|
||||||
|
);
|
||||||
|
|
||||||
let mut stale_restore_reader = PutObjReader::from_vec(b"stale A restored body".repeat(1024));
|
let mut stale_restore_reader = PutObjReader::from_vec(b"stale A restored body".repeat(1024));
|
||||||
let result = set_disks
|
let result = set_disks
|
||||||
.put_object(
|
.put_object(
|
||||||
@@ -10126,18 +10176,37 @@ mod transition_commit_failure_tests {
|
|||||||
|
|
||||||
let mut matching_restore_reader = PutObjReader::from_vec(b"matching B restored body".repeat(1024));
|
let mut matching_restore_reader = PutObjReader::from_vec(b"matching B restored body".repeat(1024));
|
||||||
let operation_b_restore_metadata = restore_metadata(operation_b, false);
|
let operation_b_restore_metadata = restore_metadata(operation_b, false);
|
||||||
set_disks
|
let restored = set_disks
|
||||||
.put_object(
|
.put_object(
|
||||||
bucket,
|
bucket,
|
||||||
object,
|
object,
|
||||||
&mut matching_restore_reader,
|
&mut matching_restore_reader,
|
||||||
&ObjectOptions {
|
&ObjectOptions {
|
||||||
user_defined: operation_b_restore_metadata,
|
user_defined: operation_b_restore_metadata.clone(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("matching operation B should be allowed to commit");
|
.expect("matching operation B should be allowed to commit");
|
||||||
|
set_disks
|
||||||
|
.finalize_restore_metadata(
|
||||||
|
bucket,
|
||||||
|
object,
|
||||||
|
&restored,
|
||||||
|
&ObjectOptions {
|
||||||
|
user_defined: restore_operation_id_metadata(operation_b),
|
||||||
|
transition: TransitionOptions {
|
||||||
|
restore_request: RestoreRequest {
|
||||||
|
days: Some(1),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("matching operation B should finalize after its commit consumes the operation id");
|
||||||
let restored = set_disks
|
let restored = set_disks
|
||||||
.get_object_info(bucket, object, &ObjectOptions::default())
|
.get_object_info(bucket, object, &ObjectOptions::default())
|
||||||
.await
|
.await
|
||||||
@@ -10503,13 +10572,16 @@ mod transition_commit_failure_tests {
|
|||||||
#[cfg(all(test, feature = "test-util"))]
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
mod transition_upload_integrity_tests {
|
mod transition_upload_integrity_tests {
|
||||||
use super::hermetic_set_disks_support::{hermetic_set_disks, hermetic_set_disks_with_lockers};
|
use super::hermetic_set_disks_support::{hermetic_set_disks, hermetic_set_disks_with_lockers};
|
||||||
|
use super::transition_commit_failure_tests::{restore_metadata, restore_operation_id_metadata};
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::bucket::lifecycle::lifecycle::{TRANSITION_PENDING, TransitionOptions};
|
use crate::bucket::lifecycle::lifecycle::{TRANSITION_PENDING, TransitionOptions};
|
||||||
use crate::disk::DiskAPI as _;
|
use crate::disk::DiskAPI as _;
|
||||||
use crate::layout::endpoints::SetupType;
|
use crate::layout::endpoints::SetupType;
|
||||||
use crate::services::tier::test_util::register_mock_tier;
|
use crate::services::tier::test_util::register_mock_tier;
|
||||||
|
use crate::set_disk::replication::RestoreFinalizeBarrier;
|
||||||
use crate::storage_api_contracts::object::{ObjectIO as _, ObjectOperations as _};
|
use crate::storage_api_contracts::object::{ObjectIO as _, ObjectOperations as _};
|
||||||
use http::HeaderMap;
|
use http::HeaderMap;
|
||||||
|
use rustfs_filemeta::RestoreStatusOps as _;
|
||||||
use rustfs_lock::client::local::LocalClient;
|
use rustfs_lock::client::local::LocalClient;
|
||||||
use rustfs_lock::{LockClient, LockError, LockId, LockInfo, LockRequest, LockResponse, LockStats};
|
use rustfs_lock::{LockClient, LockError, LockId, LockInfo, LockRequest, LockResponse, LockStats};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
@@ -10655,6 +10727,162 @@ mod transition_upload_integrity_tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn write_committed_restore(
|
||||||
|
set_disks: &Arc<SetDisks>,
|
||||||
|
disk_stores: &[DiskStore],
|
||||||
|
bucket: &str,
|
||||||
|
object: &str,
|
||||||
|
operation_id: Uuid,
|
||||||
|
) -> ObjectInfo {
|
||||||
|
for disk in disk_stores {
|
||||||
|
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||||
|
}
|
||||||
|
let mut source = PutObjReader::from_vec(b"restore source body".repeat(1024));
|
||||||
|
set_disks
|
||||||
|
.put_object(bucket, object, &mut source, &ObjectOptions::default())
|
||||||
|
.await
|
||||||
|
.expect("source object should be written");
|
||||||
|
set_disks
|
||||||
|
.put_object_metadata(
|
||||||
|
bucket,
|
||||||
|
object,
|
||||||
|
&ObjectOptions {
|
||||||
|
eval_metadata: Some(restore_metadata(operation_id, true)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("pending restore metadata should be installed");
|
||||||
|
|
||||||
|
let mut restored_reader = PutObjReader::from_vec(b"restored body".repeat(1024));
|
||||||
|
set_disks
|
||||||
|
.put_object(
|
||||||
|
bucket,
|
||||||
|
object,
|
||||||
|
&mut restored_reader,
|
||||||
|
&ObjectOptions {
|
||||||
|
user_defined: restore_metadata(operation_id, true),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("matching restore commit should consume its operation id")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_finalize_options(operation_id: Uuid) -> ObjectOptions {
|
||||||
|
ObjectOptions {
|
||||||
|
user_defined: restore_operation_id_metadata(operation_id),
|
||||||
|
transition: TransitionOptions {
|
||||||
|
restore_request: s3s::dto::RestoreRequest {
|
||||||
|
days: Some(1),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn assert_committed_restore_remains_pending(set_disks: &Arc<SetDisks>, bucket: &str, object: &str) {
|
||||||
|
let current = set_disks
|
||||||
|
.get_object_info(bucket, object, &ObjectOptions::default())
|
||||||
|
.await
|
||||||
|
.expect("pending restore metadata should remain readable");
|
||||||
|
assert!(
|
||||||
|
restore_operation_id_from_metadata(current.user_defined.as_ref())
|
||||||
|
.expect("operation id metadata should parse")
|
||||||
|
.is_none(),
|
||||||
|
"successful restore commit must have consumed the operation id"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
rustfs_filemeta::parse_restore_obj_status(
|
||||||
|
current
|
||||||
|
.user_defined
|
||||||
|
.get(s3s::header::X_AMZ_RESTORE.as_str())
|
||||||
|
.expect("pending restore header should remain"),
|
||||||
|
)
|
||||||
|
.expect("restore header should parse")
|
||||||
|
.on_going(),
|
||||||
|
"failed finalization must not publish completion metadata"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "current_thread", start_paused = true)]
|
||||||
|
#[serial_test::serial]
|
||||||
|
async fn restore_finalize_rejects_acquired_lock_loss_after_commit() {
|
||||||
|
let refresh_calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let lockers: Vec<Arc<dyn LockClient>> = (0..4)
|
||||||
|
.map(|_| Arc::new(LockLostRefreshClient::new(Arc::clone(&refresh_calls))) as Arc<dyn LockClient>)
|
||||||
|
.collect();
|
||||||
|
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks_with_lockers(4, 0, 2, lockers).await;
|
||||||
|
let bucket = "restore-finalize-acquired-lock-lost-bucket";
|
||||||
|
let object = "object.bin";
|
||||||
|
let operation_id = Uuid::new_v4();
|
||||||
|
let restored = write_committed_restore(&set_disks, &disk_stores, bucket, object, operation_id).await;
|
||||||
|
let _setup_type_guard = SetupTypeGuard::switch_to(SetupType::DistErasure).await;
|
||||||
|
let barrier = RestoreFinalizeBarrier::install(bucket, object);
|
||||||
|
let finalize_set = Arc::clone(&set_disks);
|
||||||
|
let finalize = tokio::spawn(async move {
|
||||||
|
finalize_set
|
||||||
|
.finalize_restore_metadata(bucket, object, &restored, &restore_finalize_options(operation_id))
|
||||||
|
.await
|
||||||
|
});
|
||||||
|
barrier.wait_until_paused().await;
|
||||||
|
tokio::time::advance(Duration::from_secs(11)).await;
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
assert!(refresh_calls.load(Ordering::SeqCst) > 0, "restore finalization lock must attempt renewal");
|
||||||
|
barrier.release();
|
||||||
|
|
||||||
|
let error = finalize
|
||||||
|
.await
|
||||||
|
.expect("restore finalization task should join")
|
||||||
|
.expect_err("lost acquired lock must reject restore finalization");
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
Error::Io(ref error)
|
||||||
|
if error.kind() == std::io::ErrorKind::Other
|
||||||
|
&& error.to_string() == "restore finalization lock lost before metadata update"
|
||||||
|
));
|
||||||
|
assert_committed_restore_remains_pending(&set_disks, bucket, object).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[serial_test::serial]
|
||||||
|
async fn restore_finalize_rejects_outer_fence_loss_after_metadata_read() {
|
||||||
|
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||||
|
let bucket = "restore-finalize-outer-fence-lost-bucket";
|
||||||
|
let object = "object.bin";
|
||||||
|
let operation_id = Uuid::new_v4();
|
||||||
|
let restored = write_committed_restore(&set_disks, &disk_stores, bucket, object, operation_id).await;
|
||||||
|
let (fence, loss_handle) = NamespaceLockFence::loss_handle_for_test();
|
||||||
|
let barrier = RestoreFinalizeBarrier::install(bucket, object);
|
||||||
|
let finalize_set = Arc::clone(&set_disks);
|
||||||
|
let finalize = tokio::spawn(async move {
|
||||||
|
let mut opts = restore_finalize_options(operation_id);
|
||||||
|
opts.no_lock = true;
|
||||||
|
opts.namespace_lock_fence = Some(fence);
|
||||||
|
finalize_set.finalize_restore_metadata(bucket, object, &restored, &opts).await
|
||||||
|
});
|
||||||
|
barrier.wait_until_paused().await;
|
||||||
|
loss_handle.store(true, std::sync::atomic::Ordering::Release);
|
||||||
|
barrier.release();
|
||||||
|
|
||||||
|
let error = finalize
|
||||||
|
.await
|
||||||
|
.expect("restore finalization task should join")
|
||||||
|
.expect_err("lost outer fence must reject restore finalization");
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
Error::NamespaceLockQuorumUnavailable {
|
||||||
|
mode: "restore_finalize_metadata",
|
||||||
|
required: 1,
|
||||||
|
achieved: 0,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert_committed_restore_remains_pending(&set_disks, bucket, object).await;
|
||||||
|
}
|
||||||
|
|
||||||
async fn assert_local_source_intact(set_disks: &Arc<SetDisks>, bucket: &str, object: &str, payload: &[u8]) {
|
async fn assert_local_source_intact(set_disks: &Arc<SetDisks>, bucket: &str, object: &str, payload: &[u8]) {
|
||||||
let mut restored = Vec::new();
|
let mut restored = Vec::new();
|
||||||
set_disks
|
set_disks
|
||||||
|
|||||||
@@ -18,6 +18,78 @@ use rustfs_filemeta::RestoreStatusOps;
|
|||||||
use rustfs_utils::http::headers::{AMZ_RESTORE_EXPIRY_DAYS, AMZ_RESTORE_REQUEST_DATE};
|
use rustfs_utils::http::headers::{AMZ_RESTORE_EXPIRY_DAYS, AMZ_RESTORE_REQUEST_DATE};
|
||||||
use s3s::dto::{RestoreStatus, Timestamp};
|
use s3s::dto::{RestoreStatus, Timestamp};
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
struct RestoreFinalizeBarrierState {
|
||||||
|
bucket: String,
|
||||||
|
object: String,
|
||||||
|
arrived: tokio::sync::Notify,
|
||||||
|
release: tokio::sync::Notify,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
static RESTORE_FINALIZE_BARRIER: std::sync::OnceLock<std::sync::Mutex<Option<Arc<RestoreFinalizeBarrierState>>>> =
|
||||||
|
std::sync::OnceLock::new();
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
pub(in crate::set_disk) struct RestoreFinalizeBarrier {
|
||||||
|
state: Arc<RestoreFinalizeBarrierState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
impl RestoreFinalizeBarrier {
|
||||||
|
pub(in crate::set_disk) fn install(bucket: &str, object: &str) -> Self {
|
||||||
|
let state = Arc::new(RestoreFinalizeBarrierState {
|
||||||
|
bucket: bucket.to_string(),
|
||||||
|
object: object.to_string(),
|
||||||
|
arrived: tokio::sync::Notify::new(),
|
||||||
|
release: tokio::sync::Notify::new(),
|
||||||
|
});
|
||||||
|
let mut slot = RESTORE_FINALIZE_BARRIER
|
||||||
|
.get_or_init(|| std::sync::Mutex::new(None))
|
||||||
|
.lock()
|
||||||
|
.expect("restore finalize barrier mutex should not poison");
|
||||||
|
assert!(slot.is_none(), "restore finalize barrier must be installed by one test at a time");
|
||||||
|
*slot = Some(Arc::clone(&state));
|
||||||
|
Self { state }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::set_disk) async fn wait_until_paused(&self) {
|
||||||
|
self.state.arrived.notified().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::set_disk) fn release(&self) {
|
||||||
|
self.state.release.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
impl Drop for RestoreFinalizeBarrier {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let mut slot = RESTORE_FINALIZE_BARRIER
|
||||||
|
.get_or_init(|| std::sync::Mutex::new(None))
|
||||||
|
.lock()
|
||||||
|
.expect("restore finalize barrier mutex should not poison");
|
||||||
|
if slot.as_ref().is_some_and(|state| Arc::ptr_eq(state, &self.state)) {
|
||||||
|
*slot = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
async fn maybe_pause_restore_finalize(bucket: &str, object: &str) {
|
||||||
|
let barrier = RESTORE_FINALIZE_BARRIER
|
||||||
|
.get_or_init(|| std::sync::Mutex::new(None))
|
||||||
|
.lock()
|
||||||
|
.expect("restore finalize barrier mutex should not poison")
|
||||||
|
.as_ref()
|
||||||
|
.filter(|barrier| barrier.bucket == bucket && barrier.object == object)
|
||||||
|
.cloned();
|
||||||
|
if let Some(barrier) = barrier {
|
||||||
|
barrier.arrived.notify_one();
|
||||||
|
barrier.release.notified().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
struct RestoreCleanupIdentity {
|
struct RestoreCleanupIdentity {
|
||||||
version_id: Option<Uuid>,
|
version_id: Option<Uuid>,
|
||||||
@@ -80,7 +152,7 @@ impl SetDisks {
|
|||||||
.clone()
|
.clone()
|
||||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||||
let version_id = expected.version_id.map(|v| v.to_string());
|
let version_id = expected.version_id.map(|v| v.to_string());
|
||||||
let _lock_guard = if !opts.no_lock {
|
let lock_guard = if !opts.no_lock {
|
||||||
Some(
|
Some(
|
||||||
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
|
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
|
||||||
.await?,
|
.await?,
|
||||||
@@ -99,13 +171,16 @@ impl SetDisks {
|
|||||||
.get_object_fileinfo_gated(bucket, object, &read_opts, false, false)
|
.get_object_fileinfo_gated(bucket, object, &read_opts, false, false)
|
||||||
.await?
|
.await?
|
||||||
.into_owned();
|
.into_owned();
|
||||||
if let Some(expected_operation_id) = expected_operation_id {
|
if let Some(expected_operation_id) = expected_operation_id
|
||||||
require_restore_operation_id(&fi.metadata, expected_operation_id)?;
|
&& restore_operation_id_from_metadata(&fi.metadata)?.is_some_and(|actual| actual != expected_operation_id)
|
||||||
|
{
|
||||||
|
return Err(Error::other("restore operation id changed before metadata finalization"));
|
||||||
}
|
}
|
||||||
if !expected.matches_file_info(&fi, &expected_etag) {
|
if !expected.matches_file_info(&fi, &expected_etag) {
|
||||||
return Err(Error::other("restored object changed before restore metadata finalization"));
|
return Err(Error::other("restored object changed before restore metadata finalization"));
|
||||||
}
|
}
|
||||||
ensure_restore_metadata_lock_held(bucket, object, opts, "restore_finalize_metadata")?;
|
#[cfg(all(test, feature = "test-util"))]
|
||||||
|
maybe_pause_restore_finalize(bucket, object).await;
|
||||||
let restore_expiry =
|
let restore_expiry =
|
||||||
lifecycle::expected_expiry_time(OffsetDateTime::now_utc(), opts.transition.restore_request.days.unwrap_or(1));
|
lifecycle::expected_expiry_time(OffsetDateTime::now_utc(), opts.transition.restore_request.days.unwrap_or(1));
|
||||||
fi.metadata.insert(
|
fi.metadata.insert(
|
||||||
@@ -117,6 +192,10 @@ impl SetDisks {
|
|||||||
.to_string(),
|
.to_string(),
|
||||||
);
|
);
|
||||||
self.invalidate_get_object_metadata_cache(bucket, object).await;
|
self.invalidate_get_object_metadata_cache(bucket, object).await;
|
||||||
|
ensure_restore_metadata_lock_held(bucket, object, opts, "restore_finalize_metadata")?;
|
||||||
|
if lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost()) {
|
||||||
|
return Err(Error::other("restore finalization lock lost before metadata update"));
|
||||||
|
}
|
||||||
self.update_object_meta_with_opts(
|
self.update_object_meta_with_opts(
|
||||||
bucket,
|
bucket,
|
||||||
object,
|
object,
|
||||||
|
|||||||
@@ -601,7 +601,7 @@ impl ECStore {
|
|||||||
|
|
||||||
#[instrument(skip(self))]
|
#[instrument(skip(self))]
|
||||||
pub(super) async fn handle_list_bucket(&self, opts: &BucketOptions) -> Result<Vec<BucketInfo>> {
|
pub(super) async fn handle_list_bucket(&self, opts: &BucketOptions) -> Result<Vec<BucketInfo>> {
|
||||||
// TODO: opts.cached
|
// TODO(backlog): support cached bucket listing via opts.cached
|
||||||
|
|
||||||
let mut buckets = self.peer_sys.list_bucket(opts).await?;
|
let mut buckets = self.peer_sys.list_bucket(opts).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -4673,7 +4673,7 @@ async fn gather_results(
|
|||||||
entry.name = entry.name.replace("\\", "/");
|
entry.name = entry.name.replace("\\", "/");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: rx.recv()
|
// TODO(backlog): integrate rx.recv() for incremental listing results
|
||||||
|
|
||||||
if let Some(marker) = &opts.marker
|
if let Some(marker) = &opts.marker
|
||||||
&& ((!opts.include_marker && &entry.name <= marker) || (opts.include_marker && &entry.name < marker))
|
&& ((!opts.include_marker && &entry.name <= marker) || (opts.include_marker && &entry.name < marker))
|
||||||
@@ -4703,7 +4703,7 @@ async fn gather_results(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Lifecycle
|
// TODO(backlog): integrate lifecycle evaluation during object listing
|
||||||
|
|
||||||
entries.push(Some(entry));
|
entries.push(Some(entry));
|
||||||
candidate_entries += 1;
|
candidate_entries += 1;
|
||||||
|
|||||||
@@ -343,6 +343,23 @@ impl ECStore {
|
|||||||
let (decommission, rebalance) = tokio::join!(self.is_decommission_running(), self.is_rebalance_started());
|
let (decommission, rebalance) = tokio::join!(self.is_decommission_running(), self.is_rebalance_started());
|
||||||
decommission || rebalance
|
decommission || rebalance
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns whether scanner metadata may still be hidden by a local
|
||||||
|
/// data-movement state. Terminal failed/canceled decommission entries
|
||||||
|
/// remain suspended until an operator clears or retries them, so they are
|
||||||
|
/// a publication barrier even after the worker has stopped.
|
||||||
|
pub async fn scanner_data_usage_publication_blocked(&self) -> bool {
|
||||||
|
if self.scanner_data_movement_active().await {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let pool_meta = self.pool_meta.read().await;
|
||||||
|
pool_meta.pools.iter().any(|pool| {
|
||||||
|
pool.decommission
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|info| !info.queued && (info.failed || info.canceled))
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// impl Clone for ECStore {
|
// impl Clone for ECStore {
|
||||||
@@ -875,6 +892,7 @@ impl crate::storage_api_contracts::admin::StorageAdminApi for ECStore {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::core::pools::{PoolDecommissionInfo, PoolStatus};
|
||||||
use crate::layout::endpoints::{Endpoints, PoolEndpoints, SetupType};
|
use crate::layout::endpoints::{Endpoints, PoolEndpoints, SetupType};
|
||||||
use crate::runtime::global::reset_local_disk_test_state;
|
use crate::runtime::global::reset_local_disk_test_state;
|
||||||
use crate::runtime::sources::{clear_local_disk_id_map_for_test, local_disk_path_by_id};
|
use crate::runtime::sources::{clear_local_disk_id_map_for_test, local_disk_path_by_id};
|
||||||
@@ -911,6 +929,72 @@ mod tests {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn scanner_data_usage_publication_blocks_active_and_unqueued_terminal_decommission() {
|
||||||
|
let store = build_store_with_ctx(Arc::new(InstanceContext::new()));
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
"active",
|
||||||
|
PoolDecommissionInfo {
|
||||||
|
start_time: Some(OffsetDateTime::now_utc()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"failed",
|
||||||
|
PoolDecommissionInfo {
|
||||||
|
failed: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"canceled",
|
||||||
|
PoolDecommissionInfo {
|
||||||
|
canceled: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"queued_failed",
|
||||||
|
PoolDecommissionInfo {
|
||||||
|
failed: true,
|
||||||
|
queued: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"complete",
|
||||||
|
PoolDecommissionInfo {
|
||||||
|
complete: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
("idle", PoolDecommissionInfo::default(), false),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (name, decommission, expected) in cases {
|
||||||
|
*store.pool_meta.write().await = PoolMeta {
|
||||||
|
pools: vec![PoolStatus {
|
||||||
|
id: 0,
|
||||||
|
cmd_line: format!("scanner-publication-{name}"),
|
||||||
|
last_update: OffsetDateTime::now_utc(),
|
||||||
|
decommission: Some(decommission),
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
store.scanner_data_usage_publication_blocked().await,
|
||||||
|
expected,
|
||||||
|
"unexpected scanner publication barrier state for {name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// The object graph is the isolation carrier: two ECStore instances holding
|
// The object graph is the isolation carrier: two ECStore instances holding
|
||||||
// distinct contexts report independent erasure state through their real
|
// distinct contexts report independent erasure state through their real
|
||||||
// `&self` accessors — no cross-contamination.
|
// `&self` accessors — no cross-contamination.
|
||||||
|
|||||||
@@ -332,7 +332,7 @@ impl ECStore {
|
|||||||
let expected_incarnation_id = opts.expected_bucket_incarnation_id;
|
let expected_incarnation_id = opts.expected_bucket_incarnation_id;
|
||||||
|
|
||||||
if request.prefix.is_empty() {
|
if request.prefix.is_empty() {
|
||||||
// TODO: return from cache
|
// TODO(backlog): return cached multipart listing when prefix is empty
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.single_pool() {
|
if self.single_pool() {
|
||||||
@@ -610,7 +610,7 @@ impl ECStore {
|
|||||||
let (opts, _bucket_lifecycle_guard) = self.guard_multipart_bucket_incarnation(bucket, opts).await?;
|
let (opts, _bucket_lifecycle_guard) = self.guard_multipart_bucket_incarnation(bucket, opts).await?;
|
||||||
let opts = &opts;
|
let opts = &opts;
|
||||||
|
|
||||||
// TODO: defer DeleteUploadID
|
// TODO(backlog): defer DeleteUploadID to background for faster abort response
|
||||||
|
|
||||||
if self.single_pool() {
|
if self.single_pool() {
|
||||||
return self.pools[0].abort_multipart_upload(bucket, object, upload_id, opts).await;
|
return self.pools[0].abort_multipart_upload(bucket, object, upload_id, opts).await;
|
||||||
|
|||||||
@@ -385,7 +385,7 @@ impl ECStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn is_suspended(&self, idx: usize) -> bool {
|
pub(super) async fn is_suspended(&self, idx: usize) -> bool {
|
||||||
// TODO: LOCK
|
// TODO(backlog): acquire pool metadata lock for consistent suspension check
|
||||||
|
|
||||||
let pool_meta = self.pool_meta.read().await;
|
let pool_meta = self.pool_meta.read().await;
|
||||||
|
|
||||||
|
|||||||
@@ -1640,6 +1640,60 @@ mod tests {
|
|||||||
assert_eq!(payload["items"].as_array().expect("items should be an array").len(), 0);
|
assert_eq!(payload["items"].as_array().expect("items should be an array").len(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_process_query_request_reports_displaced_terminal_detail() {
|
||||||
|
let heal_manager = Arc::new(HealManager::new(
|
||||||
|
Arc::new(MockStorage),
|
||||||
|
Some(HealConfig {
|
||||||
|
queue_size: 1,
|
||||||
|
..HealConfig::default()
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let mut displaced = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "displaced-channel".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
displaced.id = "displaced-channel-task".to_string();
|
||||||
|
let displaced_id = displaced.id.clone();
|
||||||
|
heal_manager
|
||||||
|
.submit_heal_request(displaced)
|
||||||
|
.await
|
||||||
|
.expect("initial channel task should queue");
|
||||||
|
heal_manager
|
||||||
|
.submit_heal_request(HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "successor-channel".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::High,
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
.expect("successor channel task should displace the initial task");
|
||||||
|
|
||||||
|
let processor = HealChannelProcessor::new(heal_manager);
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
processor
|
||||||
|
.process_query_request("displaced-channel".to_string(), displaced_id, None, tx)
|
||||||
|
.await
|
||||||
|
.expect("displaced query should process");
|
||||||
|
let response = rx
|
||||||
|
.await
|
||||||
|
.expect("query response should be returned")
|
||||||
|
.expect("displaced query should remain successful");
|
||||||
|
let payload: serde_json::Value = serde_json::from_slice(response.data.as_deref().expect("status payload should exist"))
|
||||||
|
.expect("status payload should be json");
|
||||||
|
assert_eq!(payload["summary"], "stopped");
|
||||||
|
assert!(
|
||||||
|
response
|
||||||
|
.error
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|detail| detail.contains("reason=displaced"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_process_query_request_reports_running_for_queued_task() {
|
async fn test_process_query_request_reports_running_for_queued_task() {
|
||||||
let heal_manager = create_test_heal_manager();
|
let heal_manager = create_test_heal_manager();
|
||||||
|
|||||||
+105
-10
@@ -40,6 +40,7 @@ use tracing::{debug, error, info, warn};
|
|||||||
use super::{DiskError, Endpoint, HealDiskExt as _, local_disk_map_read};
|
use super::{DiskError, Endpoint, HealDiskExt as _, local_disk_map_read};
|
||||||
|
|
||||||
const KEEP_HEAL_TASK_STATUS_DURATION: Duration = Duration::from_secs(10 * 60);
|
const KEEP_HEAL_TASK_STATUS_DURATION: Duration = Duration::from_secs(10 * 60);
|
||||||
|
const DISPLACED_HEAL_REASON: &str = "reason=displaced; retry_hint=submit_again";
|
||||||
const LOG_COMPONENT_HEAL: &str = "heal";
|
const LOG_COMPONENT_HEAL: &str = "heal";
|
||||||
const LOG_SUBSYSTEM_DISK_SCANNER: &str = "disk_scanner";
|
const LOG_SUBSYSTEM_DISK_SCANNER: &str = "disk_scanner";
|
||||||
const LOG_SUBSYSTEM_MANAGER: &str = "manager";
|
const LOG_SUBSYSTEM_MANAGER: &str = "manager";
|
||||||
@@ -120,26 +121,30 @@ struct MrfRepairNoticeTarget {
|
|||||||
version_id: Option<[u8; 16]>,
|
version_id: Option<[u8; 16]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone)]
|
||||||
struct HealAdmissionDecision {
|
struct HealAdmissionDecision {
|
||||||
result: HealAdmissionResult,
|
result: HealAdmissionResult,
|
||||||
displaced_task_id: Option<String>,
|
displaced_request: Option<HealRequest>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HealAdmissionDecision {
|
impl HealAdmissionDecision {
|
||||||
const fn new(result: HealAdmissionResult) -> Self {
|
const fn new(result: HealAdmissionResult) -> Self {
|
||||||
Self {
|
Self {
|
||||||
result,
|
result,
|
||||||
displaced_task_id: None,
|
displaced_request: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn accepted_with_displacement(displaced_task_id: String) -> Self {
|
fn accepted_with_displacement(displaced_request: HealRequest) -> Self {
|
||||||
Self {
|
Self {
|
||||||
result: HealAdmissionResult::Accepted,
|
result: HealAdmissionResult::Accepted,
|
||||||
displaced_task_id: Some(displaced_task_id),
|
displaced_request: Some(displaced_request),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn displaced_task_id(&self) -> Option<&str> {
|
||||||
|
self.displaced_request.as_ref().map(|request| request.id.as_str())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lock_mrf_repair_notice_targets(
|
fn lock_mrf_repair_notice_targets(
|
||||||
@@ -151,6 +156,55 @@ fn lock_mrf_repair_notice_targets(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn lock_displaced_terminals(
|
||||||
|
registry: &StdMutex<HashMap<String, Arc<CompletedHealStatus>>>,
|
||||||
|
) -> StdMutexGuard<'_, HashMap<String, Arc<CompletedHealStatus>>> {
|
||||||
|
match registry.lock() {
|
||||||
|
Ok(guard) => guard,
|
||||||
|
Err(poisoned) => poisoned.into_inner(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_displaced_terminal(
|
||||||
|
registry: &StdMutex<HashMap<String, Arc<CompletedHealStatus>>>,
|
||||||
|
request: &HealRequest,
|
||||||
|
) -> Arc<CompletedHealStatus> {
|
||||||
|
let terminal = Arc::new(CompletedHealStatus {
|
||||||
|
heal_type: request.heal_type.clone(),
|
||||||
|
status: HealTaskStatus::Failed {
|
||||||
|
error: format!("heal task displaced by a higher-priority request ({DISPLACED_HEAL_REASON})"),
|
||||||
|
},
|
||||||
|
result_items_truncated: false,
|
||||||
|
completed_at: SystemTime::now(),
|
||||||
|
seqed_items: Vec::new(),
|
||||||
|
next_seq: 0,
|
||||||
|
min_seq: 0,
|
||||||
|
});
|
||||||
|
let mut terminals = lock_displaced_terminals(registry);
|
||||||
|
prune_completed_heal_statuses(&mut terminals);
|
||||||
|
terminals.insert(request.id.clone(), Arc::clone(&terminal));
|
||||||
|
terminal
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn remove_displaced_task_aliases(
|
||||||
|
aliases: &Arc<Mutex<HashMap<String, HealTaskAlias>>>,
|
||||||
|
terminals: &StdMutex<HashMap<String, Arc<CompletedHealStatus>>>,
|
||||||
|
task_id: &str,
|
||||||
|
terminal: &Arc<CompletedHealStatus>,
|
||||||
|
) {
|
||||||
|
let mut aliases = aliases.lock().await;
|
||||||
|
let alias_ids = aliases
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(alias_id, alias)| (alias.task_id == task_id).then_some(alias_id.clone()))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let mut displaced_terminals = lock_displaced_terminals(terminals);
|
||||||
|
prune_completed_heal_statuses(&mut displaced_terminals);
|
||||||
|
for alias_id in alias_ids {
|
||||||
|
displaced_terminals.insert(alias_id, Arc::clone(terminal));
|
||||||
|
}
|
||||||
|
aliases.retain(|alias_id, alias| alias_id != task_id && alias.task_id != task_id);
|
||||||
|
}
|
||||||
|
|
||||||
async fn remove_task_aliases_for_task(registry: &Arc<Mutex<HashMap<String, HealTaskAlias>>>, task_id: &str) {
|
async fn remove_task_aliases_for_task(registry: &Arc<Mutex<HashMap<String, HealTaskAlias>>>, task_id: &str) {
|
||||||
registry
|
registry
|
||||||
.lock()
|
.lock()
|
||||||
@@ -618,6 +672,14 @@ pub struct HealManager {
|
|||||||
/// are shared so the lookup helper can hand a completed entry to a
|
/// are shared so the lookup helper can hand a completed entry to a
|
||||||
/// caller without cloning the retained result window.
|
/// caller without cloning the retained result window.
|
||||||
completed_heals: Arc<Mutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
completed_heals: Arc<Mutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
||||||
|
/// Terminals for requests removed by priority displacement. An Accepted
|
||||||
|
/// task ID remains queryable for the same process lifetime and the normal
|
||||||
|
/// ten-minute status TTL; clients should treat `reason=displaced` as a
|
||||||
|
/// terminal result and submit a fresh request. This sidecar is synchronous
|
||||||
|
/// so admission can publish the terminal while the queue transition is
|
||||||
|
/// still under its lock, without awaiting another tokio lock. Queue state
|
||||||
|
/// is process-local, so this guarantee does not extend across restart.
|
||||||
|
displaced_terminals: Arc<StdMutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
||||||
/// Client tokens merged into an existing task id.
|
/// Client tokens merged into an existing task id.
|
||||||
task_aliases: Arc<Mutex<HashMap<String, HealTaskAlias>>>,
|
task_aliases: Arc<Mutex<HashMap<String, HealTaskAlias>>>,
|
||||||
/// Heal tasks waiting for a retry backoff to expire.
|
/// Heal tasks waiting for a retry backoff to expire.
|
||||||
@@ -659,6 +721,7 @@ struct HealQueueContext<'a> {
|
|||||||
heal_queue: &'a Arc<Mutex<PriorityHealQueue>>,
|
heal_queue: &'a Arc<Mutex<PriorityHealQueue>>,
|
||||||
active_heals: &'a Arc<Mutex<HashMap<String, Arc<HealTask>>>>,
|
active_heals: &'a Arc<Mutex<HashMap<String, Arc<HealTask>>>>,
|
||||||
completed_heals: &'a Arc<Mutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
completed_heals: &'a Arc<Mutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
||||||
|
displaced_terminals: &'a Arc<StdMutex<HashMap<String, Arc<CompletedHealStatus>>>>,
|
||||||
task_aliases: &'a Arc<Mutex<HashMap<String, HealTaskAlias>>>,
|
task_aliases: &'a Arc<Mutex<HashMap<String, HealTaskAlias>>>,
|
||||||
retrying_heals: &'a Arc<Mutex<HashMap<String, RetryingHeal>>>,
|
retrying_heals: &'a Arc<Mutex<HashMap<String, RetryingHeal>>>,
|
||||||
mrf_repair_notice_targets: &'a Arc<StdMutex<HashMap<String, Vec<MrfRepairNoticeTarget>>>>,
|
mrf_repair_notice_targets: &'a Arc<StdMutex<HashMap<String, Vec<MrfRepairNoticeTarget>>>>,
|
||||||
@@ -874,7 +937,7 @@ impl HealManager {
|
|||||||
result = "accepted_by_displacement",
|
result = "accepted_by_displacement",
|
||||||
"Heal queue request accepted by displacement"
|
"Heal queue request accepted by displacement"
|
||||||
});
|
});
|
||||||
return HealAdmissionDecision::accepted_with_displacement(displaced.id);
|
return HealAdmissionDecision::accepted_with_displacement(displaced);
|
||||||
}
|
}
|
||||||
|
|
||||||
demote_to_debug_when!(per_object_request, warn, target: "rustfs::heal::manager", {
|
demote_to_debug_when!(per_object_request, warn, target: "rustfs::heal::manager", {
|
||||||
@@ -1105,6 +1168,7 @@ impl HealManager {
|
|||||||
active_heals: Arc::new(Mutex::new(HashMap::new())),
|
active_heals: Arc::new(Mutex::new(HashMap::new())),
|
||||||
heal_queue: Arc::new(Mutex::new(PriorityHealQueue::new())),
|
heal_queue: Arc::new(Mutex::new(PriorityHealQueue::new())),
|
||||||
completed_heals: Arc::new(Mutex::new(HashMap::new())),
|
completed_heals: Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
displaced_terminals: Arc::new(StdMutex::new(HashMap::new())),
|
||||||
task_aliases: Arc::new(Mutex::new(HashMap::new())),
|
task_aliases: Arc::new(Mutex::new(HashMap::new())),
|
||||||
retrying_heals: Arc::new(Mutex::new(HashMap::new())),
|
retrying_heals: Arc::new(Mutex::new(HashMap::new())),
|
||||||
mrf_repair_notice_targets: Arc::new(StdMutex::new(HashMap::new())),
|
mrf_repair_notice_targets: Arc::new(StdMutex::new(HashMap::new())),
|
||||||
@@ -1209,6 +1273,10 @@ impl HealManager {
|
|||||||
active_heals.clear();
|
active_heals.clear();
|
||||||
publish_active_heal_count(&active_heals);
|
publish_active_heal_count(&active_heals);
|
||||||
self.completed_heals.lock().await.clear();
|
self.completed_heals.lock().await.clear();
|
||||||
|
// Do not let the synchronous guard live across the following async lock.
|
||||||
|
{
|
||||||
|
lock_displaced_terminals(&self.displaced_terminals).clear();
|
||||||
|
}
|
||||||
self.task_aliases.lock().await.clear();
|
self.task_aliases.lock().await.clear();
|
||||||
self.retrying_heals.lock().await.clear();
|
self.retrying_heals.lock().await.clear();
|
||||||
lock_mrf_repair_notice_targets(&self.mrf_repair_notice_targets).clear();
|
lock_mrf_repair_notice_targets(&self.mrf_repair_notice_targets).clear();
|
||||||
@@ -1459,7 +1527,11 @@ impl HealManager {
|
|||||||
task_id = queued_id.to_owned();
|
task_id = queued_id.to_owned();
|
||||||
}
|
}
|
||||||
let should_notify = matches!(admission, HealAdmissionResult::Accepted) && config.event_driven_scheduler_enable;
|
let should_notify = matches!(admission, HealAdmissionResult::Accepted) && config.event_driven_scheduler_enable;
|
||||||
let displaced_task_id = admission_decision.displaced_task_id;
|
let displaced_task_id = admission_decision.displaced_task_id().map(ToOwned::to_owned);
|
||||||
|
let displaced_terminal = admission_decision
|
||||||
|
.displaced_request
|
||||||
|
.as_ref()
|
||||||
|
.map(|request| record_displaced_terminal(&self.displaced_terminals, request));
|
||||||
if matches!(admission, HealAdmissionResult::Accepted | HealAdmissionResult::Merged)
|
if matches!(admission, HealAdmissionResult::Accepted | HealAdmissionResult::Merged)
|
||||||
&& let Some(target) = mrf_notice_target
|
&& let Some(target) = mrf_notice_target
|
||||||
{
|
{
|
||||||
@@ -1473,8 +1545,12 @@ impl HealManager {
|
|||||||
drop(queue);
|
drop(queue);
|
||||||
drop(active_heals);
|
drop(active_heals);
|
||||||
|
|
||||||
if let Some(displaced_task_id) = displaced_task_id {
|
if let (Some(displaced_task_id), Some(displaced_terminal)) = (displaced_task_id, displaced_terminal) {
|
||||||
self.remove_aliases_for_task(&displaced_task_id).await;
|
// The queue has already removed the displaced request, so the
|
||||||
|
// synchronous terminal sidecar was published before aliases and
|
||||||
|
// MRF ownership are cleaned up.
|
||||||
|
remove_displaced_task_aliases(&self.task_aliases, &self.displaced_terminals, &displaced_task_id, &displaced_terminal)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
if should_notify {
|
if should_notify {
|
||||||
@@ -1549,6 +1625,15 @@ impl HealManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if terminal_completed.is_none() {
|
||||||
|
let mut displaced_terminals = lock_displaced_terminals(&self.displaced_terminals);
|
||||||
|
prune_completed_heal_statuses(&mut displaced_terminals);
|
||||||
|
terminal_completed = displaced_terminals
|
||||||
|
.get(canonical_task_id)
|
||||||
|
.filter(|terminal| matches_path(&terminal.heal_type))
|
||||||
|
.cloned();
|
||||||
|
}
|
||||||
|
|
||||||
match terminal_completed {
|
match terminal_completed {
|
||||||
Some(completed) => TaskStateLookup::Completed(completed),
|
Some(completed) => TaskStateLookup::Completed(completed),
|
||||||
None => TaskStateLookup::NotFound,
|
None => TaskStateLookup::NotFound,
|
||||||
@@ -1669,9 +1754,19 @@ impl HealManager {
|
|||||||
|
|
||||||
let mut completed_heals = self.completed_heals.lock().await;
|
let mut completed_heals = self.completed_heals.lock().await;
|
||||||
prune_completed_heal_statuses(&mut completed_heals);
|
prune_completed_heal_statuses(&mut completed_heals);
|
||||||
completed_heals
|
if completed_heals
|
||||||
.values()
|
.values()
|
||||||
.any(|completed| heal_type_matches_path(&completed.heal_type, heal_path))
|
.any(|completed| heal_type_matches_path(&completed.heal_type, heal_path))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
drop(completed_heals);
|
||||||
|
|
||||||
|
let mut displaced_terminals = lock_displaced_terminals(&self.displaced_terminals);
|
||||||
|
prune_completed_heal_statuses(&mut displaced_terminals);
|
||||||
|
displaced_terminals
|
||||||
|
.values()
|
||||||
|
.any(|terminal| heal_type_matches_path(&terminal.heal_type, heal_path))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get task progress
|
/// Get task progress
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ impl HealManager {
|
|||||||
let heal_queue = self.heal_queue.clone();
|
let heal_queue = self.heal_queue.clone();
|
||||||
let active_heals = self.active_heals.clone();
|
let active_heals = self.active_heals.clone();
|
||||||
let task_aliases = self.task_aliases.clone();
|
let task_aliases = self.task_aliases.clone();
|
||||||
|
let displaced_terminals = self.displaced_terminals.clone();
|
||||||
let mrf_repair_notice_targets = self.mrf_repair_notice_targets.clone();
|
let mrf_repair_notice_targets = self.mrf_repair_notice_targets.clone();
|
||||||
let storage = self.storage.clone();
|
let storage = self.storage.clone();
|
||||||
let replacement_recovery_anchors = self.replacement_recovery_anchors.clone();
|
let replacement_recovery_anchors = self.replacement_recovery_anchors.clone();
|
||||||
@@ -481,6 +482,10 @@ impl HealManager {
|
|||||||
let admission = admission_decision.result;
|
let admission = admission_decision.result;
|
||||||
let should_notify =
|
let should_notify =
|
||||||
matches!(admission, HealAdmissionResult::Accepted) && config.event_driven_scheduler_enable;
|
matches!(admission, HealAdmissionResult::Accepted) && config.event_driven_scheduler_enable;
|
||||||
|
let displaced_terminal = admission_decision
|
||||||
|
.displaced_request
|
||||||
|
.as_ref()
|
||||||
|
.map(|request| record_displaced_terminal(&displaced_terminals, request));
|
||||||
if matches!(admission, HealAdmissionResult::Accepted)
|
if matches!(admission, HealAdmissionResult::Accepted)
|
||||||
&& let Some(anchor) = recovery_anchor
|
&& let Some(anchor) = recovery_anchor
|
||||||
{
|
{
|
||||||
@@ -491,8 +496,16 @@ impl HealManager {
|
|||||||
}
|
}
|
||||||
drop(queue);
|
drop(queue);
|
||||||
drop(config);
|
drop(config);
|
||||||
if let Some(displaced_task_id) = admission_decision.displaced_task_id {
|
if let (Some(displaced_task_id), Some(displaced_terminal)) =
|
||||||
remove_task_aliases_for_task(&task_aliases, &displaced_task_id).await;
|
(admission_decision.displaced_task_id().map(ToOwned::to_owned), displaced_terminal)
|
||||||
|
{
|
||||||
|
remove_displaced_task_aliases(
|
||||||
|
&task_aliases,
|
||||||
|
&displaced_terminals,
|
||||||
|
&displaced_task_id,
|
||||||
|
&displaced_terminal,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
lock_mrf_repair_notice_targets(&mrf_repair_notice_targets).remove(&displaced_task_id);
|
lock_mrf_repair_notice_targets(&mrf_repair_notice_targets).remove(&displaced_task_id);
|
||||||
}
|
}
|
||||||
if matches!(admission, HealAdmissionResult::Accepted) {
|
if matches!(admission, HealAdmissionResult::Accepted) {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ impl HealManager {
|
|||||||
let heal_queue = self.heal_queue.clone();
|
let heal_queue = self.heal_queue.clone();
|
||||||
let active_heals = self.active_heals.clone();
|
let active_heals = self.active_heals.clone();
|
||||||
let completed_heals = self.completed_heals.clone();
|
let completed_heals = self.completed_heals.clone();
|
||||||
|
let displaced_terminals = self.displaced_terminals.clone();
|
||||||
let task_aliases = self.task_aliases.clone();
|
let task_aliases = self.task_aliases.clone();
|
||||||
let retrying_heals = self.retrying_heals.clone();
|
let retrying_heals = self.retrying_heals.clone();
|
||||||
let mrf_repair_notice_targets = self.mrf_repair_notice_targets.clone();
|
let mrf_repair_notice_targets = self.mrf_repair_notice_targets.clone();
|
||||||
@@ -53,6 +54,7 @@ impl HealManager {
|
|||||||
heal_queue: &heal_queue,
|
heal_queue: &heal_queue,
|
||||||
active_heals: &active_heals,
|
active_heals: &active_heals,
|
||||||
completed_heals: &completed_heals,
|
completed_heals: &completed_heals,
|
||||||
|
displaced_terminals: &displaced_terminals,
|
||||||
task_aliases: &task_aliases,
|
task_aliases: &task_aliases,
|
||||||
retrying_heals: &retrying_heals,
|
retrying_heals: &retrying_heals,
|
||||||
mrf_repair_notice_targets: &mrf_repair_notice_targets,
|
mrf_repair_notice_targets: &mrf_repair_notice_targets,
|
||||||
@@ -71,6 +73,7 @@ impl HealManager {
|
|||||||
heal_queue: &heal_queue,
|
heal_queue: &heal_queue,
|
||||||
active_heals: &active_heals,
|
active_heals: &active_heals,
|
||||||
completed_heals: &completed_heals,
|
completed_heals: &completed_heals,
|
||||||
|
displaced_terminals: &displaced_terminals,
|
||||||
task_aliases: &task_aliases,
|
task_aliases: &task_aliases,
|
||||||
retrying_heals: &retrying_heals,
|
retrying_heals: &retrying_heals,
|
||||||
mrf_repair_notice_targets: &mrf_repair_notice_targets,
|
mrf_repair_notice_targets: &mrf_repair_notice_targets,
|
||||||
@@ -98,6 +101,7 @@ impl HealManager {
|
|||||||
heal_queue,
|
heal_queue,
|
||||||
active_heals,
|
active_heals,
|
||||||
completed_heals,
|
completed_heals,
|
||||||
|
displaced_terminals,
|
||||||
task_aliases,
|
task_aliases,
|
||||||
retrying_heals,
|
retrying_heals,
|
||||||
mrf_repair_notice_targets,
|
mrf_repair_notice_targets,
|
||||||
@@ -183,6 +187,7 @@ impl HealManager {
|
|||||||
let active_heals_clone = active_heals.clone();
|
let active_heals_clone = active_heals.clone();
|
||||||
let heal_queue_clone = heal_queue.clone();
|
let heal_queue_clone = heal_queue.clone();
|
||||||
let completed_heals_clone = completed_heals.clone();
|
let completed_heals_clone = completed_heals.clone();
|
||||||
|
let displaced_terminals_clone = displaced_terminals.clone();
|
||||||
let task_aliases_clone = task_aliases.clone();
|
let task_aliases_clone = task_aliases.clone();
|
||||||
let retrying_heals_clone = retrying_heals.clone();
|
let retrying_heals_clone = retrying_heals.clone();
|
||||||
let mrf_repair_notice_targets_clone = mrf_repair_notice_targets.clone();
|
let mrf_repair_notice_targets_clone = mrf_repair_notice_targets.clone();
|
||||||
@@ -363,6 +368,7 @@ impl HealManager {
|
|||||||
let retry_heal_queue = heal_queue_clone.clone();
|
let retry_heal_queue = heal_queue_clone.clone();
|
||||||
let retrying_heals_for_spawn = retrying_heals_clone.clone();
|
let retrying_heals_for_spawn = retrying_heals_clone.clone();
|
||||||
let retry_task_aliases = task_aliases_clone.clone();
|
let retry_task_aliases = task_aliases_clone.clone();
|
||||||
|
let retry_displaced_terminals = displaced_terminals_clone.clone();
|
||||||
let retry_mrf_repair_notice_targets = mrf_repair_notice_targets_clone.clone();
|
let retry_mrf_repair_notice_targets = mrf_repair_notice_targets_clone.clone();
|
||||||
let retry_completed_heals = completed_heals_clone.clone();
|
let retry_completed_heals = completed_heals_clone.clone();
|
||||||
let retry_notify = notify_clone.clone();
|
let retry_notify = notify_clone.clone();
|
||||||
@@ -430,6 +436,14 @@ impl HealManager {
|
|||||||
let admission = admission_decision.result;
|
let admission = admission_decision.result;
|
||||||
let should_notify = matches!(admission, HealAdmissionResult::Accepted)
|
let should_notify = matches!(admission, HealAdmissionResult::Accepted)
|
||||||
&& retry_config.event_driven_scheduler_enable;
|
&& retry_config.event_driven_scheduler_enable;
|
||||||
|
// Publish the terminal synchronously while the
|
||||||
|
// queue transition is protected. The subsequent
|
||||||
|
// queue -> retrying handoff retains the lock order
|
||||||
|
// used by operations_snapshot.
|
||||||
|
let displaced_terminal = admission_decision
|
||||||
|
.displaced_request
|
||||||
|
.as_ref()
|
||||||
|
.map(|request| record_displaced_terminal(&retry_displaced_terminals, request));
|
||||||
match admission {
|
match admission {
|
||||||
HealAdmissionResult::Accepted => {
|
HealAdmissionResult::Accepted => {
|
||||||
// Transfer ownership while holding queue -> retrying,
|
// Transfer ownership while holding queue -> retrying,
|
||||||
@@ -437,10 +451,18 @@ impl HealManager {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pause_retry_ownership_transition(&retry_request_id, true).await;
|
pause_retry_ownership_transition(&retry_request_id, true).await;
|
||||||
retrying_heals_for_spawn.lock().await.remove(&retry_request_id);
|
retrying_heals_for_spawn.lock().await.remove(&retry_request_id);
|
||||||
let displaced_task_id = admission_decision.displaced_task_id;
|
let displaced_task_id = admission_decision.displaced_task_id().map(ToOwned::to_owned);
|
||||||
drop(queue);
|
drop(queue);
|
||||||
if let Some(displaced_task_id) = displaced_task_id {
|
if let (Some(displaced_task_id), Some(displaced_terminal)) =
|
||||||
remove_task_aliases_for_task(&retry_task_aliases, &displaced_task_id).await;
|
(displaced_task_id, displaced_terminal)
|
||||||
|
{
|
||||||
|
remove_displaced_task_aliases(
|
||||||
|
&retry_task_aliases,
|
||||||
|
&retry_displaced_terminals,
|
||||||
|
&displaced_task_id,
|
||||||
|
&displaced_terminal,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
remove_mrf_repair_notice_targets(
|
remove_mrf_repair_notice_targets(
|
||||||
&retry_mrf_repair_notice_targets,
|
&retry_mrf_repair_notice_targets,
|
||||||
&displaced_task_id,
|
&displaced_task_id,
|
||||||
@@ -567,35 +589,17 @@ impl HealManager {
|
|||||||
pub(super) fn heal_request_set_key(request: &HealRequest) -> Option<String> {
|
pub(super) fn heal_request_set_key(request: &HealRequest) -> Option<String> {
|
||||||
match &request.heal_type {
|
match &request.heal_type {
|
||||||
HealType::ErasureSet { set_disk_id, .. } => Some(set_disk_id.clone()),
|
HealType::ErasureSet { set_disk_id, .. } => Some(set_disk_id.clone()),
|
||||||
HealType::Object { .. } => heal_options_set_key(&request.options),
|
HealType::Object { .. } => request.options.set_key(),
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn heal_options_set_key(options: &HealOptions) -> Option<String> {
|
|
||||||
match (options.pool_index, options.set_index) {
|
|
||||||
(Some(pool), Some(set)) => Some(format!("pool_{pool}_set_{set}")),
|
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn heal_request_type_label(request: &HealRequest) -> &'static str {
|
pub(super) fn heal_request_type_label(request: &HealRequest) -> &'static str {
|
||||||
match &request.heal_type {
|
request.heal_type.kind_label()
|
||||||
HealType::Cluster => "cluster",
|
|
||||||
HealType::Object { .. } => "object",
|
|
||||||
HealType::Bucket { .. } => "bucket",
|
|
||||||
HealType::Prefix { .. } => "prefix",
|
|
||||||
HealType::ErasureSet { .. } => "erasure_set",
|
|
||||||
HealType::Metadata { .. } => "metadata",
|
|
||||||
HealType::ECDecode { .. } => "ec_decode",
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn heal_request_set_metric_label(request: &HealRequest) -> String {
|
pub(super) fn heal_request_set_metric_label(request: &HealRequest) -> String {
|
||||||
heal_request_set_key(request).unwrap_or_else(|| match (request.options.pool_index, request.options.set_index) {
|
heal_request_set_key(request).unwrap_or_else(|| request.options.set_metric_label())
|
||||||
(Some(pool), Some(set)) => format!("pool_{pool}_set_{set}"),
|
|
||||||
_ => "global".to_string(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn record_scheduler_skip(set_label: &str) {
|
pub(super) fn record_scheduler_skip(set_label: &str) {
|
||||||
@@ -673,7 +677,7 @@ fn emit_mrf_repaired_events(targets: Vec<MrfRepairNoticeTarget>) {
|
|||||||
pub(super) fn heal_request_set_key_for_task(task: &HealTask) -> Option<String> {
|
pub(super) fn heal_request_set_key_for_task(task: &HealTask) -> Option<String> {
|
||||||
match &task.heal_type {
|
match &task.heal_type {
|
||||||
HealType::ErasureSet { set_disk_id, .. } => Some(set_disk_id.clone()),
|
HealType::ErasureSet { set_disk_id, .. } => Some(set_disk_id.clone()),
|
||||||
HealType::Object { .. } => heal_options_set_key(&task.options),
|
HealType::Object { .. } => task.options.set_key(),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ async fn process_manager_queue_once(manager: &HealManager) {
|
|||||||
heal_queue: &manager.heal_queue,
|
heal_queue: &manager.heal_queue,
|
||||||
active_heals: &manager.active_heals,
|
active_heals: &manager.active_heals,
|
||||||
completed_heals: &manager.completed_heals,
|
completed_heals: &manager.completed_heals,
|
||||||
|
displaced_terminals: &manager.displaced_terminals,
|
||||||
task_aliases: &manager.task_aliases,
|
task_aliases: &manager.task_aliases,
|
||||||
retrying_heals: &manager.retrying_heals,
|
retrying_heals: &manager.retrying_heals,
|
||||||
mrf_repair_notice_targets: &manager.mrf_repair_notice_targets,
|
mrf_repair_notice_targets: &manager.mrf_repair_notice_targets,
|
||||||
@@ -744,10 +745,8 @@ fn test_priority_queue_pop_runnable_skips_blocked_erasure_set() {
|
|||||||
let mut running = HashMap::new();
|
let mut running = HashMap::new();
|
||||||
running.insert("pool_0_set_1".to_string(), 1);
|
running.insert("pool_0_set_1".to_string(), 1);
|
||||||
|
|
||||||
let (popped, skipped_sets) = queue.pop_runnable_with_skips(
|
let (popped, skipped_sets) =
|
||||||
|request| can_schedule_request(request, &running, 1),
|
queue.pop_runnable_with_skips(|request| can_schedule_request(request, &running, 1), heal_request_set_key);
|
||||||
|request| heal_request_set_key(request),
|
|
||||||
);
|
|
||||||
let popped = popped.expect("should find runnable request");
|
let popped = popped.expect("should find runnable request");
|
||||||
|
|
||||||
assert_eq!(skipped_sets, vec!["pool_0_set_1".to_string()]);
|
assert_eq!(skipped_sets, vec!["pool_0_set_1".to_string()]);
|
||||||
@@ -788,10 +787,8 @@ fn test_priority_queue_pop_runnable_restores_all_blocked_items() {
|
|||||||
running.insert("pool_0_set_2".to_string(), 1);
|
running.insert("pool_0_set_2".to_string(), 1);
|
||||||
running.insert("pool_0_set_3".to_string(), 1);
|
running.insert("pool_0_set_3".to_string(), 1);
|
||||||
|
|
||||||
let (popped, skipped_sets) = queue.pop_runnable_with_skips(
|
let (popped, skipped_sets) =
|
||||||
|request| can_schedule_request(request, &running, 1),
|
queue.pop_runnable_with_skips(|request| can_schedule_request(request, &running, 1), heal_request_set_key);
|
||||||
|request| heal_request_set_key(request),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(popped.is_none());
|
assert!(popped.is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -843,10 +840,8 @@ fn test_priority_queue_pop_runnable_restores_deferred_with_tail() {
|
|||||||
running.insert("pool_0_set_1".to_string(), 1);
|
running.insert("pool_0_set_1".to_string(), 1);
|
||||||
running.insert("pool_0_set_2".to_string(), 1);
|
running.insert("pool_0_set_2".to_string(), 1);
|
||||||
|
|
||||||
let (popped, skipped_sets) = queue.pop_runnable_with_skips(
|
let (popped, skipped_sets) =
|
||||||
|request| can_schedule_request(request, &running, 1),
|
queue.pop_runnable_with_skips(|request| can_schedule_request(request, &running, 1), heal_request_set_key);
|
||||||
|request| heal_request_set_key(request),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(skipped_sets, vec!["pool_0_set_1".to_string(), "pool_0_set_2".to_string()]);
|
assert_eq!(skipped_sets, vec!["pool_0_set_1".to_string(), "pool_0_set_2".to_string()]);
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
@@ -904,6 +899,31 @@ fn test_can_schedule_scoped_object_request_respects_per_set_limit() {
|
|||||||
assert!(can_schedule_request(&request, &running, 2));
|
assert!(can_schedule_request(&request, &running, 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_heal_request_and_task_metric_labels_match() {
|
||||||
|
let request = HealRequest::new(
|
||||||
|
HealType::Object {
|
||||||
|
bucket: "bucket".to_string(),
|
||||||
|
object: "object".to_string(),
|
||||||
|
version_id: None,
|
||||||
|
},
|
||||||
|
HealOptions {
|
||||||
|
pool_index: Some(0),
|
||||||
|
set_index: Some(1),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
HealPriority::Normal,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(heal_request_type_label(&request), "object");
|
||||||
|
assert_eq!(heal_request_set_key(&request), Some("pool_0_set_1".to_string()));
|
||||||
|
assert_eq!(heal_request_set_metric_label(&request), "pool_0_set_1");
|
||||||
|
|
||||||
|
let task = HealTask::from_request(request, Arc::new(MockStorage));
|
||||||
|
assert_eq!(task.metric_type_label(), "object");
|
||||||
|
assert_eq!(task.metric_set_label(), "pool_0_set_1");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_submit_heal_request_returns_merged_for_duplicate() {
|
async fn test_submit_heal_request_returns_merged_for_duplicate() {
|
||||||
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
|
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
|
||||||
@@ -2759,7 +2779,10 @@ async fn test_high_priority_request_displaces_lower_priority_when_queue_full() {
|
|||||||
HealAdmissionResult::Accepted
|
HealAdmissionResult::Accepted
|
||||||
);
|
);
|
||||||
assert_eq!(manager.get_queue_length().await, 1);
|
assert_eq!(manager.get_queue_length().await, 1);
|
||||||
assert!(matches!(manager.get_task_status(&low_id).await, Err(Error::TaskNotFound { .. })));
|
assert!(matches!(
|
||||||
|
manager.get_task_status(&low_id).await,
|
||||||
|
Ok(HealTaskStatus::Failed { error }) if error.contains("reason=displaced")
|
||||||
|
));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
manager
|
manager
|
||||||
.get_task_status(&high_id)
|
.get_task_status(&high_id)
|
||||||
@@ -2769,6 +2792,263 @@ async fn test_high_priority_request_displaces_lower_priority_when_queue_full() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn displaced_task_remains_queryable() {
|
||||||
|
let manager = HealManager::new(
|
||||||
|
Arc::new(MockStorage),
|
||||||
|
Some(HealConfig {
|
||||||
|
queue_size: 1,
|
||||||
|
..HealConfig::default()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let mut displaced = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "displaced-bucket".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
displaced.id = "displaced-task".to_string();
|
||||||
|
let displaced_id = displaced.id.clone();
|
||||||
|
manager
|
||||||
|
.submit_heal_request(displaced)
|
||||||
|
.await
|
||||||
|
.expect("displaced request should queue");
|
||||||
|
|
||||||
|
let successor = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "successor-bucket".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::High,
|
||||||
|
);
|
||||||
|
manager
|
||||||
|
.submit_heal_request(successor)
|
||||||
|
.await
|
||||||
|
.expect("successor should displace low work");
|
||||||
|
|
||||||
|
let report = manager
|
||||||
|
.get_task_report(&displaced_id)
|
||||||
|
.await
|
||||||
|
.expect("displaced report should remain queryable");
|
||||||
|
assert!(matches!(report.status, HealTaskStatus::Failed { ref error } if error.contains("reason=displaced")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn displaced_archive_failure_keeps_queryable_terminal() {
|
||||||
|
let manager = HealManager::new(Arc::new(MockStorage), None);
|
||||||
|
let mut request = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "archive-failure".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
request.id = "archive-failure-task".to_string();
|
||||||
|
let request_id = request.id.clone();
|
||||||
|
// The synchronous sidecar is the authoritative fallback when the normal
|
||||||
|
// completed-task archive has no entry (the failure window that must not
|
||||||
|
// turn an Accepted ID into NotFound).
|
||||||
|
record_displaced_terminal(&manager.displaced_terminals, &request);
|
||||||
|
assert!(manager.completed_heals.lock().await.is_empty());
|
||||||
|
assert!(matches!(
|
||||||
|
manager.get_task_status(&request_id).await,
|
||||||
|
Ok(HealTaskStatus::Failed { error }) if error.contains("reason=displaced")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn scheduler_retry_displacement_keeps_evicted_task_queryable() {
|
||||||
|
let manager = Arc::new(HealManager::new(
|
||||||
|
Arc::new(MockStorage),
|
||||||
|
Some(HealConfig {
|
||||||
|
queue_size: 1,
|
||||||
|
event_driven_scheduler_enable: false,
|
||||||
|
..HealConfig::default()
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let mut retry_request = HealRequest::object("retry-transition".to_string(), "object".to_string(), None);
|
||||||
|
retry_request.priority = HealPriority::High;
|
||||||
|
let retry_id = retry_request.id.clone();
|
||||||
|
manager
|
||||||
|
.submit_heal_request(retry_request)
|
||||||
|
.await
|
||||||
|
.expect("retry request should queue");
|
||||||
|
|
||||||
|
// Process exactly one queue cycle so the retry task is spawned without a
|
||||||
|
// background scheduler consuming the filler request before the retry wakes.
|
||||||
|
process_manager_queue_once(&manager).await;
|
||||||
|
tokio::time::timeout(Duration::from_secs(1), async {
|
||||||
|
loop {
|
||||||
|
if manager.retrying_heals.lock().await.contains_key(&retry_id) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("retry request should enter backoff");
|
||||||
|
|
||||||
|
let filler = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "retry-displaced-filler".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
let filler_id = filler.id.clone();
|
||||||
|
manager
|
||||||
|
.submit_heal_request(filler)
|
||||||
|
.await
|
||||||
|
.expect("filler request should occupy the queue");
|
||||||
|
|
||||||
|
tokio::time::timeout(Duration::from_secs(5), async {
|
||||||
|
loop {
|
||||||
|
if matches!(
|
||||||
|
manager.get_task_status(&filler_id).await,
|
||||||
|
Ok(HealTaskStatus::Failed { ref error }) if error.contains("reason=displaced")
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("retry admission should displace the filler request");
|
||||||
|
assert_eq!(manager.get_queue_length().await, 1);
|
||||||
|
assert_eq!(
|
||||||
|
manager.get_task_status(&retry_id).await.expect("retry should be queued"),
|
||||||
|
HealTaskStatus::Pending
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn concurrent_displacers_produce_one_terminal_generation() {
|
||||||
|
let manager = Arc::new(HealManager::new(
|
||||||
|
Arc::new(MockStorage),
|
||||||
|
Some(HealConfig {
|
||||||
|
queue_size: 1,
|
||||||
|
..HealConfig::default()
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let mut displaced = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "concurrent-displaced".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
displaced.id = "concurrent-displaced-task".to_string();
|
||||||
|
let displaced_id = displaced.id.clone();
|
||||||
|
manager
|
||||||
|
.submit_heal_request(displaced)
|
||||||
|
.await
|
||||||
|
.expect("initial request should queue");
|
||||||
|
|
||||||
|
let first = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "concurrent-successor-a".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::High,
|
||||||
|
);
|
||||||
|
let second = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "concurrent-successor-b".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::High,
|
||||||
|
);
|
||||||
|
let (first_result, second_result) = tokio::join!(manager.submit_heal_request(first), manager.submit_heal_request(second));
|
||||||
|
let accepted = [&first_result, &second_result]
|
||||||
|
.into_iter()
|
||||||
|
.filter(|result| matches!(result, Ok(HealAdmissionResult::Accepted)))
|
||||||
|
.count();
|
||||||
|
assert_eq!(accepted, 1, "exactly one concurrent displacer should win the full queue");
|
||||||
|
assert!(
|
||||||
|
first_result.is_ok() && second_result.is_ok(),
|
||||||
|
"the losing request should receive a typed Full result"
|
||||||
|
);
|
||||||
|
let terminals = lock_displaced_terminals(&manager.displaced_terminals);
|
||||||
|
assert_eq!(terminals.len(), 1);
|
||||||
|
assert!(terminals.contains_key(&displaced_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn successor_chain_is_bounded_and_authorized() {
|
||||||
|
let manager = HealManager::new(
|
||||||
|
Arc::new(MockStorage),
|
||||||
|
Some(HealConfig {
|
||||||
|
queue_size: 1,
|
||||||
|
..HealConfig::default()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let mut original = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "authorized-original".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
original.id = "authorized-original-task".to_string();
|
||||||
|
let original_id = original.id.clone();
|
||||||
|
manager.submit_heal_request(original).await.expect("original should queue");
|
||||||
|
let mut duplicate = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "authorized-original".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
duplicate.id = "authorized-duplicate-task".to_string();
|
||||||
|
let duplicate_id = duplicate.id.clone();
|
||||||
|
manager
|
||||||
|
.submit_heal_request(duplicate)
|
||||||
|
.await
|
||||||
|
.expect("same-target duplicate should merge");
|
||||||
|
let successor = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "authorized-successor".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::High,
|
||||||
|
);
|
||||||
|
let successor_id = successor.id.clone();
|
||||||
|
manager.submit_heal_request(successor).await.expect("successor should queue");
|
||||||
|
assert!(manager.task_aliases.lock().await.is_empty());
|
||||||
|
assert!(matches!(manager.get_task_status(&original_id).await, Ok(HealTaskStatus::Failed { .. })));
|
||||||
|
assert!(matches!(manager.get_task_status(&duplicate_id).await, Ok(HealTaskStatus::Failed { .. })));
|
||||||
|
assert_eq!(
|
||||||
|
manager
|
||||||
|
.get_task_status(&successor_id)
|
||||||
|
.await
|
||||||
|
.expect("successor should remain queued"),
|
||||||
|
HealTaskStatus::Pending
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn displaced_terminal_expires_after_bounded_ttl() {
|
||||||
|
let manager = HealManager::new(Arc::new(MockStorage), None);
|
||||||
|
let mut request = HealRequest::new(
|
||||||
|
HealType::Bucket {
|
||||||
|
bucket: "expires".to_string(),
|
||||||
|
},
|
||||||
|
HealOptions::default(),
|
||||||
|
HealPriority::Low,
|
||||||
|
);
|
||||||
|
request.id = "expires-task".to_string();
|
||||||
|
let request_id = request.id.clone();
|
||||||
|
record_displaced_terminal(&manager.displaced_terminals, &request);
|
||||||
|
{
|
||||||
|
let mut terminals = lock_displaced_terminals(&manager.displaced_terminals);
|
||||||
|
let entry =
|
||||||
|
Arc::get_mut(terminals.get_mut(&request_id).expect("terminal should be retained")).expect("test owns terminal entry");
|
||||||
|
entry.completed_at = SystemTime::now() - KEEP_HEAL_TASK_STATUS_DURATION - Duration::from_secs(1);
|
||||||
|
}
|
||||||
|
assert!(matches!(manager.get_task_status(&request_id).await, Err(Error::TaskNotFound { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_displacing_registered_mrf_task_drops_notice_ownership() {
|
async fn test_displacing_registered_mrf_task_drops_notice_ownership() {
|
||||||
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
|
let storage: Arc<dyn HealStorageAPI> = Arc::new(MockStorage);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user