Compare commits

..

8 Commits

Author SHA1 Message Date
loverustfs f59daa1500 ci: require execution evidence for production ECStore recovery tests 2026-12-02 20:00:31 +08:00
loverustfs f956f54ceb test(ecstore): verify durable overwrite and multipart replay on simulated disks
Require the armed crash paths to fire and preserve the generation acknowledged to the caller. Store per-drive publication evidence so completion retries after power loss can verify the original upload and reject absent or misplaced witnesses.
2026-12-02 20:00:31 +08:00
loverustfs ffe40451c1 fix(kms): skip Transit directories when listing keys
Keep the BYOK wrapping-key directory out of key pagination so the deletion sweep can continue. Refs rustfs/rustfs#9846.
2026-12-02 19:34:25 +08:00
Rasmus Haslund 615e55825e fix(s3): echo multipart checksums in ListParts (#9814)
Carry the upload's checksum algorithm and type and each part's recorded checksums through PartInfo and render them in the ListParts response.
2026-12-02 16:08:17 +08:00
Hauser Zhi 2537596a4f chore(deps): refresh Cargo dependencies (#9842)
* chore(deps): refresh Cargo dependencies

Update TAR and Windows bindings, preserve Windows file disposition flags, and retain the recorder version shared with Kafka and Gateway RDMA. Refresh the standalone fuzz dependency graph.

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

* chore(deps): upgrade metrics to 0.25

Route metrics 0.24 consumers through the 0.25 implementation in both workspaces. Verify that legacy metrics share the recorder and that dependency resolution cannot silently restore a second recorder.

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

* chore(deps): update RustFS Kafka to 1.5.0

Resolve both Kafka packages at 1.5.0 and drop the unused metrics facade patch from the fuzz workspace. Keep the main workspace facade for the remaining Metrique dependency.

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

* fix(metrics): disambiguate the doctest extern names

Alias the 0.25 implementation so rustdoc can link it alongside the 0.24 compatibility facade. Preserve the shared recorder and dependency lockfile.

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

* chore(deps): update http to 1.6.0

Align the workspace and standalone fuzz manifests and lockfiles on http 1.6.0.

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

* fix(deps): refresh Cargo dependencies and preserve HTTP values

Refresh registry constraints and lockfiles. Preserve legacy opaque ETags and response headers with byte validation while retaining POST and signed override validation.

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:38 +08:00
Hauser Zhi 6b014ec215 feat(capacity): read usage directly on dedicated mounts (#9840)
* feat(capacity): read usage directly on dedicated mounts

Allow operators of dedicated filesystems to use block usage for background
capacity estimates. Reuse the existing blocking scan and cache update
paths so a successful probe establishes the per-disk baseline.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* refactor(capacity): verify whole mounts before reading usage

Share mount eligibility across a refresh and read allocated blocks
through the checked directory descriptor. Rebuild a complete per-disk
baseline when the local disk set changes.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* fix(capacity): discard stale topology on bounded refresh

Reconcile a scheduled full refresh against the topology it scanned.
Represent baseline completeness with the per-disk map and compute
aggregate totals in one pass.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

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

* fix(capacity): restrict direct reads to isolated filesystem types

Use the filesystem type from the existing descriptor-based statfs
call to keep shared-pool accounting out of the direct mount path.
Cover directory fallback and symlinked mount roots.

Refs: rustfs/rustfs#9837

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:30 +08:00
Hauser Zhi a368c669a2 feat(bench): record write latency in preflight queue samples (#9850)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:24 +08:00
hector e0b548fff0 fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready (#9848)
* fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready

- Use single-node single-disk layout (RUSTFS_VOLUMES=/data with a single rustfs_data volume) so docker compose up works out of the box without triggering same-device strict disk topology errors
- Switch healthcheck to /health/ready on port 9000 with --connect-timeout 3 --max-time 5 (decoupled from console toggle)
- Pin volume-permission-helper to alpine:3.24 with network_mode: none and skip redundant recursive chown -R when ownership is already 10001:10001
- Allow overriding S3/Console host ports and credentials via env vars, and configure ulimits.nofile=65535

Signed-off-by: xiaomage <jhma@rustfs.com>

* fix(docker): align RUSTFS_OBS_LOG_DIRECTORY to /logs in docker-compose-simple.yml

Signed-off-by: xiaomage <jhma@rustfs.com>

---------

Signed-off-by: xiaomage <jhma@rustfs.com>
2026-12-02 11:21:56 +08:00
42 changed files with 2145 additions and 812 deletions
+13
View File
@@ -382,6 +382,19 @@ jobs:
} > artifacts/workspace/doctest-diagnostics.txt
exit "${status}"
- name: Verify production ECStore crash and recovery
if: needs.classify-changes.outputs.mode == 'full'
env:
CARGO_BUILD_JOBS: "2"
run: |
dst=(--locked -p rustfs-ecstore --features dst --test dst_production_ecstore --profile ci)
mkdir -p artifacts/workspace/dst
cargo nextest list "${dst[@]}" --message-format json > artifacts/workspace/dst/selection.json
rm -f target/nextest/ci/junit.xml
trap 'if [[ -f target/nextest/ci/junit.xml ]]; then cp target/nextest/ci/junit.xml artifacts/workspace/dst/junit.xml; fi' EXIT
cargo nextest run "${dst[@]}" --no-tests fail --retries 0
python3 scripts/ci_test_artifact.py evidence --dst artifacts/workspace/dst/selection.json target/nextest/ci/junit.xml
- name: Upload test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
Generated
+415 -222
View File
File diff suppressed because it is too large Load Diff
+17 -15
View File
@@ -40,6 +40,7 @@ members = [
"crates/lock", # Distributed locking implementation
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
"crates/madmin", # Management dashboard and admin API interface
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
"crates/notify", # Notification system for events
"crates/obs", # Observability utilities
"crates/object-capacity", # Capacity scan and refresh core
@@ -192,13 +193,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.5.0"
http = "1.6.0"
http-body = "1.1.0"
http-body-util = "0.1.5"
memchr = "2.8.3"
minlz = "1.2.3"
reqwest = "0.13.5"
rustfs-kafka-async = { version = "1.4.1" }
rustfs-kafka-async = { version = "1.5.0" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -224,7 +225,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
byteorder = "1.5.1"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -269,7 +270,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.3" }
jiff = { version = "1.1.0" }
time = { version = "0.3.55" }
# Database
@@ -282,15 +283,15 @@ anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.17"
tar-framing = "0.0.17"
tar-codec = "0.0.18"
tar-framing = "0.0.18"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-sts = { default-features = false, version = "1.130.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
@@ -357,7 +358,7 @@ percent-encoding = "2.3.2"
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -378,7 +379,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
starshard = { version = "2.4.2" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -400,15 +401,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
metrics = "0.25.1"
metrics-util = "0.21"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -416,7 +417,7 @@ opentelemetry-otlp = { version = "0.33.1" }
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
opentelemetry_sdk = { version = "0.33.1" }
opentelemetry-semantic-conventions = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.2" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -431,7 +432,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.5" }
rustfs-mimalloc = { version = "0.7.6" }
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
hotpath = { version = "=0.33.1", default-features = false }
# Snapshot testing for output format regression detection
@@ -483,6 +484,7 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
metrics = { path = "crates/metrics-compat" }
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
+6
View File
@@ -45,6 +45,9 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
/// Environment variable for following symbolic links during capacity calculation
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
/// Use filesystem-reported used space on dedicated drive mounts.
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
/// Environment variable for enabling dynamic timeout calculation
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
@@ -94,6 +97,9 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
/// Default: false (disabled for safety)
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
/// Use directory scans by default to preserve logical file-size accounting.
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
/// Enable dynamic timeout calculation based on directory characteristics
/// Default: true (enabled)
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,14 +1329,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1391,14 +1389,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
@@ -1438,7 +1434,6 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1458,8 +1453,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1941,14 +1935,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1966,8 +1953,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
}
}
@@ -1984,14 +1970,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
}
}
@@ -2560,7 +2539,6 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2570,14 +2548,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
replicate_delete(*del_info, storage).await;
}
}
}
@@ -4535,102 +4506,6 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,40 +2422,12 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
return replicate_force_delete_to_targets(&dobj, storage).await;
}
let bucket = dobj.bucket.clone();
@@ -2500,7 +2472,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::Unfinished;
return false;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2508,7 +2480,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return DeleteReplicationAttempt::Completed;
return true;
}
if dobj.delete_object.delete_marker
@@ -2530,7 +2502,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return DeleteReplicationAttempt::Completed;
return true;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2548,7 +2520,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2557,7 +2529,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2582,7 +2554,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
}
}
@@ -2593,7 +2565,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2617,14 +2589,14 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
warn!(
debug!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2648,7 +2620,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return DeleteReplicationAttempt::SourceDeferred;
return false;
}
};
@@ -2886,12 +2858,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
}
};
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2899,7 +2866,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
))
)
}
/// Reads the source version addressed by `delete_marker_version_id` so a
+313 -53
View File
@@ -70,6 +70,12 @@ use crate::disk::{
endpoint::Endpoint,
error::{DiskError, Error, Result},
format::FormatV3,
multipart_source::{
MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartProofKind, MultipartPublicationResult, MultipartSourceOperation,
MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, MultipartSourceResponse, MultipartSourceSnapshot,
MultipartUndoCapability, ProofVerificationContext, PublicationIdentity, SourceConditionV1, capture_source_condition,
publication_identity, require_source_condition, strip_transport_condition,
},
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
};
use crate::erasure::coding::{self, bitrot_verify};
@@ -78,6 +84,8 @@ use crate::set_disk::SetDisks;
use crate::store::init_format::save_format_file;
const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx";
const DST_MULTIPART_STATE: &str = ".dst-mpu-consumed";
const DST_MULTIPART_ANCHOR: &str = ".dst-mpu-retirement-anchor";
const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024;
fn sim_to_io_err(err: SimErr) -> IoError {
@@ -210,6 +218,22 @@ struct SimDeleteTxRecord {
backup_xl: Option<Vec<u8>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartAnchor {
disk_id: Uuid,
physical_slot: usize,
publication: PublicationIdentity,
original_sha256: [u8; 32],
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartState {
anchor: SimMultipartAnchor,
capability_sha256: Option<[u8; 32]>,
}
/// Deterministic simulated disk implementing production [`DiskAPI`] directly
/// on top of [`SimDiskIo`].
#[derive(Clone)]
@@ -226,6 +250,7 @@ pub struct DstSimDisk {
scanning: Arc<AtomicU32>,
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
cas_lock: Arc<tokio::sync::Mutex<()>>,
multipart_publication_lock: Arc<tokio::sync::Mutex<()>>,
configured_capacity: Arc<RwLock<Option<u64>>>,
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
}
@@ -281,6 +306,7 @@ impl DstSimDisk {
scanning: Arc::new(AtomicU32::new(0)),
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
multipart_publication_lock: Arc::new(tokio::sync::Mutex::new(())),
configured_capacity: Arc::new(RwLock::new(None)),
multipart_proof_authority: Arc::new(RwLock::new(None)),
}
@@ -299,6 +325,12 @@ impl DstSimDisk {
&self.sim
}
/// Returns the simulator-only retirement witness path for fault injection.
pub fn multipart_retirement_anchor_path(volume: &str, object: &str, data_dir: Uuid) -> Result<String> {
let target_dir = join_vol_path(volume, object)?;
Ok(format!("{target_dir}/{data_dir}/{DST_MULTIPART_ANCHOR}"))
}
pub fn crash_registry(&self) -> &CrashRegistry {
&self.crash_registry
}
@@ -431,6 +463,241 @@ impl DstSimDisk {
Ok(())
}
fn multipart_authority(&self) -> Result<ProofVerificationContext> {
self.multipart_proof_authority
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
.ok_or(DiskError::UnsupportedDisk)
}
async fn sync_multipart_source_absence(&self, mut path: &str) -> Result<()> {
while let Some((parent, _)) = path.rsplit_once('/') {
match self.sim.stat(parent).await {
Ok(contents) if contents.is_dir => return self.fsync_parent_chain(parent).await,
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
Err(SimErr::NotFound(_)) => path = parent,
Err(error) => return Err(map_sim_err(error)),
}
}
self.fsync_parent_chain("").await
}
async fn prepare_multipart_anchor(
&self,
source_dir: &str,
src_path: &str,
target: (&str, &str),
fi: &FileInfo,
publication: PublicationIdentity,
) -> Result<SimMultipartAnchor> {
self.multipart_authority()?;
let condition = require_source_condition(fi)?;
if publication.lineage.path != src_path
|| (publication.lineage.bucket.as_str(), publication.lineage.object.as_str()) != target
|| condition.attach(&mut fi.clone())? != publication
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
match self.sim.stat(&format!("{source_dir}/{DST_MULTIPART_STATE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let original = self
.sim
.read_file(&format!("{source_dir}/{STORAGE_FORMAT_FILE}"))
.await
.map_err(map_sim_err)?;
let original_fi = get_file_info(
&original,
RUSTFS_META_MULTIPART_BUCKET,
src_path,
&publication.lineage.original_version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
if capture_source_condition(target.0, target.1, src_path, &original_fi, publication.attempt)? != condition
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&original_fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(SimMultipartAnchor {
disk_id: self.get_disk_id().await?.ok_or(DiskError::InconsistentDisk)?,
physical_slot: self.disk_idx,
publication,
original_sha256: Sha256::digest(original).into(),
})
}
fn multipart_snapshot(
anchor: &SimMultipartAnchor,
revision: u64,
phase: MultipartSourcePhase,
record: &[u8],
target: &[u8],
capability_sha256: Option<[u8; 32]>,
) -> MultipartSourceSnapshot {
let state_sha256: [u8; 32] = Sha256::digest(record).into();
let mut inventory = Sha256::new();
inventory.update(state_sha256);
inventory.update(Sha256::digest(target));
MultipartSourceSnapshot {
disk_id: anchor.disk_id,
physical_slot: anchor.physical_slot,
lineage: anchor.publication.lineage.clone(),
generation: anchor.publication.source_generation,
revision,
phase,
state_sha256,
head_sha256: None,
inventory_sha256: inventory.finalize().into(),
capability_sha256,
publication: Some(anchor.publication.clone()),
}
}
async fn publish_multipart_witness(
&self,
source_dir: &str,
target_dir: &str,
anchor: SimMultipartAnchor,
target: &[u8],
) -> Result<MultipartPublicationResult> {
let authority = self.multipart_authority()?;
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", anchor.publication.final_data_dir);
let anchor_bytes = rmp_serde::to_vec_named(&anchor).map_err(Error::other)?;
self.write_durable_file(&anchor_path, Bytes::from(anchor_bytes)).await?;
let undo_capability = MultipartUndoCapability::new();
let state = SimMultipartState {
anchor,
capability_sha256: Some(undo_capability.digest()),
};
let record = rmp_serde::to_vec_named(&state).map_err(Error::other)?;
// The fsync of the source directory also persists removal of its old
// xl.meta name, which was renamed to the destination during commit.
self.write_durable_file(&format!("{source_dir}/{DST_MULTIPART_STATE}"), Bytes::copy_from_slice(&record))
.await?;
let snapshot = Self::multipart_snapshot(
&state.anchor,
1,
MultipartSourcePhase::ConsumedUnsealed,
&record,
target,
state.capability_sha256,
);
let publication = state.anchor.publication;
let proof = MultipartSourceProof::issue(&authority, MultipartProofKind::Published, publication.attempt, None, snapshot)?;
Ok(MultipartPublicationResult {
publication,
proof,
undo_capability,
})
}
async fn confirm_multipart_witness(
&self,
path: &str,
publication: &PublicationIdentity,
challenge: Uuid,
) -> Result<MultipartSourceProof> {
self.ensure_online()?;
publication.lineage.validate()?;
if publication.lineage.path != path || challenge.is_nil() {
return Err(DiskError::ConditionalDeleteConflict);
}
let _guard = self.multipart_publication_lock.lock().await;
let authority = self.multipart_authority()?;
let lineage = &publication.lineage;
let source_dir = join_vol_path(RUSTFS_META_MULTIPART_BUCKET, path)?;
let target_dir = join_vol_path(&lineage.bucket, &lineage.object)?;
let target_meta = format!("{target_dir}/{STORAGE_FORMAT_FILE}");
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", publication.final_data_dir);
let anchor_raw = self.sim.read_file(&anchor_path).await.map_err(map_sim_err)?;
let anchor: SimMultipartAnchor = rmp_serde::from_slice(&anchor_raw).map_err(Error::other)?;
if Some(anchor.disk_id) != self.get_disk_id().await?
|| anchor.physical_slot != self.disk_idx
|| anchor.publication != *publication
{
return Err(DiskError::ConditionalDeleteConflict);
}
let target = self.sim.read_file(&target_meta).await.map_err(map_sim_err)?;
let fi = get_file_info(
&target,
&lineage.bucket,
&lineage.object,
&publication.version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
let condition = SourceConditionV1 {
lineage: lineage.clone(),
generation: publication.source_generation,
attempt: publication.attempt,
};
let geometry = &lineage.geometry;
if publication_identity(&fi)?.as_ref() != Some(publication)
|| condition.attach(&mut fi.clone())? != *publication
|| geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|| fi.erasure.distribution != geometry.distribution
|| fi.erasure.data_blocks != geometry.data_blocks
|| fi.erasure.parity_blocks != geometry.parity_blocks
|| fi.erasure.block_size != geometry.block_size
{
return Err(DiskError::ConditionalDeleteConflict);
}
if !fi.inline_data() && fi.size > 0 {
let verified = self.verify_file(&lineage.bucket, &lineage.object, &fi).await?;
if verified.results.iter().any(|result| *result != CHECK_PART_SUCCESS) {
return Err(DiskError::FileCorrupt);
}
}
self.sim.fsync_file(&target_meta).await.map_err(map_sim_err)?;
self.fsync_parent_chain(&target_dir).await?;
let (kind, snapshot) = match self.sim.stat(&source_dir).await {
Err(SimErr::NotFound(_)) => {
self.sync_multipart_source_absence(&source_dir).await?;
(
MultipartProofKind::RootMissingTerminal,
Self::multipart_snapshot(&anchor, 0, MultipartSourcePhase::RootMissing, &anchor_raw, &target, None),
)
}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => {
match self.sim.stat(&format!("{source_dir}/{STORAGE_FORMAT_FILE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let state_path = format!("{source_dir}/{DST_MULTIPART_STATE}");
let mut raw = self.sim.read_file(&state_path).await.map_err(map_sim_err)?;
let mut state: SimMultipartState = rmp_serde::from_slice(&raw).map_err(Error::other)?;
if state.anchor != anchor {
return Err(DiskError::ConditionalDeleteConflict);
}
if state.capability_sha256.take().is_some() {
raw = Bytes::from(rmp_serde::to_vec_named(&state).map_err(Error::other)?);
self.write_durable_file(&state_path, raw.clone()).await?;
}
(
MultipartProofKind::TerminalTarget,
Self::multipart_snapshot(&anchor, 2, MultipartSourcePhase::LocalTerminalSeal, &raw, &target, None),
)
}
};
MultipartSourceProof::issue(&authority, kind, challenge, None, snapshot)
}
fn load_filemeta_preserving_inline(raw: &[u8]) -> Result<FileMeta> {
let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?;
if !inline_buf.is_empty() {
@@ -1428,7 +1695,7 @@ impl DiskAPI for DstSimDisk {
&self,
src_volume: &str,
src_path: &str,
file_info: FileInfo,
mut file_info: FileInfo,
dst_volume: &str,
dst_path: &str,
) -> Result<RenameDataResp> {
@@ -1442,6 +1709,23 @@ impl DiskAPI for DstSimDisk {
let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}");
let multipart = src_volume == RUSTFS_META_MULTIPART_BUCKET;
let _multipart_guard = if multipart {
Some(self.multipart_publication_lock.lock().await)
} else {
None
};
let publication = if multipart { publication_identity(&file_info)? } else { None };
let multipart_anchor = if let Some(publication) = publication {
let anchor = self
.prepare_multipart_anchor(&src_dir, src_path, (dst_volume, dst_path), &file_info, publication)
.await?;
strip_transport_condition(&mut file_info.metadata);
Some(anchor)
} else {
None
};
let existing_raw = match self.sim.read_file(&dst_meta).await {
Ok(b) => Some(b),
Err(SimErr::NotFound(_)) => None,
@@ -1484,20 +1768,15 @@ impl DiskAPI for DstSimDisk {
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
crate::disk::multipart_source::publication_identity(&file_info)?
} else {
None
};
let has_external_parts =
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
if has_external_parts
&& let Some(data_dir) = file_info.data_dir
&& !data_dir.is_nil()
{
let src_data_dir = multipart_pub_identity
let src_data_dir = multipart_anchor
.as_ref()
.map(|p| p.lineage.original_data_dir)
.map(|anchor| anchor.publication.lineage.original_data_dir)
.unwrap_or(data_dir);
let src_data = format!("{src_dir}/{src_data_dir}");
let dst_data = format!("{dst_dir}/{data_dir}");
@@ -1533,7 +1812,10 @@ impl DiskAPI for DstSimDisk {
self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?;
self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?;
self.sim
.write_file(&src_meta, new_meta_bytes.clone())
.await
.map_err(map_sim_err)?;
self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?;
self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?;
@@ -1545,50 +1827,12 @@ impl DiskAPI for DstSimDisk {
let _ = self.sim.remove_dir_all(&src_dir).await;
}
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
let authority = self
.multipart_proof_authority
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
if let (Some(publication), Some(authority)) = (publication, authority) {
let disk_id = self
.disk_id
.read()
.unwrap_or_else(|p| p.into_inner())
.ok_or(DiskError::InconsistentDisk)?;
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
disk_id,
physical_slot: self.disk_idx,
lineage: publication.lineage.clone(),
generation: publication.source_generation,
revision: 1,
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
state_sha256: [0; 32],
head_sha256: None,
inventory_sha256: [0; 32],
capability_sha256: Some(undo_capability.digest()),
publication: Some(publication.clone()),
};
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
&authority,
crate::disk::multipart_source::MultipartProofKind::Published,
Uuid::new_v4(),
None,
snapshot,
)?;
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
publication,
proof,
undo_capability,
}))
} else {
None
}
} else {
None
let multipart_source = match multipart_anchor {
Some(anchor) => Some(Box::new(
self.publish_multipart_witness(&src_dir, &dst_dir, anchor, &new_meta_bytes)
.await?,
)),
None => None,
};
Ok(RenameDataResp {
@@ -1601,6 +1845,22 @@ impl DiskAPI for DstSimDisk {
})
}
async fn recover_multipart_source(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
if request.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION {
return Err(DiskError::UnsupportedDisk);
}
match request.operation {
MultipartSourceOperation::ConfirmTerminal {
expected: None,
publication,
challenge,
} => Ok(MultipartSourceResponse::TerminalConfirmed(
self.confirm_multipart_witness(&request.path, &publication, challenge).await?,
)),
_ => Err(DiskError::UnsupportedDisk),
}
}
async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result<Vec<String>> {
self.ensure_online()?;
self.ensure_volume_exists(volume).await?;
+1 -1
View File
@@ -1731,7 +1731,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
let handle = directory.handle.as_raw_handle();
+4 -2
View File
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
// its header, the complete UTF-16 name, and trailing zeroed storage.
// `dst_parent` and `source` remain live until the synchronous call returns.
unsafe {
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -7753,7 +7753,9 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
let mut disposition = FILE_DISPOSITION_INFORMATION {
DeleteFile: u8::from(delete_file),
};
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
let mut io_status = IO_STATUS_BLOCK::default();
@@ -3922,6 +3922,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: Some(OffsetDateTime::now_utc()),
size: w_size,
actual_size,
checksums: part_info.checksums,
};
// error!("put_object_part ret {:?}", &ret);
@@ -4020,6 +4021,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket: owner.bucket,
object: owner.object,
});
// The upload records its checksum algorithm and type at CreateMultipartUpload.
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
// so a client that resumes an upload can state the same checksum contract.
let checksum_algorithm = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
.cloned()
.unwrap_or_default();
let checksum_type = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
.cloned()
.unwrap_or_default();
let mut ret = ListPartsInfo {
recorded_owner,
bucket: bucket.to_owned(),
@@ -4028,6 +4042,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
storage_class,
max_parts,
part_number_marker,
checksum_algorithm,
checksum_type,
user_defined: {
let mut metadata = fi.metadata.clone();
strip_internal_multipart_metadata(&mut metadata);
@@ -4120,6 +4136,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: part.mod_time,
size: part.size,
actual_size: part.actual_size,
checksums: part.checksums.clone(),
});
count -= 1;
@@ -7607,6 +7624,35 @@ mod tests {
}
}
#[tokio::test]
async fn list_object_parts_echoes_upload_and_part_checksums() {
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-checksum-listing";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
let (upload_id, _, checksums) =
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
.await;
let page = set_disks
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
.await
.expect("checksummed parts should be listable");
assert_eq!(page.checksum_algorithm, "SHA256");
assert_eq!(page.checksum_type, "COMPOSITE");
assert_eq!(page.parts.len(), payloads.len());
for (part, checksum) in page.parts.iter().zip(&checksums) {
assert_eq!(
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
Some(&checksum.encoded),
"part {} must echo its recorded checksum",
part.part_num
);
}
}
#[tokio::test]
async fn list_parts_baseline_legacy_owner_metadata() {
let (_roots, disks, set) = hermetic_set_disks(4).await;
+154 -16
View File
@@ -379,9 +379,9 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
CrashPoint::RenameAfterDataRename,
CrashPoint::RenameAfterBackupBeforeMetaCommit,
CrashPoint::RenameAfterMetaCommit,
CrashPoint::MetaWriteAfterTmpBeforeRename,
];
let mut acknowledged_overwrites = 0;
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
.iter()
.enumerate()
@@ -457,8 +457,13 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
// Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed)
let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await;
fixture.crash_registry.clear();
let overwrite = put_bytes(&fixture, bucket, &key, &v2).await;
for slot in 0..affected_drives {
assert!(
!fixture.crash_registry.take_if_armed_on_drive(point, &key, "dst-node0", slot),
"seed={seed:#x} key={key}: {point:?} did not fire on drive {slot}"
);
}
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
fixture.crash_and_reboot_all();
@@ -475,18 +480,19 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
}
// INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1`
// OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes!
let observed = get_bytes(&fixture, bucket, &key)
.await
.unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}"));
assert!(
observed == v1 || observed == v2,
"atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})",
observed.len(),
v1.len(),
v2.len()
);
let observed = get_bytes(&fixture, bucket, &key).await.unwrap_or_else(|e| {
panic!("committed object {key} unreadable after ALICE crash at {point:?} (seed={seed:#x}): {e:?}")
});
if overwrite.is_ok() {
acknowledged_overwrites += 1;
assert!(observed == v2, "seed={seed:#x} key={key}: acknowledged overwrite lost after {point:?}");
} else {
// A fault can interrupt the reply after local publication completed.
assert!(
observed == v1 || observed == v2,
"seed={seed:#x} key={key}: torn overwrite after {point:?}: {overwrite:?}"
);
}
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
// and previously untouched anchor objects remain 100% bit-exact!
@@ -513,6 +519,38 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
}
}
assert!(acknowledged_overwrites > 0, "no degraded overwrite received an ACK");
}
#[tokio::test]
async fn metadata_write_crash_preserves_published_metadata() {
let fixture = make_dst_sim_set_disks(0xC2A5_4005, 4, 2, None).await.unwrap();
let bucket = "dst-meta-crash";
let key = "metadata.bin";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
put_bytes(&fixture, bucket, key, b"committed").await.unwrap();
let disk = &fixture.disks[0];
let sim = &fixture.sim_disks[0];
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
let path = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
let original = sim.sim().read_file(&path).await.unwrap();
let mut next = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
next.metadata.insert("x-amz-meta-probe".into(), "updated".into());
let point = CrashPoint::MetaWriteAfterTmpBeforeRename;
fixture.crash_registry.arm_on_drive(point, key, "dst-node0", 0);
assert!(disk.write_metadata("", bucket, key, next.clone()).await.is_err());
assert!(!fixture.crash_registry.take_if_armed_on_drive(point, key, "dst-node0", 0));
fixture.crash_and_reboot_all();
assert_eq!(sim.sim().read_file(&path).await.unwrap(), original);
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), b"committed");
disk.write_metadata("", bucket, key, next).await.unwrap();
fixture.crash_and_reboot_all();
let updated = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
assert_eq!(updated.metadata.get("x-amz-meta-probe").map(String::as_str), Some("updated"));
}
// ============================================================================
@@ -902,6 +940,10 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
// ------------------------------------------------------------------------
let mut before_cleanup_hits = 0usize;
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
let opts = ObjectOptions {
versioned: seed % 2 == 0,
..dst_object_options()
};
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
@@ -959,7 +1001,7 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
let crashed = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts.clone(), &opts)
.await;
assert!(
crashed.is_err(),
@@ -985,6 +1027,21 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
);
// A client that lost the completion response must recover the identity of
// the existing commit, including the version ID on a versioned bucket.
let published = fixture.set_disks.get_object_info(bucket, &key, &opts).await.unwrap();
assert_eq!(published.version_id.is_some(), opts.versioned);
let retried = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.await
.expect("complete retry after post-commit power loss");
assert!(retried.multipart_completion_replayed, "seed={seed:#x}: upload committed again");
assert_eq!(retried.version_id, published.version_id);
assert_eq!(retried.etag, published.etag);
assert_eq!(get_bytes(&fixture, bucket, &key).await.unwrap(), expected);
// Post-crash heal converges cleanly and every drive verifies both parts!
let (_heal_item, heal_err) = fixture
.set_disks
@@ -1016,6 +1073,13 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
"drive {slot} must pass HighwayHash256S verification for both parts"
);
let raw = disk.read_all(bucket, &format!("{key}/{STORAGE_FORMAT_FILE}")).await.unwrap();
let versions = FileMeta::load(&raw)
.unwrap()
.get_all_file_info_versions(bucket, &key, true)
.unwrap();
assert_eq!(versions.versions.len(), 1, "drive {slot}: duplicate multipart commit");
assert_eq!(versions.versions[0].version_id, published.version_id);
}
}
assert_eq!(
@@ -1023,3 +1087,77 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
);
}
#[tokio::test]
async fn multipart_replay_rejects_missing_or_other_disk_anchor() {
let fixture = make_dst_sim_set_disks(0x671, 4, 2, None).await.unwrap();
let bucket = "dst-mpu-anchor";
let key = "published";
let opts = dst_object_options();
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
let upload = fixture.set_disks.new_multipart_upload(bucket, key, &opts).await.unwrap();
let expected = deterministic_payload(0x671, key, 128 * 1024);
let mut payload = PutObjReader::from_vec(expected.clone());
let part = fixture
.set_disks
.put_object_part(bucket, key, &upload.upload_id, 1, &mut payload, &opts)
.await
.unwrap();
let parts = vec![CompletePart {
part_num: 1,
etag: part.etag,
..Default::default()
}];
let complete = || {
fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
};
let published = complete().await.unwrap();
fixture.crash_and_reboot_all();
let replayed = complete().await.expect("all four witnesses are available");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
let info = fixture.disks[0]
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.unwrap();
let anchor =
rustfs_ecstore::api::dst::DstSimDisk::multipart_retirement_anchor_path(bucket, key, info.data_dir.unwrap()).unwrap();
let (parent, _) = anchor.rsplit_once('/').unwrap();
let disks = &fixture.sim_disks;
let own_0 = disks[0].sim().read_file(&anchor).await.unwrap();
let own_1 = disks[1].sim().read_file(&anchor).await.unwrap();
let foreign = disks[2].sim().read_file(&anchor).await.unwrap();
for disk in &disks[..2] {
disk.sim().remove_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), expected);
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
disks[0].sim().write_file(&anchor, foreign).await.unwrap();
disks[0].sim().fsync_file(&anchor).await.unwrap();
disks[0].sim().fsync_dir(parent).await.unwrap();
fixture.crash_and_reboot_all();
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
for (disk, own) in disks[..2].iter().zip([own_0, own_1]) {
disk.sim().write_file(&anchor, own).await.unwrap();
disk.sim().fsync_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
let replayed = complete()
.await
.expect("each restored witness belongs to its own physical disk");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
}
+68 -1
View File
@@ -1428,6 +1428,9 @@ impl VaultTransitKmsClient {
}
})
.await?;
// Transit LIST also returns directory entries, including the BYOK
// wrapping-key directory. Only actual key names belong in the cursor.
all_keys.retain(|key| !key.ends_with('/'));
// Vault's own LIST ordering is not part of its contract, so the sort is
// what makes the marker a stable cursor across calls.
all_keys.sort_unstable();
@@ -2068,6 +2071,70 @@ mod tests {
serde_json::to_value(&response).expect("serialize transit key read response")
}
#[tokio::test]
async fn list_skips_byok_directories_before_pagination() {
let listed = serde_json::json!({ "keys": ["zulu", "import/", "import", "alpha", "versions/"] });
let metadata = metadata_read_data(&TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()));
let (vault, client) = scripted_client(vec![
ScriptedResponse::ok(listed.clone()),
ScriptedResponse::ok(transit_key_read_data("alpha")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(transit_key_read_data("import")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(listed),
ScriptedResponse::ok(transit_key_read_data("zulu")),
ScriptedResponse::ok(metadata),
])
.await;
let first = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
..Default::default()
},
None,
)
.await
.expect("list the first page despite directory entries");
assert_eq!(first.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["alpha", "import"]);
assert_eq!(first.next_marker.as_deref(), Some("import"));
assert!(first.truncated);
assert!(first.unreadable_key_ids.is_empty());
let last = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
marker: first.next_marker,
..Default::default()
},
None,
)
.await
.expect("a sweep can continue past the wrapping-key directory");
assert_eq!(last.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["zulu"]);
assert!(last.next_marker.is_none());
assert!(!last.truncated);
assert!(last.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 8, "only actual keys should be described");
}
#[tokio::test]
async fn list_with_only_the_byok_directory_is_empty() {
let (vault, client) = scripted_client(vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/"] }))]).await;
let listed = client
.list_keys(&ListKeysRequest::default(), None)
.await
.expect("the wrapping-key directory is not a KMS key");
assert!(listed.keys.is_empty());
assert!(listed.next_marker.is_none());
assert!(!listed.truncated);
assert!(listed.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 1, "a directory must not be described");
}
/// A listing must not silently shrink when the backend is the problem.
///
/// Before the per-key classification this path used `?`, so any describe
@@ -2076,7 +2143,7 @@ mod tests {
/// about it. A transit mount that stops answering must still fail loudly.
#[tokio::test]
async fn list_fails_when_a_transit_key_read_is_unavailable() {
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["key-a"] }))];
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/", "key-a"] }))];
for _ in 0..3 {
responses.push(ScriptedResponse::error(503, "temporarily unavailable"));
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "metrics"
version = "0.24.6"
publish = false
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "RustFS compatibility facade for dependencies requiring metrics 0.24"
[dependencies]
# Use a distinct extern name when rustdoc also links the facade as metrics.
metrics_025 = { package = "metrics", version = "0.25.1" }
[dev-dependencies]
metrics-util = { workspace = true, features = ["debugging"] }
toml = "1.2.3"
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Share the metrics recorder with dependencies requiring metrics 0.24.
// RUSTFS_COMPAT_TODO(metrics-024-recorder): Share the recorder with 0.24 consumers. Remove after all consumers accept metrics 0.25 directly.
pub use metrics_025::*;
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
#[test]
fn legacy_macros_reach_the_metrics_025_recorder() {
let recorder = DebuggingRecorder::new();
metrics_025::with_local_recorder(&recorder, || {
crate::counter!("messages", "topic" => "events").increment(2);
metrics_025::counter!("messages", "topic" => "events").increment(3);
crate::gauge!("connections").set(4.0);
crate::histogram!("latency").record(5.0);
});
let entries = recorder.snapshotter().snapshot().into_vec();
let expected = [
(
metrics_025::Key::from_parts("messages", vec![metrics_025::Label::new("topic", "events")]),
DebugValue::Counter(5),
),
(metrics_025::Key::from_name("connections"), DebugValue::Gauge(4.0.into())),
(metrics_025::Key::from_name("latency"), DebugValue::Histogram(vec![5.0.into()])),
];
assert_eq!(entries.len(), expected.len());
for (key, value) in expected {
assert!(
entries
.iter()
.any(|(entry, _, _, recorded)| entry.key() == &key && recorded == &value)
);
}
}
#[test]
fn workspace_and_fuzz_use_only_one_recorder_implementation() {
for (lockfile, needs_facade) in [
(include_str!("../../../Cargo.lock"), true),
(include_str!("../../../fuzz/Cargo.lock"), false),
] {
let lock: toml::Value = toml::from_str(lockfile).expect("Cargo lockfile should parse");
let packages = lock["package"].as_array().expect("Cargo lockfile should list packages");
let metrics: Vec<_> = packages
.iter()
.filter(|package| package["name"].as_str() == Some("metrics"))
.collect();
assert_eq!(metrics.len(), 1 + usize::from(needs_facade), "metrics must have one implementation");
assert_eq!(
metrics
.iter()
.any(|package| { package["version"].as_str() == Some("0.24.6") && package.get("source").is_none() }),
needs_facade,
);
assert!(metrics.iter().any(|package| {
package["version"]
.as_str()
.is_some_and(|version| version.starts_with("0.25."))
&& package["source"]
.as_str()
.is_some_and(|source| source.starts_with("registry+"))
}));
}
}
}
+9 -16
View File
@@ -169,34 +169,24 @@ Refreshing only dirty disks is safe only when:
- `disk_cache_complete == true`
- which means the system has already completed at least one full refresh without partial errors
- and the per-disk cache is fully populated
- and the per-disk cache covers the current local disk set
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
### Merge Rules After a Subset Refresh
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
## Relationship to the RustFS Main Flow
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
The high-level flow is:
1. Startup calls `init_capacity_management_for_local_disks()`.
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
4. If the cache is fresh enough, the cached value is returned directly.
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
## Public API
@@ -288,6 +278,7 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
@@ -296,6 +287,8 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
take precedence over the drive-timeout profile.
+9 -16
View File
@@ -169,34 +169,24 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且成功拿到了每盘缓存
- 并且每盘缓存覆盖当前本地盘集合
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
## 与 RustFS 主流程的关系
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
上层使用方式大致如下:
1. 启动时调用 `init_capacity_management_for_local_disks()`。
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
4. 缓存足够新时直接返回。
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
6. 缓存极旧且写入频率高时,前台阻塞刷新。
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
## 公开 API
@@ -288,6 +278,7 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
@@ -296,6 +287,8 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
### 配置缓存注意事项
在非测试构建中,配置通过 `OnceLock` 缓存:
+161 -52
View File
@@ -29,6 +29,8 @@ use rustfs_config::{
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
ENV_DRIVE_TIMEOUT_PROFILE,
};
#[cfg(target_os = "linux")]
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
use rustfs_io_metrics::capacity_metrics::{
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
@@ -86,6 +88,8 @@ struct CachedCapacityConfig {
metrics_interval: Duration,
/// Follow symlinks flag
follow_symlinks: bool,
#[cfg(target_os = "linux")]
use_mount_usage: bool,
/// Enable dynamic timeout flag
enable_dynamic_timeout: bool,
/// Min timeout
@@ -153,6 +157,8 @@ impl CachedCapacityConfig {
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
)),
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
#[cfg(target_os = "linux")]
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
max_timeout: Duration::from_secs(env_u64_at_least(
@@ -285,6 +291,11 @@ pub fn get_follow_symlinks() -> bool {
get_cached_config().follow_symlinks
}
#[cfg(target_os = "linux")]
pub(crate) fn get_use_mount_usage() -> bool {
get_cached_config().use_mount_usage
}
/// Get enable dynamic timeout flag from environment or default
#[cfg(not(test))]
pub fn get_enable_dynamic_timeout() -> bool {
@@ -353,8 +364,7 @@ pub struct CapacityUpdate {
/// Whether the value is estimated instead of exact.
pub is_estimated: bool,
/// Whether the refresh behind this update had partial disk failures.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
/// Independent of `is_estimated`, which describes how bytes were measured.
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -754,7 +764,6 @@ pub struct HybridCapacityManager {
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
/// Whether the per-disk cache currently covers all known disks.
disk_cache_complete: Arc<RwLock<bool>>,
/// Configuration
config: HybridStrategyConfig,
/// Shared singleflight refresh state
@@ -787,7 +796,6 @@ impl HybridCapacityManager {
write_record: Arc::new(WriteRecord::new()),
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
disk_cache: Arc::new(RwLock::new(HashMap::new())),
disk_cache_complete: Arc::new(RwLock::new(false)),
config,
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
}
@@ -811,57 +819,62 @@ impl HybridCapacityManager {
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
/// so they never report the subset bytes as the whole-cluster total.
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
self.commit_capacity(update, source, None).await
}
async fn commit_capacity(
&self,
mut update: CapacityUpdate,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let mut disk_cache_complete = self.disk_cache_complete.write().await;
let recompute = if !update.per_disk.is_empty()
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
} else if !disk_cache.is_empty()
&& let Some(disks) = full_scan_disks
{
// A bounded full scan may publish bytes without establishing a
// baseline. Do not merge a previous topology into that result.
let local: HashSet<_> = disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
if disk_cache.len() != local.len()
|| !disk_cache
.keys()
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
{
disk_cache.clear();
}
*disk_cache_complete = true;
true
} else if *disk_cache_complete {
// Merging over a complete cache also covers a degraded
// (partial-failure) full refresh: successfully scanned disks
// are refreshed while failed disks keep their last-known
// values, so the published total does not dip to the
// surviving-subset sum and bounce back on the next refresh.
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
true
} else {
false
};
}
if recompute {
// Reconcile cluster-wide aggregates from the full per-disk cache so a
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
// A nonempty disk cache always covers one complete topology. A
// degraded refresh on that topology keeps last-known disk entries.
if replaces_cache || !disk_cache.is_empty() {
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
});
update.total_used = bytes;
update.file_count = files;
update.is_estimated = estimated;
}
}
@@ -1051,15 +1064,33 @@ impl HybridCapacityManager {
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
pub async fn can_refresh_dirty_subset(&self) -> bool {
*self.disk_cache_complete.read().await
!self.disk_cache.read().await.is_empty()
}
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
let cache = self.disk_cache.read().await;
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
}
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
///
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
/// they cannot miss the completion notification even if the leader finishes very quickly.
#[hotpath::measure]
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
{
self.refresh_or_join_for_disks(source, None, refresh_fn).await
}
#[hotpath::measure]
async fn refresh_or_join_for_disks<F, Fut>(
&self,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
refresh_fn: F,
) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
@@ -1141,7 +1172,7 @@ impl HybridCapacityManager {
// returned to this caller and the one published to joiners carry the cluster totals
// rather than a dirty-subset's partial bytes.
let result = match result {
Ok(update) => Ok(self.update_capacity(update, source).await),
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1427,8 +1458,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2476,6 +2507,84 @@ mod tests {
assert!(!cached.degraded);
}
#[tokio::test]
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
let temp = tempfile::TempDir::new().expect("create capacity fixture");
let active = temp.path().join("active");
let replacement = temp.path().join("replacement");
std::fs::create_dir(&active).expect("create active disk");
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
let active = active.to_str().expect("UTF-8 active path");
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
let mut old = full_two_disk_update();
old.per_disk[0] = disk_entry("active", active, 100, 1);
manager.update_capacity(old, DataSource::Scheduled).await;
let current = vec![
CapacityDiskRef {
endpoint: "active".into(),
drive_path: active.into(),
},
CapacityDiskRef {
endpoint: "replacement".into(),
drive_path: replacement_path.into(),
},
];
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
let published = manager.get_capacity().await.expect("publish degraded refresh");
assert!(published.degraded);
assert_eq!(published.total_used, 3);
assert!(!manager.can_refresh_dirty_subset().await);
assert_eq!(
select_scheduled_capacity_refresh(&manager, &current).await,
ScheduledCapacityRefresh::Idle
);
std::fs::create_dir(&replacement).expect("make replacement readable");
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![scope_disk("replacement", replacement_path)],
})
.await;
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
let published = manager.get_capacity().await.expect("publish recovered refresh");
assert_eq!(published.total_used, 8);
assert!(!published.degraded);
assert!(manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
let current = [
CapacityDiskRef {
endpoint: "node-a".into(),
drive_path: "/tmp/disk-a".into(),
},
CapacityDiskRef {
endpoint: "node-c".into(),
drive_path: "/tmp/disk-c".into(),
},
];
let mut timed_out = CapacityUpdate::estimated(160, 2);
timed_out.timed_out = true;
timed_out.per_disk = vec![
disk_entry("node-a", "/tmp/disk-a", 60, 1),
disk_entry("node-c", "/tmp/disk-c", 100, 1),
];
let published = manager
.refresh_or_join_for_disks(DataSource::Scheduled, Some(&current), || async { Ok(timed_out) })
.await
.expect("publish bounded full refresh");
assert_eq!(published.total_used, 160);
assert!(published.timed_out);
assert!(published.is_estimated);
assert!(!manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
+168 -52
View File
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(target_os = "linux")]
use super::capacity_manager::get_use_mount_usage;
use super::capacity_manager::{
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
@@ -23,6 +25,8 @@ use rustfs_io_metrics::capacity_metrics::{
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
record_capacity_timeout_fallback,
};
#[cfg(target_os = "linux")]
use rustfs_utils::os::MountUsageSnapshot;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Component, Path};
@@ -198,10 +202,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
&& components.all(|component| matches!(component, Component::Normal(_)))
}
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -232,7 +236,14 @@ async fn calculate_data_dir_used_capacity_report(
let mut per_disk = Vec::with_capacity(disks.len());
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
let limits = ScanLimits::from_env();
let mut scans = stream::iter(
disks
.iter()
.cloned()
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
)
.buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -351,38 +362,43 @@ pub(crate) async fn select_scheduled_capacity_refresh(
// entries so the dirty gauge reflects local pending work (backlog#1020).
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
capacity_manager.retain_dirty_disks_within(&local_set).await;
if disks.is_empty() {
return ScheduledCapacityRefresh::Idle;
}
let full_scan = || ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
if cached_topology_matches == Some(false) {
return full_scan();
}
let dirty_disks = capacity_manager.get_dirty_disks().await;
if dirty_disks.is_empty() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
return if capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
};
}
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
if cached_topology_matches.is_none() {
return full_scan();
}
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -404,9 +420,13 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
let scan_started_at = Instant::now();
let report = calculate_data_dir_used_capacity_report(&disks)
let report = calculate_data_dir_used_capacity_report(disks)
.await
.map_err(|e| e.to_string())?;
@@ -421,8 +441,8 @@ pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subs
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// This is primarily intended for benchmarks and operational tooling that need to exercise
/// the same scan path as admin capacity queries without going through the full admin stack.
/// This is intended for benchmarks and operational tooling that need the same scan path
/// as background capacity refreshes. Direct filesystem readings do not count files.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -551,6 +571,8 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -572,6 +594,7 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -579,15 +602,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks: get_follow_symlinks(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
}
}
}
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
/// mount point. On a shared filesystem (several logical disks per filesystem,
/// common in dev deployments) statvfs counts unrelated data and would badly
/// overcount, so `None` is returned and callers keep scan-based estimates.
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
let parent = path.parent()?;
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
@@ -624,7 +647,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
/// then propagates the original error, as before.
#[allow(clippy::too_many_arguments)]
fn timeout_fallback_estimate(
path: &Path,
fallback_mount_path: Option<&Path>,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -639,7 +662,7 @@ fn timeout_fallback_estimate(
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
exact_prefix_bytes.saturating_add(estimated_overflow)
});
let disk_used = mount_point_used_bytes(path);
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -699,9 +722,8 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
let path = path.to_path_buf();
let limits = ScanLimits::from_env();
let budget = outer_scan_budget(&limits);
// The blocking thread cannot be killed; on ceiling expiry the caller (and
@@ -734,6 +756,13 @@ async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::
}
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled before starting",
));
}
let ScanLimits {
max_files_threshold,
base_timeout,
@@ -742,13 +771,28 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
#[cfg(target_os = "linux")]
if let Some(mount_usage) = &limits.mount_usage {
let start_time = Instant::now();
let used_bytes = mount_usage.used_bytes(path);
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled while reading mount usage",
));
}
if let Some(used_bytes) = used_bytes {
record_capacity_scan_mode("mount_usage");
return Ok(CapacityScanResult {
used_bytes,
is_estimated: true,
scan_duration: start_time.elapsed(),
..Default::default()
});
}
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -761,7 +805,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
let path = resolved_root.as_path();
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
#[cfg(target_os = "linux")]
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
#[cfg(not(target_os = "linux"))]
let fallback_mount_path = Some(path);
let start_time = Instant::now();
let mut exact_prefix_bytes = 0u64;
let mut overflow_sampled_bytes = 0u64;
let mut file_count = 0usize;
@@ -816,7 +866,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
Ok(half_elapsed) => half_elapsed,
Err(e) => {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -989,7 +1039,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1220,6 +1270,8 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1236,7 +1288,7 @@ mod tests {
#[test]
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1248,7 +1300,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1265,7 +1317,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1284,7 +1336,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1309,14 +1361,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 16);
assert_eq!(size.file_count, 2);
}
#[tokio::test]
async fn test_get_dir_size_async_nonexistent_directory() {
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
assert!(result.is_err());
}
@@ -1424,12 +1476,45 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
// A tempdir lives on the same filesystem as its parent, so statvfs
// must not be trusted as a per-disk proxy there.
let temp_dir = tempfile::TempDir::new().unwrap();
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
let limits = ScanLimits {
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
..tight_limits(Duration::from_secs(60))
};
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
assert_eq!(scan.used_bytes, 12);
assert_eq!(scan.file_count, 1);
assert!(!scan.is_estimated);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_completes_without_walk_budget() {
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
let path = Path::new("/dev/shm");
let mount_usage = Arc::new(MountUsageSnapshot::default());
if mount_usage.used_bytes(path).is_none() {
return;
}
let limits = ScanLimits {
mount_usage: Some(mount_usage),
..tight_limits(Duration::ZERO)
};
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
let drive_link = temp_dir.path().join("drive");
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
for root in [path, drive_link.as_path()] {
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
assert!(scan.is_estimated);
assert!(!scan.timed_out);
assert!(!scan.metadata_incomplete);
assert_eq!(scan.file_count, 0);
assert_eq!(scan.metadata_reads, 0);
}
}
#[test]
@@ -1452,6 +1537,8 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1851,6 +1938,35 @@ mod tests {
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].endpoint, "disk-2");
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
let replacement = vec![
disks[0].clone(),
CapacityDiskRef {
endpoint: "disk-3".into(),
drive_path: "/tmp/disk-3".into(),
},
];
// Replacing a disk changes membership even when the disk count stays
// the same and the only dirty mark belonged to the removed disk.
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement.clone(),
dirty_subset: false,
}
);
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![disk_scope_key(&replacement[1])],
})
.await;
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement,
dirty_subset: false,
}
);
}
#[cfg(unix)]
@@ -1869,7 +1985,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
@@ -1894,7 +2010,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
+2
View File
@@ -70,6 +70,8 @@ pub struct PartInfo {
pub size: usize,
pub etag: Option<String>,
pub actual_size: i64,
/// Checksums recorded when the part was uploaded, keyed by algorithm name.
pub checksums: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default)]
+109 -23
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
use rustix::fs::statfs;
use std::collections::BTreeSet;
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, Error, ErrorKind, Read};
@@ -27,27 +27,10 @@ static BAVAIL_GT_BFREE_WARNING_PATHS: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceL
/// Returns total and free bytes available in a directory, e.g. `/`.
pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
// Use statfs on Linux to get access to f_type (filesystem magic number)
let stat = statfs(p.as_ref())?;
// Linux statfs:
// f_bsize: Optimal transfer block size
// f_blocks: Total data blocks in file system
// f_frsize: Fragment size (since Linux 2.6) - unit for blocks
//
// If f_frsize is > 0, it is the unit for f_blocks, f_bfree, f_bavail.
// Otherwise f_bsize is used.
let bsize = if stat.f_frsize > 0 {
stat.f_frsize as u64
} else {
stat.f_bsize as u64
};
let bfree = stat.f_bfree as u64;
let bavail = stat.f_bavail as u64;
let blocks = stat.f_blocks as u64;
let (total, free, used) = calculate_space_usage(blocks, bfree, bavail, bsize, p.as_ref())?;
let st = rustix::fs::stat(p.as_ref())?;
let path = p.as_ref();
let stat = statfs(path)?;
let (total, free, used) = statfs_space_usage(&stat, path)?;
let st = rustix::fs::stat(path)?;
Ok(DiskInfo {
total,
@@ -62,6 +45,84 @@ pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
})
}
fn statfs_space_usage(stat: &StatFs, path: &Path) -> io::Result<(u64, u64, u64)> {
// Block counts are in fragment-size units when the kernel provides them.
let block_size = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize };
calculate_space_usage(stat.f_blocks, stat.f_bfree, stat.f_bavail, block_size as u64, path)
}
/// Snapshot of Linux whole-filesystem mount eligibility for one refresh.
///
/// The mount table is read lazily when the first candidate mount root is
/// probed. The caller is responsible for ensuring exclusive use of the filesystem.
#[derive(Debug, Default)]
pub struct MountUsageSnapshot(OnceLock<Option<HashMap<u64, (u32, u32)>>>);
impl MountUsageSnapshot {
/// Return filesystem-reported used bytes for a directory at an eligible mount root.
///
/// Direct accounting is supported for XFS, the ext family, and tmpfs.
/// Returns `None` when the mount or its filesystem type is ineligible
/// or the kernel cannot identify or read the mounted filesystem.
pub fn used_bytes(&self, path: &Path) -> Option<u64> {
let directory = open(path, OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).ok()?;
let stat = statx(&directory, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
if !StatxFlags::from_bits_retain(stat.stx_mask).contains(StatxFlags::MNT_ID)
|| !stat.stx_attributes.contains(StatxAttributes::MOUNT_ROOT)
{
return None;
}
let mounts = self
.0
.get_or_init(|| {
let mountinfo = fs::read("/proc/self/mountinfo").ok()?;
eligible_usage_mounts(&String::from_utf8_lossy(&mountinfo))
})
.as_ref()?;
if mounts.get(&stat.stx_mnt_id) != Some(&(stat.stx_dev_major, stat.stx_dev_minor)) {
return None;
}
// Read the same mount that was classified, even if the path was replaced.
let stat = fstatfs(directory).ok()?;
if !supports_direct_mount_usage(stat.f_type as u64) {
return None;
}
let (_, _, used) = statfs_space_usage(&stat, path).ok()?;
Some(used)
}
}
fn supports_direct_mount_usage(fs_type: u64) -> bool {
// Distinct mount and device IDs do not establish independent block
// accounting on filesystems that share a pool across subvolumes.
matches!(get_fs_type(fs_type), "XFS" | "EXT4" | "TMPFS")
}
fn eligible_usage_mounts(mountinfo: &str) -> Option<HashMap<u64, (u32, u32)>> {
let mut devices = HashMap::new();
let mut parents = HashSet::new();
for line in mountinfo.lines() {
let mut fields = line.split_ascii_whitespace();
let id: u64 = fields.next()?.parse().ok()?;
let parent: u64 = fields.next()?.parse().ok()?;
let (major, minor) = fields.next()?.split_once(':')?;
let device = (major.parse().ok()?, minor.parse().ok()?);
let root = fields.next()?;
parents.insert(parent);
// A second view of the same device may alias accounting for the whole filesystem.
devices
.entry(device)
.and_modify(|mount| *mount = None)
.or_insert((root == "/").then_some(id));
}
Some(
devices
.into_iter()
.filter_map(|(device, id)| id.filter(|id| !parents.contains(id)).map(|id| (id, device)))
.collect(),
)
}
fn calculate_space_usage(blocks: u64, bfree: u64, bavail: u64, bsize: u64, path: &Path) -> std::io::Result<(u64, u64, u64)> {
let available = if bfree < bavail {
if should_warn_bavail_greater_than_bfree(path) {
@@ -450,6 +511,31 @@ mod tests {
assert_eq!(mountinfo_path(line), Some("/data/replacement"));
}
#[test]
fn mount_usage_requires_a_unique_whole_filesystem_with_no_child_mounts() {
let mountinfo = "\
1 0 0:1 / / rw - overlay overlay rw\n\
2 1 0:2 / /data/whole rw - tmpfs tmpfs rw\n\
3 1 0:3 /subdir /data/bind rw - tmpfs tmpfs rw\n\
4 1 0:4 / /data/parent rw - tmpfs tmpfs rw\n\
5 4 0:5 / /data/parent/child rw - tmpfs tmpfs rw\n\
6 1 0:6 / /data/alias1 rw - tmpfs tmpfs rw\n\
7 1 0:6 / /data/alias2 rw - tmpfs tmpfs rw";
assert_eq!(eligible_usage_mounts(mountinfo), Some(HashMap::from([(2, (0, 2)), (5, (0, 5))])));
assert!(eligible_usage_mounts("1 0 no-device /").is_none());
}
#[test]
fn mount_usage_uses_only_filesystems_with_independent_block_accounting() {
assert!(supports_direct_mount_usage(0x58465342)); // XFS
assert!(supports_direct_mount_usage(0xEF53)); // ext family
assert!(supports_direct_mount_usage(0x01021994)); // tmpfs
assert!(!supports_direct_mount_usage(0x9123683E)); // Btrfs
assert!(!supports_direct_mount_usage(0x2FC12FC1)); // ZFS
assert!(!supports_direct_mount_usage(0x794C7630)); // OverlayFS
assert!(!supports_direct_mount_usage(0x6969)); // NFS
}
#[test]
fn reject_relative_path_for_cross_device_validation() {
let err = ensure_no_sub_mounts("relative/path", &[]).unwrap_err();
+3 -1
View File
@@ -24,7 +24,9 @@ mod unix;
mod windows;
#[cfg(target_os = "linux")]
pub use linux::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
pub use linux::{
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
};
#[cfg(all(unix, not(target_os = "linux")))]
pub use unix::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
+32 -36
View File
@@ -13,7 +13,7 @@
# limitations under the License.
services:
# RustFS main service
# RustFS single-node single-disk (SNSD) service
rustfs:
image: rustfs/rustfs:latest
container_name: rustfs-server
@@ -23,31 +23,29 @@ services:
security_opt:
- "no-new-privileges:true"
ports:
- "9000:9000" # S3 API port
- "9001:9001" # Console port
- "${RUSTFS_S3_PORT:-9000}:9000" # S3 API port
- "${RUSTFS_CONSOLE_PORT:-9001}:9001" # Console port
environment:
- RUSTFS_VOLUMES=/data/rustfs{0...3}
- RUSTFS_VOLUMES=/data
- RUSTFS_ADDRESS=0.0.0.0:9000
- RUSTFS_CONSOLE_ADDRESS=0.0.0.0:9001
- RUSTFS_CONSOLE_ENABLE=true
- RUSTFS_CONSOLE_CORS_ALLOWED_ORIGINS=*
- RUSTFS_ACCESS_KEY=rustfsadmin # CHANGEME
- RUSTFS_SECRET_KEY=rustfsadmin # CHANGEME
- RUSTFS_ACCESS_KEY=${RUSTFS_ACCESS_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_SECRET_KEY=${RUSTFS_SECRET_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_OBS_LOGGER_LEVEL=info
- RUSTFS_OBS_LOG_DIRECTORY=/app/logs
- RUSTFS_OBS_LOG_DIRECTORY=/logs
# Optional TLS:
# - mount your cert directory to /opt/tls
# - set RUSTFS_TLS_PATH=/opt/tls
# - when TLS is enabled, health checks automatically switch to HTTPS
# Keep strict disk topology checks enabled by default.
# For local testing only, set `RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true` explicitly.
- RUSTFS_UNSAFE_BYPASS_DISK_CHECK=${RUSTFS_UNSAFE_BYPASS_DISK_CHECK:-false}
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
ulimits:
nofile:
soft: 65535
hard: 65535
networks:
- rustfs-network
restart: unless-stopped
@@ -63,21 +61,21 @@ services:
test:
[
"CMD",
"sh", "-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS; \
"sh",
"-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS --connect-timeout 3 --max-time 5; \
if [ -n \"$${RUSTFS_TLS_PATH:-}\" ]; then \
scheme=\"https\"; \
ca_path=\"$${RUSTFS_HEALTHCHECK_CA:-}\"; \
if [ -z \"$${ca_path}\" ] && [ -f /opt/tls/ca.crt ]; then ca_path=/opt/tls/ca.crt; fi; \
case \"$${host}\" in 127.0.0.1|localhost) strict_host=false ;; *) strict_host=true ;; esac; \
if [ \"$${strict_host}\" = true ] && [ -n \"$${ca_path}\" ]; then \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\" --resolve \"$${host}:9001:127.0.0.1\"; \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\"; \
else \
set -- \"$${@}\" -k; \
fi; \
fi; \
curl \"$${@}\" \"$${scheme}://$${host}:9000/health\" && \
curl \"$${@}\" \"$${scheme}://$${host}:9001/rustfs/console/health\""
curl \"$${@}\" \"$${scheme}://$${host}:9000/health/ready\""
]
interval: 30s
timeout: 10s
@@ -86,30 +84,28 @@ services:
# RustFS volume permissions fixer service
volume-permission-helper:
image: alpine
image: alpine:3.24
network_mode: none
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
command: >
sh -c "
chown -R 10001:10001 /data/rustfs0 /data/rustfs1 /data/rustfs2 /data/rustfs3 /app/logs &&
echo 'Volume Permissions fixed' &&
exit 0
"
sh -ec '
for dir in /data /logs; do
if [ "$$(stat -c %u:%g "$$dir")" != "10001:10001" ]; then
chown -R 10001:10001 "$$dir"
fi
done
echo "Volume permissions ready"
'
# Permission baseline:
# - default RustFS runtime user is 10001:10001
# - alternatively, run rustfs service with host-matched `user: \"<uid>:<gid>\"`
# - alternatively, run rustfs service with host-matched `user: "<uid>:<gid>"`
restart: "no"
networks:
rustfs-network:
volumes:
rustfs_data_0:
rustfs_data_1:
rustfs_data_2:
rustfs_data_3:
rustfs_data:
logs:
@@ -11,6 +11,10 @@
## Open Items
- `http-opaque-response-headers` HTTP response encoding. Preserve UTF-8 lifecycle rule IDs in x-amz-expiration and UTF-8 Content-Type parameters while the gateway string encoder accepts only ASCII. Remove the RustFS projection after the gateway emits the original opaque bytes in these response headers.
- `metrics-024-recorder` dependency constraint bridge. The workspace still resolves metrics 0.24 for Metrique and its metrics utility. The local crate re-exports metrics 0.25 so all producers share the same recorder. Remove the crate and workspace Cargo patch after every resolved consumer accepts metrics 0.25 directly.
- `9526` NIXL shard reads recognize the exact file-missing response from peers that predate the disk error header. Remove the response-body check once all supported NIXL peers send the header.
- `openidconnect-hmac-signature-width` ID token verification guard: openidconnect 4.1.0 converts decoded HMAC signatures to fixed-size arrays, which panic on unexpected lengths. Check HS256, HS384, and HS512 signature widths before delegating all cryptographic, issuer, audience, expiry, and nonce checks to the upstream verifier. Remove the guard after a supported upstream release returns verification errors for arbitrary HMAC signature lengths.
@@ -98,6 +98,8 @@ For a dedicated Linux test cluster, add the following flags to the ABBA command
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
The queue TSV also records `completed_writes`, `write_ms_per_op`, and `peak_write_ms_per_op` for the same samples. Write latency divides the change in milliseconds spent writing by the change in completed writes. The node average is weighted by completed writes, and the peak is the highest per-device average among devices with write completions. A window with no completed writes reports zero completions and `NA` for both latency fields. Compare the last two samples of successful attempts across legs to check for different write completion behavior at similarly low queue depths. These fields are diagnostic and the existing queue and drift thresholds still apply.
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
+2
View File
@@ -22,6 +22,8 @@ Specialized boundary, hardware and alternate-feature lanes run only on the sched
Workspace Clippy runs on every event with a selected workspace Rust job, pull requests included, in its own `Workspace Clippy` job. It runs beside `Workspace Lint and Build` instead of in front of it, because check-mode metadata and the linked test binaries share no compiler output; `scripts/ci_gate.py --check-workflow` rejects a workflow in which the archive producer or any archive consumer waits for the lint, or in which the lint leaves the aggregate. `Workspace Lint and Build` keeps its name as the archive producer: it creates the exact test archive and runs doctests; `Workspace tests` consumes the archive without rebuilding it. `cache-warm.yml` warms Clippy's check artifacts under `ci-dev` with the same invocation to reuse compatible dependency artifacts. `make pre-commit` does not run Clippy. Select local Clippy targets, features, and documentation exemptions from the root `AGENTS.md` verification tier; the workspace command below reproduces the CI lane and is not a universal pre-push requirement.
Full-scope runs also execute the production ECStore suite in `dst_production_ecstore` against simulated disks with `--features dst`. It checks the durability of acknowledged writes, metadata publication, and multipart retries with valid, missing, or misplaced per-drive evidence. The workspace producer retains the nextest listing and JUnit report and verifies that every required case passed.
Serial ILM tests run at the end of `workspace-tests` for the `full` scope, consuming the same verified archive as ordinary workspace tests. The existing ignored-test filter and `-j1` remain; `--profile default` keeps the no-retry execution and preserves the separate core CI JUnit report. Any ILM failure fails the consumer and required aggregate. Logs remain in the workspace test evidence artifact. There is no separate ILM compilation or cache restore.
`required-checks` runs even after failed or skipped dependencies. `scripts/ci_gate.py verify` rejects missing jobs, unexpected jobs, failure, cancellation, and unexpected skips; optional lanes are required only on their declared events. `Workspace Clippy` is the workspace lint, `Workspace Lint and Build` and `Workspace tests` are the ordinary Rust producer and consumer, while `Test and Lint` uniquely names the aggregate. New validation jobs must update both its direct dependencies and the script contract. A report-only lane is registered in `REPORT_ONLY_JOBS` instead: it stays out of the aggregate, must keep its distinguishing environment, and must keep the steps it reruns identical to the required job it mirrors. Test this wiring and its failure cases with `python3 scripts/ci_gate.py --self-test`.
+238 -97
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.162.0"
version = "1.163.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
]
@@ -1364,9 +1364,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "byteorder"
version = "1.5.0"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
[[package]]
name = "bytes"
@@ -1512,7 +1512,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"subtle",
]
@@ -3636,7 +3636,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3656,9 +3656,9 @@ checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
[[package]]
name = "http"
version = "1.5.0"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
dependencies = [
"bytes",
"itoa",
@@ -3804,7 +3804,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
"windows-core 0.62.2",
]
[[package]]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.15"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -3975,7 +3975,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result",
"windows-result 0.4.1",
"windows-sys 0.61.2",
]
@@ -4041,23 +4041,23 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "jiff"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"
dependencies = [
"jiff-core 1.0.2",
"jiff-static 1.0.3",
"jiff-core 1.1.0",
"jiff-static 1.1.0",
"jiff-tzdb-platform 1.0.0",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4072,9 +4072,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "1.0.2"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"
dependencies = [
"log",
]
@@ -4093,11 +4093,11 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"
dependencies = [
"jiff-core 1.0.2",
"jiff-core 1.1.0",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -4147,7 +4147,7 @@ dependencies = [
"simd_cesu8",
"thiserror",
"walkdir",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4527,9 +4527,9 @@ dependencies = [
[[package]]
name = "metrics"
version = "0.24.6"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2"
checksum = "eb1b882a87a42420c952fbb7173ff4fa5d380b51eb26c95bf77435811201db7a"
dependencies = [
"portable-atomic",
"rapidhash",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -5094,7 +5094,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5106,7 +5106,7 @@ dependencies = [
"libc",
"redox_syscall 0.9.5",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
]
@@ -6362,7 +6362,7 @@ dependencies = [
"hyper",
"hyper-rustls",
"hyper-util",
"jiff 1.0.3",
"jiff 1.1.0",
"lazy_static",
"libc",
"md-5",
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"slab",
"smallvec",
@@ -6432,7 +6432,7 @@ dependencies = [
"urlencoding",
"uuid",
"winapi-util",
"windows-sys 0.61.2",
"windows-sys 0.101.0",
"xxhash-rust",
]
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6492,7 +6492,7 @@ dependencies = [
"arbitrary",
"bytes",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"libfuzzer-sys",
"quick-xml 0.42.0",
"rustfs-ecstore",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"tokio",
"uuid",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"twox-hash",
"unicode-normalization",
@@ -6592,9 +6592,9 @@ dependencies = [
[[package]]
name = "rustfs-kafka"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82dc39ba1a5a9f6b2e49decb0b54c23ebaebdfb08a899307c266694bfd269bf9"
checksum = "d66b41fff6ef985a310f7dac070fda947b7588e56decd837084c41edc24841a0"
dependencies = [
"base64 0.23.1",
"bytes",
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"thiserror",
"tracing",
@@ -6617,20 +6617,21 @@ dependencies = [
[[package]]
name = "rustfs-kafka-async"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "684f5e78ea1421bbf915e4cd0515bdefd587cfa281da000e41ae4a434f90195a"
checksum = "7ceb19d7045aa067259792637be2f72c971aece9ccaf7f6c76ec7ac272904d37"
dependencies = [
"base64 0.23.1",
"bytes",
"hmac 0.13.0",
"indexmap",
"kafka-protocol",
"metrics",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-rustls",
"tracing",
@@ -6654,7 +6655,7 @@ dependencies = [
"chacha20poly1305",
"hex-simd",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"md-5",
"metrics",
"moka",
@@ -6665,7 +6666,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"thiserror",
"tokio",
@@ -6724,7 +6725,7 @@ dependencies = [
"http",
"humantime",
"hyper",
"jiff 1.0.3",
"jiff 1.1.0",
"reqwest",
"rustfs-signer",
"serde",
@@ -6742,7 +6743,7 @@ dependencies = [
"form_urlencoded",
"hashbrown 0.17.2",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"percent-encoding",
"quick-xml 0.42.0",
@@ -6795,7 +6796,7 @@ dependencies = [
"base64-simd",
"futures",
"ipnetwork",
"jiff 1.0.3",
"jiff 1.1.0",
"jsonwebtoken",
"moka",
"regex",
@@ -6878,7 +6879,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tokio-util",
@@ -6919,7 +6920,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6971,7 +6972,7 @@ dependencies = [
"futures-core",
"hotpath",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"lz4",
"lz4_flex",
"memchr",
@@ -7016,7 +7017,7 @@ dependencies = [
name = "rustfs-scanner-metrics"
version = "1.0.8"
dependencies = [
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"rmp-serde",
"rustfs-heal-contracts",
@@ -7092,7 +7093,7 @@ dependencies = [
"hotpath",
"hyper",
"hyper-rustls",
"jiff 1.0.3",
"jiff 1.1.0",
"lapin",
"libc",
"metrics",
@@ -7114,7 +7115,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"snap",
"sysinfo",
"thiserror",
@@ -7139,7 +7140,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tracing",
@@ -7148,8 +7149,9 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
dependencies = [
"io-uring",
"libc",
@@ -7183,14 +7185,14 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"siphasher",
"snap",
"tokio",
"tracing",
"transform-stream",
"url",
"windows",
"windows 0.101.0",
"zstd 0.14.5",
]
@@ -7551,9 +7553,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.2"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7784,9 +7786,9 @@ dependencies = [
[[package]]
name = "starshard"
version = "2.4.1"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0883700b50fd0b62120ebc4c07230e02f0cf1ead474c3b3b44eaa13e0a999ea"
checksum = "adc82b6d069d07eb9b6433ccabdaf31ea1508cd240f6fe12284e0dd3d7609bd5"
dependencies = [
"async-trait",
"hashbrown 0.17.2",
@@ -7902,9 +7904,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -7913,7 +7915,7 @@ dependencies = [
"objc2-io-kit",
"objc2-open-directory",
"rayon",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -8156,7 +8158,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -8847,10 +8849,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752"
dependencies = [
"windows-collections 0.101.0",
"windows-core 0.101.0",
"windows-future 0.101.0",
"windows-numerics 0.101.0",
"windows-reference",
"windows-time",
]
[[package]]
@@ -8859,7 +8875,16 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
"windows-core 0.62.2",
]
[[package]]
name = "windows-collections"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
@@ -8868,11 +8893,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-core"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac"
dependencies = [
"windows-implement 0.101.0",
"windows-interface 0.101.0",
"windows-link 0.101.0",
"windows-result 0.101.0",
"windows-strings 0.101.0",
]
[[package]]
@@ -8881,9 +8919,20 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
name = "windows-future"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551"
dependencies = [
"windows-core 0.101.0",
"windows-link 0.101.0",
"windows-threading 0.101.0",
]
[[package]]
@@ -8897,6 +8946,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -8908,20 +8968,56 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-numerics"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-reference"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466"
dependencies = [
"windows-core 0.101.0",
"windows-time",
]
[[package]]
@@ -8930,9 +9026,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
@@ -8941,7 +9037,16 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8950,7 +9055,16 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8968,7 +9082,16 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8993,7 +9116,25 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-threading"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-time"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
+1 -1
View File
@@ -16,7 +16,7 @@ path = "src/lib.rs"
[dependencies]
arbitrary = { version = "1", features = ["derive"] }
bytes = "1.12.2"
http = "1.5.0"
http = "1.6.0"
jiff = { version = "1.0.2", features = ["serde"] }
libfuzzer-sys = "0.4"
quick-xml = { version = "0.42.0", features = ["serialize", "serde-types", "encoding"] }
+1 -1
View File
@@ -422,7 +422,7 @@ rustfs-mimalloc = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
libsystemd.workspace = true
rustfs-mimalloc = { workspace = true, features = ["no_thp"] }
rustfs-mimalloc-sys = "0.7.5"
rustfs-mimalloc-sys = "0.7.6"
[target.'cfg(any(all(target_os = "macos", any(target_arch = "x86_64", target_arch = "aarch64")), all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64"))))'.dependencies]
pyroscope = { workspace = true, optional = true, features = ["backend-pprof-rs"] }
+1 -1
View File
@@ -53,7 +53,7 @@ pub(crate) struct ResponseEtag {
impl ResponseEtag {
pub(crate) fn to_http_header(&self) -> Result<http::HeaderValue, http::header::InvalidHeaderValue> {
let prefix = if self.weak { "W/" } else { "" };
http::HeaderValue::from_str(&format!("{prefix}\"{}\"", self.opaque))
http::HeaderValue::from_bytes(format!("{prefix}\"{}\"", self.opaque).as_bytes())
}
pub(super) fn from_stored(value: &str) -> Self {
+2 -1
View File
@@ -85,7 +85,8 @@ pub(crate) fn post_metadata_headers(
}
}
if let Some(value) = content_type {
let wire = HeaderValue::from_str(value).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let wire =
HeaderValue::from_bytes(value.as_bytes()).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let base = value.split(';').next().unwrap_or(value).trim();
if !base.is_ascii() {
return Err(s3_error!(InvalidArgument, "Invalid POST content field"));
+2 -2
View File
@@ -740,7 +740,7 @@ fn build_put_object_expiration_header(event: &lifecycle::Event) -> Option<String
// parser, which rejects `2026-10-02T00:00:00Z` and drops the metadata.
let expiry_date = format_http_date(&expire_time).ok()?;
let value = format!("expiry-date=\"{}\", rule-id=\"{}\"", expiry_date, event.rule_id);
http::HeaderValue::from_str(&value).is_ok().then_some(value)
http::HeaderValue::from_bytes(value.as_bytes()).is_ok().then_some(value)
}
pub(super) fn internal_object_info_lookup_opts(mut opts: ObjectOptions) -> ObjectOptions {
@@ -2278,7 +2278,7 @@ mod tests {
}
event.rule_id = "保留策略".to_owned();
let header = build_put_object_expiration_header(&event).expect("valid UTF-8 IDs remain supported");
assert!(http::HeaderValue::from_str(&header).is_ok());
assert!(http::HeaderValue::from_bytes(header.as_bytes()).is_ok());
assert!(header.contains("保留策略"));
}
@@ -152,6 +152,14 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
.user_defined
.keys()
.any(|key| rustfs_utils::http::is_object_encryption_marker(key));
// The upload's checksum contract, recorded at CreateMultipartUpload, is echoed here so a
// client resuming from ListParts sees the same algorithm and type.
let checksum_algorithm = (!page.checksum_algorithm.is_empty())
.then_some(page.checksum_algorithm)
.map(dto::ChecksumAlgorithm::custom);
let checksum_type = (!page.checksum_type.is_empty())
.then_some(page.checksum_type)
.map(dto::ChecksumType::custom);
let parts = page
.parts
.into_iter()
@@ -168,12 +176,23 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
i64::try_from(part.size)
.map_err(|_| s3_error!(InternalError, "a stored part size is outside the ListParts response range"))?
};
let checksums = part.checksums.unwrap_or_default();
let checksum = |algorithm: &str| checksums.get(algorithm).cloned();
Ok(dto::Part {
e_tag: dto_values::stored_etag(tag),
last_modified: part.last_mod.map(dto_values::timestamp),
part_number,
size,
..Default::default()
checksum_crc32: checksum("CRC32"),
checksum_crc32c: checksum("CRC32C"),
checksum_crc64nvme: checksum("CRC64NVME"),
checksum_sha1: checksum("SHA1"),
checksum_sha256: checksum("SHA256"),
checksum_sha512: checksum("SHA512"),
checksum_md5: checksum("MD5"),
checksum_xxhash3: checksum("XXHASH3"),
checksum_xxhash64: checksum("XXHASH64"),
checksum_xxhash128: checksum("XXHASH128"),
})
})
.collect::<S3Result<_>>()?;
@@ -192,6 +211,8 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
storage_class: Some(dto::StorageClass::custom(
effective_class(Some(page.storage_class.as_str()), None).to_owned(),
)),
checksum_algorithm,
checksum_type,
..Default::default()
})
}
@@ -84,6 +84,36 @@ fn test_list_parts_output_maps_parts_and_owner() {
assert_eq!(initiator.display_name, owner.display_name);
}
#[test]
fn test_list_parts_output_maps_recorded_checksums() {
let output = list_parts_output(ListPartsInfo {
checksum_algorithm: "SHA256".into(),
checksum_type: "COMPOSITE".into(),
parts: vec![PartInfo {
size: 5,
checksums: Some(std::collections::HashMap::from([
("CRC32".to_owned(), "part-crc32".to_owned()),
("SHA256".to_owned(), "part-sha256".to_owned()),
])),
..part(1)
}],
..page()
})
.unwrap();
assert_eq!(output.checksum_algorithm.as_ref().map(|value| value.as_str()), Some("SHA256"));
assert_eq!(output.checksum_type.as_ref().map(|value| value.as_str()), Some("COMPOSITE"));
assert_eq!(output.parts[0].checksum_crc32.as_deref(), Some("part-crc32"));
assert_eq!(output.parts[0].checksum_sha256.as_deref(), Some("part-sha256"));
assert!(output.parts[0].checksum_sha1.is_none());
let xml = encode_xml(output);
assert!(xml.contains("<ChecksumAlgorithm>SHA256</ChecksumAlgorithm>"), "{xml}");
assert!(xml.contains("<ChecksumType>COMPOSITE</ChecksumType>"), "{xml}");
assert!(xml.contains("<ChecksumCRC32>part-crc32</ChecksumCRC32>"), "{xml}");
assert!(xml.contains("<ChecksumSHA256>part-sha256</ChecksumSHA256>"), "{xml}");
}
#[test]
fn test_list_parts_output_xml_omits_terminal_marker() {
for (marker, parts) in [(0, vec![]), (3, vec![10]), (0, vec![1, 3])] {
+23
View File
@@ -135,6 +135,18 @@ fn resp<O: Served>(answered: Answered<O::Output>) -> Resp<O> {
.with_extra_headers(headers)
}
// RUSTFS_COMPAT_TODO(http-opaque-response-headers): Preserve UTF-8 response values. Remove after the gateway codec emits opaque bytes.
fn preserve_opaque_header(headers: &mut http::HeaderMap, name: impl http::header::IntoHeaderName, field: Option<&str>) {
// Keep the typed field so the encoder does not write a default Content-Type.
// Its ASCII constructor skips the opaque value, leaving the extra header to supply it.
if let Some(value) = field
&& !value.is_ascii()
&& let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes())
{
headers.insert(name, value);
}
}
impl<O: Served> Handler<O> for GatewayBackend {
async fn call(&self, request: Req<O>) -> HandlerResult<O> {
self.serve(request).await
@@ -270,6 +282,17 @@ mod tests {
assert_eq!(registered, rows(OPERATIONS).map(|row| row.name).collect());
}
#[test]
fn expiration_projection_preserves_utf8_without_accepting_controls() {
let mut headers = http::HeaderMap::new();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留策略\""));
assert_eq!(headers[rustfs_utils::http::AMZ_EXPIRATION].as_bytes(), "rule-id=\"保留策略\"".as_bytes());
headers.clear();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留\n策略\""));
assert!(headers.is_empty());
}
/// An invalid header value does not alter the response status or other headers.
#[test]
fn a_stored_tag_a_header_cannot_hold_is_left_out_and_the_answer_stands() {
@@ -14,7 +14,7 @@
//! The gateway operations of migration batch C (rustfs/backlog#2765): GetObject, HeadObject and GetObjectAttributes.
use super::{OpRow, Served, resp, row};
use super::{OpRow, Served, preserve_opaque_header, resp, row};
use crate::app::object_usecase::{
DefaultObjectUsecase, GetObjectAttributesFields, GetObjectAttributesOutputFacts, GetObjectBody, GetObjectOutputFacts,
HeadObjectOutputFacts, ResponseEtag,
@@ -28,7 +28,7 @@ use crate::storage_api::server::http::access::access_owned::object_read::{
use rustfs_gateway::{Req, Resp, dto};
use rustfs_s3_ops::S3Operation;
use rustfs_s3_types::{S3ErrorCode, S3Result, s3_error};
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use rustfs_utils::http::{AMZ_EXPIRATION, SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use std::sync::Arc;
pub(super) const ROWS: &[OpRow] = &[
@@ -63,9 +63,18 @@ impl Served for dto::HeadObject {
authorize_head_object(&server_ctx, envelope, bucket, key, version_id).await
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let preserve_content_type = request.input().response_content_type.is_none();
let result = DefaultObjectUsecase::with_context(context)
.execute_head_object(envelope, request.into_input())
.await;
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
});
head_result(result)
}
}
@@ -95,10 +104,19 @@ impl Served for dto::GetObject {
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let log_error = super::error::object_error_logger("GetObject", request.context().transport_extensions().clone());
let preserve_content_type = request.input().response_content_type.is_none();
let result = get_result(
DefaultObjectUsecase::with_context(context)
.execute_gateway_get_object(envelope, request.into_input())
.await,
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
}),
);
result.inspect_err(log_error)
}
@@ -222,6 +240,7 @@ pub(super) fn get_response(answered: Answered<GetObjectOutputFacts>) -> S3Result
} = answered;
insert_etag(&mut headers, output.etag)
.map_err(|_| s3_error!(InternalError, "We encountered an internal error. Please try again."))?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
output.dto.body = output
.body
.map(|body| match body {
@@ -271,6 +290,7 @@ pub(super) fn head_response(answered: Answered<HeadObjectOutputFacts>) -> S3Resu
mut headers,
} = answered;
insert_etag(&mut headers, output.etag)?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
Ok(resp::<dto::HeadObject>(Answered {
output: output.dto,
status,
@@ -14,7 +14,7 @@
//! PutObject gateway registration and native request/response projection.
use super::{OpRow, Served, row};
use super::{OpRow, Served, preserve_opaque_header, row};
use crate::app::RequestEnvelope;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartTarget, UploadPartWriteInput, UploadPartWriteOutput};
use crate::app::object::FrameTrailers;
@@ -275,6 +275,7 @@ fn native_output(output: PutObjectWriteOutput) -> S3Result<Resp<dto::PutObject>>
output.checksum_crc64nvme,
],
)?;
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, output.expiration.as_deref());
let dto = dto::PutObjectOutput {
e_tag: crate::app::dto_values::stored_etag(
output
+1 -1
View File
@@ -794,7 +794,7 @@ pub fn parse_etag(object_etag: &str) -> Result<HeaderValue, S3Error> {
let etag_quoted = format!("\"{}\"", etag_trimmed);
HeaderValue::from_str(&etag_quoted).map_err(|e| {
HeaderValue::from_bytes(etag_quoted.as_bytes()).map_err(|e| {
warn!(
"Failed to convert ETag to HeaderValue (ETag: {}): {}. The ETag header will be omitted from the response.",
etag_quoted, e
@@ -807,6 +807,17 @@ fn gateway_post_archive_encoding_uses_form_content_fields() {
.request("GET", &format!("/{BUCKET}/quoted-utf8"), b"", &[], Some(0))
.await;
assert_eq!(read.headers.get("content-type").map(String::as_str), Some("text/plain; name=\"café\""));
let overridden = root
.request(
"GET",
&format!("/{BUCKET}/quoted-utf8?response-content-type=text%2Fplain"),
b"",
&[],
Some(0),
)
.await;
assert_eq!(overridden.status, 200, "{}", overridden.body);
assert_eq!(overridden.headers.get("content-type").map(String::as_str), Some("text/plain"));
server.shutdown().await;
},
);
+19 -3
View File
@@ -24,6 +24,16 @@ CORE_TESTS = {
"head_object_consistency_test::head_object_consistency_after_write_and_multipart_and_presigned_head",
"storage_class_capability_test::tests::historical_label_only_metadata_is_standard_without_hiding_a_real_transition_tier",
}
DST_SUITE = "rustfs-ecstore::dst_production_ecstore"
DST_TESTS = {
"dst_prod_test1_quorum_put_get_delete_offline_and_enospc",
"dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal",
"dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed",
"metadata_write_crash_preserves_published_metadata",
"dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence",
"dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup",
"multipart_replay_rejects_missing_or_other_disk_anchor",
}
def output(*args):
@@ -151,12 +161,16 @@ def selected_tests(listing):
return selected
def verify_execution(listing, junit, core=False):
def verify_execution(listing, junit, core=False, dst=False):
inventory = json.loads(Path(listing).read_text())
expected = selected_tests(inventory)
known = {(binary, name) for binary, suite in inventory["rust-suites"].items() for name in suite["testcases"]}
if core and (len(expected) != len(CORE_TESTS) or {name for _, name in expected} != CORE_TESTS):
raise ValueError("core contract must select exactly the write/read, denial and restart proofs")
if dst:
missing = {(DST_SUITE, name) for name in DST_TESTS} - expected
if missing:
raise ValueError(f"missing production DST tests: {sorted(missing)}")
report = ET.parse(junit).getroot()
if report.tag != "testsuites" or report.get("failures") != "0" or report.get("errors") != "0":
raise ValueError("test report must be a successful nextest run")
@@ -201,7 +215,9 @@ def main():
child = sub.add_parser("evidence")
child.add_argument("listing", type=Path)
child.add_argument("junit", type=Path)
child.add_argument("--core", action="store_true")
required = child.add_mutually_exclusive_group()
required.add_argument("--core", action="store_true")
required.add_argument("--dst", action="store_true")
args = parser.parse_args()
try:
if args.command == "build":
@@ -221,7 +237,7 @@ def main():
"doc": [*selection, "--doc"], "warm": ["--no-run", *selection]}[args.operation]
subprocess.run(command, cwd=ROOT, check=True)
else:
print(f"Verified {verify_execution(args.listing, args.junit, args.core)} test executions")
print(f"Verified {verify_execution(args.listing, args.junit, args.core, args.dst)} test executions")
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.CalledProcessError) as error:
print(f"verification artifact: {error}", file=sys.stderr)
return 1
+13 -2
View File
@@ -244,10 +244,10 @@ class ExecutionEvidenceTests(unittest.TestCase):
self.listing = listing([("crate-a", "one", False), ("crate-b", "two", False), ("crate-b", "ignored", True)])
self.report = junit([("crate-a", "one", None), ("crate-b", "two", None)])
def verify(self, listing_value=None, report=None, *, core=False):
def verify(self, listing_value=None, report=None, *, core=False, dst=False):
self.listing_file.write_text(json.dumps(self.listing if listing_value is None else listing_value))
ET.ElementTree(self.report if report is None else report).write(self.junit_file)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core, dst=dst)
def test_exact_selected_set_and_known_ignored_cases(self):
self.assertEqual(self.verify(), 2)
@@ -321,6 +321,17 @@ class ExecutionEvidenceTests(unittest.TestCase):
with self.subTest(attribute=attribute), self.assertRaises(ValueError):
self.verify(report=report)
def test_dst_rejects_a_green_report_with_a_missing_required_test(self):
cases = [(artifact.DST_SUITE, name) for name in sorted(artifact.DST_TESTS)]
for selected in [cases, cases[:-1]]:
inventory = listing([(suite, name, False) for suite, name in selected])
report = junit([(suite, name, None) for suite, name in selected])
if selected == cases:
self.assertEqual(self.verify(inventory, report, dst=True), len(cases))
else:
with self.assertRaisesRegex(ValueError, "missing production DST tests"):
self.verify(inventory, report, dst=True)
def test_core_requires_exactly_three_selected_proofs(self):
names = sorted(artifact.CORE_TESTS)
core_listing = listing([("e2e", name, False) for name in names])
+56 -2
View File
@@ -286,18 +286,48 @@ marker="$GUARD_DIR/$host"
case "${QUEUE_FIXTURE:-quiet}" in
missing) exit 2 ;;
hung) exec sleep 60 ;;
diskstats-*)
QUEUE_SAMPLE_DIR="$(mktemp -d "$GUARD_DIR/diskstats.XXXXXXXX")"
export QUEUE_SAMPLE_DIR
trap 'rm -rf -- "$QUEUE_SAMPLE_DIR"' EXIT
printf '10.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cat >"$QUEUE_SAMPLE_DIR/diskstats" <<'STATS'
259 0 nvme0n1 0 0 0 0 20 0 80 40 0 0 100
259 1 nvme1n1 0 0 0 0 30 0 80 60 0 0 100
STATS
cp "$QUEUE_SAMPLE_DIR/diskstats" "$QUEUE_SAMPLE_DIR/after"
if [[ "$QUEUE_FIXTURE" != diskstats-idle ]]; then
writes=24
write_ms=48
case "$QUEUE_FIXTURE" in
diskstats-reset-count) writes=19 ;;
diskstats-reset-time) write_ms=39 ;;
esac
printf '259 0 nvme0n1 0 0 0 0 %s 0 96 %s 0 0 250\n' "$writes" "$write_ms" >"$QUEUE_SAMPLE_DIR/after"
printf '259 1 nvme1n1 0 0 0 0 46 0 128 76 0 0 150\n' >>"$QUEUE_SAMPLE_DIR/after"
fi
advance_diskstats() {
printf '15.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cp "$QUEUE_SAMPLE_DIR/after" "$QUEUE_SAMPLE_DIR/diskstats"
}
export -f advance_diskstats
command=$(printf '%s\n' "$command" | sed \
's@/proc/uptime@"$QUEUE_SAMPLE_DIR/uptime"@g; s@/proc/diskstats@"$QUEUE_SAMPLE_DIR/diskstats"@g; s@^sleep 5$@advance_diskstats@')
bash -c "$command"
exit
;;
reset)
n=0
[[ ! -f "$marker" ]] || read -r n < "$marker"
n=$((n+1))
printf '%s\n' "$n" > "$marker"
if [[ "$host" == host-b && "$n" == 2 ]]; then
echo '0.050000 0.800000'
echo '0.050000 0.800000 0 NA NA'
exit 0
fi
;;
esac
echo '0.050000 0.070000'
echo '0.050000 0.070000 0 NA NA'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
@@ -369,4 +399,28 @@ if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=hung "$SCRIPT_DIR/wait_cluster_disk_que
fi
rg -q 'failed or timed out' "$TMP_DIR/queue-timeout.log"
queue_cmd=("$SCRIPT_DIR/wait_cluster_disk_queue.sh"
--target a=host-a --devices a=nvme0n1+nvme1n1 --timeout-secs 11)
for fixture in diskstats-write diskstats-idle; do
PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.tsv"
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n' >"$TMP_DIR/expected.tsv"
for sample in 1 2; do
if [[ "$fixture" == diskstats-write ]]; then
printf '%s\ta\t0.020000\t0.030000\t20\t1.200000\t2.000000\n' "$sample"
else
printf '%s\ta\t0.000000\t0.000000\t0\tNA\tNA\n' "$sample"
fi
done >>"$TMP_DIR/expected.tsv"
diff -u "$TMP_DIR/expected.tsv" "$TMP_DIR/$fixture.tsv"
done
for fixture in diskstats-reset-count diskstats-reset-time; do
if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.log" 2>&1; then
echo "expected $fixture to fail an otherwise quiet sample" >&2
exit 1
fi
rg -q 'disk queue sample failed or timed out' "$TMP_DIR/$fixture.log"
done
echo "object batch benchmark enhanced tests passed"
+37 -9
View File
@@ -73,6 +73,7 @@ trap 'exit 143' TERM
# Only validated device names are placed in the SSH command. The sampler uses
# monotonic uptime and the weighted I/O milliseconds from /proc/diskstats.
# Write completions and write milliseconds describe the same sampling window.
sample=$(cat <<'REMOTE'
set -eu
export LC_ALL=C
@@ -81,8 +82,8 @@ snapshot() {
BEGIN { n=split(devices,d," "); for(i=1;i<=n;i++) want[d[i]]=1 }
FNR==NR { t=$1; next }
$3 in want {
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
if (NF<14 || $8 !~ /^[0-9]+$/ || $11 !~ /^[0-9]+$/ || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14,$8,$11
got++
}
END { if (got!=n) exit 2 }
@@ -93,10 +94,36 @@ sleep 5
after=$(snapshot)
printf '%s\n--\n%s\n' "$before" "$after" | awk '
$0=="--" { second=1; next }
!second { if ($1 in t) bad=1; t[$1]=$2; w[$1]=$3; count++; next }
{ if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1]) { bad=1; next }
q=($3-w[$1])/(1000*($2-t[$1])); sum+=q; if(q>peak)peak=q; got++ }
END { if (bad||!count||got!=count) exit 2; printf "%.6f %.6f\n",sum/count,peak }
!second {
if ($1 in t) bad=1
t[$1]=$2; w[$1]=$3; writes[$1]=$4; write_ms[$1]=$5
count++
next
}
{
if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1] || $4<writes[$1] || $5<write_ms[$1]) {
bad=1
next
}
q=($3-w[$1])/(1000*($2-t[$1]))
sum+=q
if (q>peak) peak=q
completed=$4-writes[$1]
if (completed>0) {
elapsed_ms=$5-write_ms[$1]
total_completed+=completed
total_write_ms+=elapsed_ms
await_ms=elapsed_ms/completed
if (await_ms>peak_write_ms) peak_write_ms=await_ms
}
got++
}
END {
if (bad||!count||got!=count) exit 2
printf "%.6f %.6f %.0f",sum/count,peak,total_completed
if (total_completed>0) printf " %.6f %.6f\n",total_write_ms/total_completed,peak_write_ms
else printf " NA NA\n"
}
'
REMOTE
)
@@ -104,7 +131,7 @@ REMOTE
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
@@ -125,12 +152,13 @@ while ((end-SECONDS >= 5)); do
quiet=true
for i in "${!targets[@]}"; do
result=$(cat "$artifacts/$i")
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)$ ]]; then
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)\ ([0-9]+)\ (NA|[0-9]+\.[0-9]+)\ (NA|[0-9]+\.[0-9]+)$ ]]; then
echo "invalid disk queue sample from ${targets[i]%%=*}" >&2; exit 1
fi
mean="${BASH_REMATCH[1]}"
peak="${BASH_REMATCH[2]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak" \
"${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}" "${BASH_REMATCH[5]}"
if ! awk -v mean="$mean" -v peak="$peak" 'BEGIN {exit !(mean<=0.25 && peak<=0.75)}'; then quiet=false; fi
done
if [[ "$quiet" == true ]]; then