mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-23 04:39:04 +00:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 566877d3ba | |||
| 23a2c7d776 | |||
| 5f72209446 | |||
| 3294c64fcc | |||
| a8be0f81f5 | |||
| 3179b7acb8 | |||
| d25b84a793 | |||
| a79b806fb4 |
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=9f767b37ed8b1c82da62ea441462d75487785c8086e56f08fb6f6cd89c6e2e52
|
||||
sha256-linux=fbdaf42b220958d4b1e8880e0f8b5a7992d38e21051bb60596dd4538424757d6
|
||||
sha256-darwin=f832043fcca8c0b616c5d820a3a652da7544298ef5812a8668a3a9a3e4607b8b
|
||||
sha256-linux=93b94adb110b86a41d0b7313909e0bf53cb1515e2d08e8f105652b29b249990f
|
||||
|
||||
@@ -39,11 +39,10 @@ jobs:
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout main branch
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: main
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
@@ -89,11 +88,10 @@ jobs:
|
||||
# either casing.
|
||||
NO_PROXY: 127.0.0.1,localhost
|
||||
steps:
|
||||
- name: Checkout main branch
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: main
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
@@ -178,11 +176,10 @@ jobs:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
NO_PROXY: 127.0.0.1,localhost
|
||||
steps:
|
||||
- name: Checkout main branch
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: main
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
//! E2E tests for group management (fixes #2028).
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, admin_request, awscurl_delete, awscurl_get, awscurl_put, init_logging};
|
||||
use crate::common::{RustFSTestEnvironment, admin_ok, admin_request, init_logging};
|
||||
use aws_sdk_s3::config::{Credentials, Region};
|
||||
use aws_sdk_s3::{Client, Config};
|
||||
use tracing::info;
|
||||
@@ -83,7 +83,6 @@ async fn update_group_members_rejects_invalid_new_group_names() -> Result<(), Bo
|
||||
|
||||
/// Test that deleting a group with members fails, and deleting an empty group succeeds.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires awscurl and spawns a real RustFS server"]
|
||||
async fn test_delete_group_requires_empty_membership() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
|
||||
@@ -91,29 +90,58 @@ async fn test_delete_group_requires_empty_membership() -> Result<(), Box<dyn std
|
||||
env.start_rustfs_server(vec![]).await?;
|
||||
|
||||
// 1. Create a user
|
||||
let add_user_url = format!("{}/rustfs/admin/v3/add-user?accessKey=testuser1", env.url);
|
||||
let user_body = serde_json::json!({
|
||||
"secretKey": "testuser1secret",
|
||||
"status": "enabled"
|
||||
});
|
||||
awscurl_put(&add_user_url, &user_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/add-user?accessKey=testuser1",
|
||||
Some(user_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Created testuser1");
|
||||
|
||||
// 2. Create a group with testuser1 as a member
|
||||
let update_members_url = format!("{}/rustfs/admin/v3/update-group-members", env.url);
|
||||
let add_member_body = serde_json::json!({
|
||||
"group": "testgroup",
|
||||
"members": ["testuser1"],
|
||||
"isRemove": false,
|
||||
"groupStatus": "enabled"
|
||||
});
|
||||
awscurl_put(&update_members_url, &add_member_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/update-group-members",
|
||||
Some(add_member_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Added testuser1 to testgroup");
|
||||
|
||||
// 3. Attempt to delete the group while it still has members — should fail
|
||||
let delete_group_url = format!("{}/rustfs/admin/v3/group/testgroup", env.url);
|
||||
let delete_result = awscurl_delete(&delete_group_url, &env.access_key, &env.secret_key).await;
|
||||
assert!(delete_result.is_err(), "deleting a non-empty group should fail");
|
||||
let (delete_status, delete_body) = admin_request(
|
||||
&env.url,
|
||||
http::Method::DELETE,
|
||||
"/rustfs/admin/v3/group/testgroup",
|
||||
None,
|
||||
&env.access_key,
|
||||
&env.secret_key,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
delete_status,
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"deleting a non-empty group must return HTTP 400, body: {delete_body}"
|
||||
);
|
||||
assert!(
|
||||
delete_body.contains("<Code>InvalidRequest</Code>"),
|
||||
"deleting a non-empty group must return InvalidRequest, body: {delete_body}"
|
||||
);
|
||||
assert!(
|
||||
delete_body.contains("<Message>group is not empty</Message>"),
|
||||
"deleting a non-empty group returned an unexpected message: {delete_body}"
|
||||
);
|
||||
info!("Delete of non-empty group correctly rejected");
|
||||
|
||||
// 4. Remove the member from the group
|
||||
@@ -123,17 +151,42 @@ async fn test_delete_group_requires_empty_membership() -> Result<(), Box<dyn std
|
||||
"isRemove": true,
|
||||
"groupStatus": "enabled"
|
||||
});
|
||||
awscurl_put(&update_members_url, &remove_member_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/update-group-members",
|
||||
Some(remove_member_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Removed testuser1 from testgroup");
|
||||
|
||||
// 5. Delete the now-empty group — should succeed
|
||||
awscurl_delete(&delete_group_url, &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(&env, http::Method::DELETE, "/rustfs/admin/v3/group/testgroup", None).await?;
|
||||
info!("Deleted empty testgroup successfully");
|
||||
|
||||
// 6. Verify the group no longer exists
|
||||
let get_group_url = format!("{}/rustfs/admin/v3/group?group=testgroup", env.url);
|
||||
let get_result = awscurl_get(&get_group_url, &env.access_key, &env.secret_key).await;
|
||||
assert!(get_result.is_err(), "group should no longer exist after deletion");
|
||||
let (get_status, get_body) = admin_request(
|
||||
&env.url,
|
||||
http::Method::GET,
|
||||
"/rustfs/admin/v3/group?group=testgroup",
|
||||
None,
|
||||
&env.access_key,
|
||||
&env.secret_key,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
get_status,
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"a deleted group must return HTTP 404, body: {get_body}"
|
||||
);
|
||||
assert!(
|
||||
get_body.contains("<Code>NoSuchResource</Code>"),
|
||||
"a deleted group must return NoSuchResource, body: {get_body}"
|
||||
);
|
||||
assert!(
|
||||
get_body.contains("<Message>group 'testgroup' does not exist</Message>"),
|
||||
"a deleted group returned an unexpected message: {get_body}"
|
||||
);
|
||||
info!("Confirmed testgroup no longer exists");
|
||||
|
||||
Ok(())
|
||||
@@ -142,7 +195,6 @@ async fn test_delete_group_requires_empty_membership() -> Result<(), Box<dyn std
|
||||
/// Test that a user with only group membership (no explicit user policy) gets group policies
|
||||
/// and can perform actions allowed by the group (regression test for #2028.1).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires awscurl and spawns a real RustFS server"]
|
||||
async fn test_user_with_only_group_gets_group_policies() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
|
||||
@@ -160,39 +212,56 @@ async fn test_user_with_only_group_gets_group_policies() -> Result<(), Box<dyn s
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListAllMyBuckets"],
|
||||
"Resource": ["*"]
|
||||
"Resource": ["arn:aws:s3:::*"]
|
||||
}]
|
||||
});
|
||||
let add_policy_url = format!("{}/rustfs/admin/v3/add-canned-policy?name={}", env.url, policy_name);
|
||||
awscurl_put(&add_policy_url, &policy_doc.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-canned-policy?name={policy_name}"),
|
||||
Some(policy_doc.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Created canned policy {}", policy_name);
|
||||
|
||||
// 2. Create user with no explicit policy
|
||||
let add_user_url = format!("{}/rustfs/admin/v3/add-user?accessKey={}", env.url, user_name);
|
||||
let user_body = serde_json::json!({
|
||||
"secretKey": user_secret,
|
||||
"status": "enabled"
|
||||
});
|
||||
awscurl_put(&add_user_url, &user_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-user?accessKey={user_name}"),
|
||||
Some(user_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Created user {} with no explicit policy", user_name);
|
||||
|
||||
// 3. Add user to group (creates group with this member; user_group_memberships must be updated)
|
||||
let update_members_url = format!("{}/rustfs/admin/v3/update-group-members", env.url);
|
||||
let add_member_body = serde_json::json!({
|
||||
"group": group_name,
|
||||
"members": [user_name],
|
||||
"isRemove": false,
|
||||
"groupStatus": "enabled"
|
||||
});
|
||||
awscurl_put(&update_members_url, &add_member_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/update-group-members",
|
||||
Some(add_member_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Added {} to group {}", user_name, group_name);
|
||||
|
||||
// 4. Attach policy to group
|
||||
let set_policy_url = format!(
|
||||
"{}/rustfs/admin/v3/set-user-or-group-policy?policyName={}&userOrGroup={}&isGroup=true",
|
||||
env.url, policy_name, group_name
|
||||
);
|
||||
awscurl_put(&set_policy_url, "", &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/set-user-or-group-policy?policyName={policy_name}&userOrGroup={group_name}&isGroup=true"),
|
||||
Some(String::new()),
|
||||
)
|
||||
.await?;
|
||||
info!("Attached policy {} to group {}", policy_name, group_name);
|
||||
|
||||
// 5. User with only group (no user policy) should be able to list buckets
|
||||
@@ -209,7 +278,6 @@ async fn test_user_with_only_group_gets_group_policies() -> Result<(), Box<dyn s
|
||||
/// Test that after deleting a user who was the only member of a group, the group can be deleted
|
||||
/// (regression test for #2028.2: delete group uses backend membership, not stale cache).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires awscurl and spawns a real RustFS server"]
|
||||
async fn test_delete_group_after_deleting_user() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
|
||||
@@ -221,33 +289,47 @@ async fn test_delete_group_after_deleting_user() -> Result<(), Box<dyn std::erro
|
||||
let group_name = "soledeletegroup";
|
||||
|
||||
// 1. Create user
|
||||
let add_user_url = format!("{}/rustfs/admin/v3/add-user?accessKey={}", env.url, user_name);
|
||||
let user_body = serde_json::json!({
|
||||
"secretKey": user_secret,
|
||||
"status": "enabled"
|
||||
});
|
||||
awscurl_put(&add_user_url, &user_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
&format!("/rustfs/admin/v3/add-user?accessKey={user_name}"),
|
||||
Some(user_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Created user {}", user_name);
|
||||
|
||||
// 2. Add user to group
|
||||
let update_members_url = format!("{}/rustfs/admin/v3/update-group-members", env.url);
|
||||
let add_member_body = serde_json::json!({
|
||||
"group": group_name,
|
||||
"members": [user_name],
|
||||
"isRemove": false,
|
||||
"groupStatus": "enabled"
|
||||
});
|
||||
awscurl_put(&update_members_url, &add_member_body.to_string(), &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::PUT,
|
||||
"/rustfs/admin/v3/update-group-members",
|
||||
Some(add_member_body.to_string()),
|
||||
)
|
||||
.await?;
|
||||
info!("Added {} to group {}", user_name, group_name);
|
||||
|
||||
// 3. Delete the user (backend and cache update so group membership becomes empty)
|
||||
let remove_user_url = format!("{}/rustfs/admin/v3/remove-user?accessKey={}", env.url, user_name);
|
||||
awscurl_delete(&remove_user_url, &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(
|
||||
&env,
|
||||
http::Method::DELETE,
|
||||
&format!("/rustfs/admin/v3/remove-user?accessKey={user_name}"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
info!("Deleted user {}", user_name);
|
||||
|
||||
// 4. Deleting the group should succeed (backend has empty members; no stale cache)
|
||||
let delete_group_url = format!("{}/rustfs/admin/v3/group/{}", env.url, group_name);
|
||||
awscurl_delete(&delete_group_url, &env.access_key, &env.secret_key).await?;
|
||||
admin_ok(&env, http::Method::DELETE, &format!("/rustfs/admin/v3/group/{group_name}"), None).await?;
|
||||
info!("Deleted group {} after user was removed", group_name);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -784,6 +784,24 @@ pub(crate) fn create_deferred_bitrot_reader_with_stripe_handle(
|
||||
///
|
||||
/// # Returns
|
||||
/// A Result containing the BitrotWriterWrapper or an error
|
||||
/// Size hint handed to `DiskAPI::create_file` for a bitrot-wrapped shard.
|
||||
///
|
||||
/// A known length is grown by one checksum per shard so the on-disk file size
|
||||
/// matches what the bitrot writer emits. A negative length is the
|
||||
/// unknown-size sentinel (`HashReader::SIZE_PRESERVE_LAYER`, used by SSE and
|
||||
/// compression) and must be preserved: `RemoteDisk::create_file` forwards it
|
||||
/// in the `put_file_stream` query, and the receiver only treats `size > 0` as
|
||||
/// a fixed body length when locating the authenticated trailer. Clamping it
|
||||
/// to `0` would claim an empty body and misframe the stream. `0` stays `0`
|
||||
/// because a genuinely empty object still means an empty body.
|
||||
fn bitrot_create_file_size(length: i64, shard_size: usize, checksum_algo: &HashAlgorithm) -> i64 {
|
||||
if length <= 0 {
|
||||
return length;
|
||||
}
|
||||
let length = length as usize;
|
||||
(length.div_ceil(shard_size) * checksum_algo.size() + length) as i64
|
||||
}
|
||||
|
||||
pub async fn create_bitrot_writer(
|
||||
is_inline_buffer: bool,
|
||||
disk: Option<&DiskStore>,
|
||||
@@ -796,12 +814,7 @@ pub async fn create_bitrot_writer(
|
||||
let writer = if is_inline_buffer {
|
||||
CustomWriter::new_inline_buffer()
|
||||
} else if let Some(disk) = disk {
|
||||
let length = if length > 0 {
|
||||
let length = length as usize;
|
||||
(length.div_ceil(shard_size) * checksum_algo.size() + length) as i64
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let length = bitrot_create_file_size(length, shard_size, &checksum_algo);
|
||||
|
||||
let file = disk.create_file("", volume, path, length).await?;
|
||||
#[cfg(feature = "hotpath")]
|
||||
@@ -820,6 +833,25 @@ mod tests {
|
||||
use rustfs_rio::ChunkReader;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[test]
|
||||
fn bitrot_create_file_size_grows_known_length_by_checksums() {
|
||||
// 10 bytes over 4-byte shards = 3 shards, each followed by a 32-byte hash.
|
||||
assert_eq!(bitrot_create_file_size(10, 4, &HashAlgorithm::HighwayHash256), 10 + 3 * 32);
|
||||
assert_eq!(bitrot_create_file_size(10, 4, &HashAlgorithm::None), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrot_create_file_size_keeps_empty_and_unknown_distinct() {
|
||||
assert_eq!(bitrot_create_file_size(0, 4, &HashAlgorithm::HighwayHash256), 0);
|
||||
// SSE/compression streams advertise SIZE_PRESERVE_LAYER (-1); the remote
|
||||
// put_file_stream receiver relies on a non-positive size to parse the auth
|
||||
// trailer from the stream tail, so the sentinel must survive untouched.
|
||||
assert_eq!(
|
||||
bitrot_create_file_size(rustfs_rio::HashReader::SIZE_PRESERVE_LAYER, 4, &HashAlgorithm::HighwayHash256),
|
||||
rustfs_rio::HashReader::SIZE_PRESERVE_LAYER
|
||||
);
|
||||
}
|
||||
|
||||
struct TestChunkReader {
|
||||
chunks: VecDeque<Bytes>,
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use crate::heal::{
|
||||
progress::{HealProgress, HealStatistics},
|
||||
resume::{ReplacementPhase, ResumeGc, ResumeManager, ResumeState, ResumeUtils},
|
||||
resume::{ReplacementPhase, ResumeManager, ResumeState, ResumeUtils},
|
||||
storage::HealStorageAPI,
|
||||
task::{HealOptions, HealPriority, HealRequest, HealTask, HealTaskStatus, HealType, demote_to_debug_when},
|
||||
};
|
||||
@@ -53,11 +53,9 @@ const EVENT_HEAL_MAINLINE_THROTTLE: &str = "heal_mainline_throttle";
|
||||
const EVENT_HEAL_SCHEDULER_STATE: &str = "heal_scheduler_state";
|
||||
const EVENT_HEAL_QUEUE_STATE: &str = "heal_queue_state";
|
||||
const EVENT_HEAL_UNCLEAN_SHUTDOWN: &str = "heal_unclean_shutdown";
|
||||
const EVENT_HEAL_RESUME_GC: &str = "heal_resume_gc";
|
||||
const LEGACY_ROOT_HEAL_PATH: &str = ".";
|
||||
const MAX_RECOVERABLE_HEAL_RETRIES: u32 = 3;
|
||||
const MAX_RECOVERABLE_HEAL_RETRY_DELAY: Duration = Duration::from_secs(30);
|
||||
const RESUME_GC_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
|
||||
// Admission/scheduler outcomes for per-object requests (Object/Metadata/
|
||||
// ECDecode) log via demote_to_debug_when! — MRF, autoheal, and scanner
|
||||
@@ -1152,49 +1150,6 @@ impl HealManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start the bounded resume-state inspector. Destructive GC remains
|
||||
/// disabled until the durable owner/CAS contract from backlog#1927 is
|
||||
/// available; this task therefore cannot remove an active or stale file.
|
||||
async fn start_resume_gc(&self) {
|
||||
let cancel = self.cancel_token.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut gc_by_disk = HashMap::<String, ResumeGc>::new();
|
||||
let mut ticker = interval(RESUME_GC_INTERVAL);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
_ = ticker.tick() => {
|
||||
let disks = {
|
||||
let local_disk_map = local_disk_map_read().await;
|
||||
local_disk_map.values().flatten().cloned().collect::<Vec<_>>()
|
||||
};
|
||||
for disk in disks {
|
||||
let disk_key = disk.endpoint().to_string();
|
||||
let gc = gc_by_disk.entry(disk_key).or_default();
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
result = gc.inspect_disk(&disk) => {
|
||||
if let Err(error) = result {
|
||||
warn!(
|
||||
target: "rustfs::heal::manager",
|
||||
event = EVENT_HEAL_RESUME_GC,
|
||||
component = LOG_COMPONENT_HEAL,
|
||||
subsystem = LOG_SUBSYSTEM_MANAGER,
|
||||
state = "inspect_failed",
|
||||
endpoint = %disk.endpoint(),
|
||||
error = %error,
|
||||
"Heal resume GC inspection failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Create new HealManager
|
||||
pub fn new(storage: Arc<dyn HealStorageAPI>, config: Option<HealConfig>) -> Self {
|
||||
Self::new_with_workload_provider(storage, config, None)
|
||||
@@ -1260,9 +1215,6 @@ impl HealManager {
|
||||
// competing task for the same set.
|
||||
self.process_unclean_shutdown().await;
|
||||
|
||||
// Inspect resume artifacts in a bounded, fail-closed background task.
|
||||
self.start_resume_gc().await;
|
||||
|
||||
// start auto disk scanner to heal unformatted disks
|
||||
if self.config.read().await.enable_auto_heal {
|
||||
self.start_auto_disk_scanner().await?;
|
||||
|
||||
@@ -28,12 +28,10 @@ use super::{
|
||||
};
|
||||
|
||||
mod checkpoint;
|
||||
mod gc;
|
||||
mod replacement;
|
||||
mod utils;
|
||||
|
||||
pub use checkpoint::{CheckpointManager, ResumeCheckpoint};
|
||||
pub(crate) use gc::ResumeGc;
|
||||
pub(crate) use replacement::replacement_target_identities_match;
|
||||
use replacement::replacement_targets_match_identities;
|
||||
pub use replacement::{
|
||||
|
||||
@@ -1,666 +0,0 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Bounded inspection of heal resume artifacts.
|
||||
//!
|
||||
//! The durable owner/CAS and quarantine primitives belong to backlog #1927 and
|
||||
//! are not part of the current base revision. This module is therefore
|
||||
//! deliberately inspect-only. In particular, it must never turn an age check
|
||||
//! into a delete: ordinary heal writers still publish raw files on this base,
|
||||
//! so a GC-side compare-and-delete would not fence a concurrent claim.
|
||||
|
||||
use metrics::counter;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Component, Path},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
use super::super::{BUCKET_META_PREFIX, DiskError, DiskStore, RUSTFS_META_BUCKET, storage_api::owner::EcstoreDiskAPI};
|
||||
use super::{
|
||||
LEGACY_REPLACEMENT_RECOVERY_MARKER_FILE, REPLACEMENT_COMPLETION_PROOF_FILE, REPLACEMENT_INTENT_FILE,
|
||||
REPLACEMENT_INTENT_SEAL_FILE, RESUME_CHECKPOINT_FILE, RESUME_PROGRESS_FILE, RESUME_STATE_FILE, ResumeCheckpoint, ResumeState,
|
||||
checkpoint::CURRENT_CHECKPOINT_SCHEMA,
|
||||
};
|
||||
use crate::{Error, Result};
|
||||
|
||||
const DEFAULT_ENTRY_BUDGET: usize = 256;
|
||||
const DEFAULT_BYTE_BUDGET: usize = 4 * 1024 * 1024;
|
||||
const GC_METRIC: &str = "rustfs_heal_resume_gc_inspected_total";
|
||||
const GC_ERROR_METRIC: &str = "rustfs_heal_resume_gc_inspect_errors_total";
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ResumeGcConfig {
|
||||
/// Maximum number of directory entries considered in one disk pass.
|
||||
pub(crate) max_entries: usize,
|
||||
/// Maximum number of bytes read in one disk pass.
|
||||
pub(crate) max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for ResumeGcConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_entries: DEFAULT_ENTRY_BUDGET,
|
||||
max_bytes: DEFAULT_BYTE_BUDGET,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct ResumeGcReport {
|
||||
/// Directory entries visited (including malformed entries).
|
||||
pub(crate) inspected: usize,
|
||||
pub(crate) active_skipped: usize,
|
||||
pub(crate) orphaned: usize,
|
||||
/// Records that must be handed to #1927's quarantine owner.
|
||||
pub(crate) quarantine_required: usize,
|
||||
pub(crate) generation_skipped: usize,
|
||||
pub(crate) clock_skew: usize,
|
||||
pub(crate) read_errors: usize,
|
||||
pub(crate) retained: usize,
|
||||
/// True while #1927's durable claim/quarantine capability is unavailable.
|
||||
pub(crate) destructive_disabled: bool,
|
||||
pub(crate) budget_exhausted: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ResumeGc {
|
||||
config: ResumeGcConfig,
|
||||
/// Alternate the first namespace so a full ordinary page cannot starve
|
||||
/// replacement recovery when the list API has no continuation token.
|
||||
recovery_first: bool,
|
||||
}
|
||||
|
||||
impl ResumeGc {
|
||||
#[cfg(test)]
|
||||
fn with_config(config: ResumeGcConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
recovery_first: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inspect one bounded page from each resume namespace.
|
||||
///
|
||||
/// The caller owns scheduling and cancellation. A malformed or unreadable
|
||||
/// artifact is reported and retained so a later pass can retry it; no
|
||||
/// individual artifact error aborts the rest of the bounded page.
|
||||
pub(crate) async fn inspect_disk(&mut self, disk: &DiskStore) -> Result<ResumeGcReport> {
|
||||
let mut report = ResumeGcReport {
|
||||
destructive_disabled: true,
|
||||
..ResumeGcReport::default()
|
||||
};
|
||||
if self.config.max_entries == 0 || self.config.max_bytes == 0 {
|
||||
report.budget_exhausted = true;
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
let mut bytes_read = 0usize;
|
||||
let recovery_first = self.recovery_first;
|
||||
self.recovery_first = !self.recovery_first;
|
||||
if recovery_first {
|
||||
inspect_namespace(self.config, disk, &replacement_prefix(), true, now, &mut bytes_read, &mut report).await?;
|
||||
if !report.budget_exhausted {
|
||||
inspect_namespace(self.config, disk, BUCKET_META_PREFIX, false, now, &mut bytes_read, &mut report).await?;
|
||||
}
|
||||
} else {
|
||||
inspect_namespace(self.config, disk, BUCKET_META_PREFIX, false, now, &mut bytes_read, &mut report).await?;
|
||||
if !report.budget_exhausted {
|
||||
inspect_namespace(self.config, disk, &replacement_prefix(), true, now, &mut bytes_read, &mut report).await?;
|
||||
}
|
||||
}
|
||||
|
||||
counter!(GC_METRIC).increment(u64::try_from(report.inspected).unwrap_or(u64::MAX));
|
||||
counter!(GC_ERROR_METRIC).increment(u64::try_from(report.read_errors).unwrap_or(u64::MAX));
|
||||
Ok(report)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
struct ArtifactSet {
|
||||
state: bool,
|
||||
checkpoint: bool,
|
||||
progress: bool,
|
||||
replacement_intent: bool,
|
||||
proof: bool,
|
||||
seal: bool,
|
||||
legacy_marker: bool,
|
||||
temporary: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum ArtifactKind {
|
||||
State,
|
||||
Checkpoint,
|
||||
Progress,
|
||||
ReplacementIntent,
|
||||
Proof,
|
||||
Seal,
|
||||
LegacyMarker,
|
||||
}
|
||||
|
||||
impl ArtifactSet {
|
||||
fn add(&mut self, kind: ArtifactKind, temporary: bool) {
|
||||
self.temporary |= temporary;
|
||||
match kind {
|
||||
ArtifactKind::State => self.state = true,
|
||||
ArtifactKind::Checkpoint => self.checkpoint = true,
|
||||
ArtifactKind::Progress => self.progress = true,
|
||||
ArtifactKind::ReplacementIntent => self.replacement_intent = true,
|
||||
ArtifactKind::Proof => self.proof = true,
|
||||
ArtifactKind::Seal => self.seal = true,
|
||||
ArtifactKind::LegacyMarker => self.legacy_marker = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct InspectOptions {
|
||||
max_bytes: usize,
|
||||
now: u64,
|
||||
}
|
||||
|
||||
struct InspectProgress<'a> {
|
||||
bytes_read: &'a mut usize,
|
||||
report: &'a mut ResumeGcReport,
|
||||
}
|
||||
|
||||
fn replacement_prefix() -> String {
|
||||
super::replacement_recovery_dir().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
async fn inspect_namespace(
|
||||
config: ResumeGcConfig,
|
||||
disk: &DiskStore,
|
||||
prefix: &str,
|
||||
replacement: bool,
|
||||
now: u64,
|
||||
bytes_read: &mut usize,
|
||||
report: &mut ResumeGcReport,
|
||||
) -> Result<()> {
|
||||
let remaining = config.max_entries.saturating_sub(report.inspected);
|
||||
if remaining == 0 {
|
||||
report.budget_exhausted = true;
|
||||
return Ok(());
|
||||
}
|
||||
let count = i32::try_from(remaining).unwrap_or(i32::MAX);
|
||||
let mut entries = match EcstoreDiskAPI::list_dir(disk.as_ref(), "", RUSTFS_META_BUCKET, prefix, count).await {
|
||||
Ok(entries) => entries,
|
||||
Err(DiskError::FileNotFound | DiskError::VolumeNotFound) => return Ok(()),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
entries.sort_unstable();
|
||||
|
||||
let mut artifacts = BTreeMap::<String, ArtifactSet>::new();
|
||||
for entry in entries {
|
||||
if report.inspected >= config.max_entries {
|
||||
report.budget_exhausted = true;
|
||||
break;
|
||||
}
|
||||
report.inspected += 1;
|
||||
let Some((task_id, kind, temporary)) = artifact_name(&entry, replacement) else {
|
||||
report.quarantine_required += 1;
|
||||
report.retained += 1;
|
||||
continue;
|
||||
};
|
||||
artifacts.entry(task_id).or_default().add(kind, temporary);
|
||||
}
|
||||
if report.inspected >= config.max_entries {
|
||||
report.budget_exhausted = true;
|
||||
}
|
||||
|
||||
for (task_id, artifacts) in artifacts {
|
||||
if *bytes_read >= config.max_bytes {
|
||||
report.budget_exhausted = true;
|
||||
break;
|
||||
}
|
||||
let options = InspectOptions {
|
||||
max_bytes: config.max_bytes,
|
||||
now,
|
||||
};
|
||||
let mut progress = InspectProgress { bytes_read, report };
|
||||
inspect_task(options, disk, prefix, replacement, &task_id, artifacts, &mut progress).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn inspect_task(
|
||||
options: InspectOptions,
|
||||
disk: &DiskStore,
|
||||
prefix: &str,
|
||||
replacement: bool,
|
||||
task_id: &str,
|
||||
artifacts: ArtifactSet,
|
||||
progress: &mut InspectProgress<'_>,
|
||||
) -> Result<()> {
|
||||
let legacy_replacement = !replacement && !artifacts.state && artifacts.replacement_intent;
|
||||
let state_suffix = if replacement || legacy_replacement {
|
||||
REPLACEMENT_INTENT_FILE
|
||||
} else {
|
||||
RESUME_STATE_FILE
|
||||
};
|
||||
let state_path = artifact_path(prefix, task_id, state_suffix)?;
|
||||
let state = match read_bounded(disk, &state_path, options.max_bytes, progress.bytes_read).await {
|
||||
ReadOutcome::Missing => {
|
||||
progress.report.orphaned += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
ReadOutcome::TooLarge => {
|
||||
progress.report.quarantine_required += 1;
|
||||
progress.report.retained += 1;
|
||||
progress.report.budget_exhausted = true;
|
||||
return Ok(());
|
||||
}
|
||||
ReadOutcome::Error => {
|
||||
progress.report.read_errors += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
ReadOutcome::Bytes(bytes) => bytes,
|
||||
};
|
||||
|
||||
let parsed: ResumeState = match serde_json::from_slice(&state) {
|
||||
Ok(state) => state,
|
||||
Err(_) => {
|
||||
progress.report.quarantine_required += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if parsed.schema_version > super::CURRENT_RESUME_SCHEMA || parsed.task_id != task_id {
|
||||
progress.report.quarantine_required += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if persistent_age_seconds(options.now, parsed.last_update).is_none() {
|
||||
progress.report.clock_skew += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(generation) = parsed.replacement_generation.as_deref()
|
||||
&& !claim_generation_matches(Some(generation), Some(task_id))
|
||||
{
|
||||
progress.report.generation_skipped += 1;
|
||||
progress.report.retained += 1;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !replacement && artifacts.checkpoint {
|
||||
let checkpoint_path = artifact_path(prefix, task_id, RESUME_CHECKPOINT_FILE)?;
|
||||
match read_bounded(disk, &checkpoint_path, options.max_bytes, progress.bytes_read).await {
|
||||
ReadOutcome::Bytes(bytes) => match serde_json::from_slice::<ResumeCheckpoint>(&bytes) {
|
||||
Ok(checkpoint) if checkpoint.schema_version <= CURRENT_CHECKPOINT_SCHEMA && checkpoint.task_id == task_id => {}
|
||||
_ => {
|
||||
progress.report.quarantine_required += 1;
|
||||
progress.report.retained += 1;
|
||||
}
|
||||
},
|
||||
ReadOutcome::Missing => {
|
||||
progress.report.orphaned += 1;
|
||||
progress.report.retained += 1;
|
||||
}
|
||||
ReadOutcome::TooLarge => {
|
||||
progress.report.quarantine_required += 1;
|
||||
progress.report.retained += 1;
|
||||
progress.report.budget_exhausted = true;
|
||||
}
|
||||
ReadOutcome::Error => {
|
||||
progress.report.read_errors += 1;
|
||||
progress.report.retained += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if artifacts.state && artifacts.replacement_intent {
|
||||
// A task cannot have two authoritative state records in one namespace;
|
||||
// preserve both until the durable owner can resolve the generation.
|
||||
progress.report.quarantine_required += 1;
|
||||
}
|
||||
|
||||
if !parsed.completed {
|
||||
progress.report.active_skipped += 1;
|
||||
}
|
||||
// The state and all associated evidence remain recoverable until #1927
|
||||
// supplies a common generation/CAS transition and quarantine owner.
|
||||
progress.report.retained += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum ReadOutcome {
|
||||
Bytes(Vec<u8>),
|
||||
Missing,
|
||||
TooLarge,
|
||||
Error,
|
||||
}
|
||||
|
||||
async fn read_bounded(disk: &DiskStore, path: &str, max_bytes: usize, bytes_read: &mut usize) -> ReadOutcome {
|
||||
let remaining = max_bytes.saturating_sub(*bytes_read);
|
||||
if remaining == 0 {
|
||||
return ReadOutcome::TooLarge;
|
||||
}
|
||||
let read_len = remaining.saturating_add(1);
|
||||
let reader = match EcstoreDiskAPI::read_file(disk.as_ref(), RUSTFS_META_BUCKET, path).await {
|
||||
Ok(reader) => reader,
|
||||
Err(DiskError::FileNotFound | DiskError::VolumeNotFound) => return ReadOutcome::Missing,
|
||||
Err(_) => return ReadOutcome::Error,
|
||||
};
|
||||
let mut bytes = Vec::with_capacity(read_len.min(64 * 1024));
|
||||
let Ok(read_len) = u64::try_from(read_len) else {
|
||||
return ReadOutcome::TooLarge;
|
||||
};
|
||||
if reader.take(read_len).read_to_end(&mut bytes).await.is_err() {
|
||||
return ReadOutcome::Error;
|
||||
}
|
||||
if bytes.len() > remaining {
|
||||
*bytes_read = max_bytes;
|
||||
return ReadOutcome::TooLarge;
|
||||
}
|
||||
*bytes_read = bytes_read.saturating_add(bytes.len());
|
||||
ReadOutcome::Bytes(bytes)
|
||||
}
|
||||
|
||||
fn artifact_path(prefix: &str, task_id: &str, suffix: &str) -> Result<String> {
|
||||
if super::validate_resume_task_id(task_id).is_err() {
|
||||
return Err(Error::other("invalid resume task id"));
|
||||
}
|
||||
Path::new(prefix)
|
||||
.join(format!("{task_id}_{suffix}"))
|
||||
.to_str()
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| Error::other("invalid resume artifact path"))
|
||||
}
|
||||
|
||||
/// Parse one directory entry without ever accepting a path component supplied
|
||||
/// by a client. DiskAPI filters symlinks, but this check also protects remote
|
||||
/// implementations and future mutating callers from traversal/reparse names.
|
||||
fn artifact_name(entry: &str, replacement: bool) -> Option<(String, ArtifactKind, bool)> {
|
||||
let path = Path::new(entry);
|
||||
if entry.is_empty() || path.components().count() != 1 || !matches!(path.components().next(), Some(Component::Normal(_))) {
|
||||
return None;
|
||||
}
|
||||
let (stem, temporary) = entry
|
||||
.strip_suffix(".tmp")
|
||||
.map(|stem| (stem, true))
|
||||
.or_else(|| entry.strip_suffix(".bak").map(|stem| (stem, true)))
|
||||
.unwrap_or((entry, false));
|
||||
let suffixes: &[(&str, ArtifactKind)] = if replacement {
|
||||
&[
|
||||
(REPLACEMENT_INTENT_FILE, ArtifactKind::ReplacementIntent),
|
||||
(REPLACEMENT_COMPLETION_PROOF_FILE, ArtifactKind::Proof),
|
||||
(REPLACEMENT_INTENT_SEAL_FILE, ArtifactKind::Seal),
|
||||
]
|
||||
} else {
|
||||
&[
|
||||
(RESUME_STATE_FILE, ArtifactKind::State),
|
||||
(RESUME_CHECKPOINT_FILE, ArtifactKind::Checkpoint),
|
||||
(RESUME_PROGRESS_FILE, ArtifactKind::Progress),
|
||||
(LEGACY_REPLACEMENT_RECOVERY_MARKER_FILE, ArtifactKind::LegacyMarker),
|
||||
(REPLACEMENT_INTENT_FILE, ArtifactKind::ReplacementIntent),
|
||||
(REPLACEMENT_COMPLETION_PROOF_FILE, ArtifactKind::Proof),
|
||||
(REPLACEMENT_INTENT_SEAL_FILE, ArtifactKind::Seal),
|
||||
]
|
||||
};
|
||||
suffixes.iter().find_map(|(suffix, kind)| {
|
||||
stem.strip_suffix(&format!("_{suffix}"))
|
||||
.filter(|task_id| super::validate_resume_task_id(task_id).is_ok())
|
||||
.map(|task_id| (task_id.to_string(), *kind, temporary))
|
||||
})
|
||||
}
|
||||
|
||||
fn persistent_age_seconds(now: u64, updated: u64) -> Option<u64> {
|
||||
now.checked_sub(updated)
|
||||
}
|
||||
|
||||
fn claim_generation_matches(observed: Option<&str>, expected: Option<&str>) -> bool {
|
||||
expected.is_none() || observed == expected
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::heal::{DiskOption, Endpoint, new_disk};
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
async fn test_disk() -> (TempDir, DiskStore) {
|
||||
let temp = TempDir::new().expect("test disk directory");
|
||||
let endpoint = Endpoint::try_from(temp.path().to_string_lossy().as_ref()).expect("test endpoint");
|
||||
let disk = new_disk(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("test disk");
|
||||
match disk.make_volume(RUSTFS_META_BUCKET).await {
|
||||
Ok(()) | Err(DiskError::VolumeExists) => {}
|
||||
Err(error) => panic!("metadata volume: {error}"),
|
||||
}
|
||||
match disk.make_volume(&format!("{RUSTFS_META_BUCKET}/{BUCKET_META_PREFIX}")).await {
|
||||
Ok(()) | Err(DiskError::VolumeExists) => {}
|
||||
Err(error) => panic!("resume volume: {error}"),
|
||||
}
|
||||
(temp, disk)
|
||||
}
|
||||
|
||||
async fn write_state(disk: &DiskStore, state: &ResumeState) {
|
||||
let path = format!("{BUCKET_META_PREFIX}/{}_{}", state.task_id, RESUME_STATE_FILE);
|
||||
disk.write_all(RUSTFS_META_BUCKET, &path, serde_json::to_vec(state).unwrap().into())
|
||||
.await
|
||||
.expect("resume state");
|
||||
}
|
||||
|
||||
async fn write_replacement_state(disk: &DiskStore, state: &ResumeState) {
|
||||
let volume = format!("{RUSTFS_META_BUCKET}/{BUCKET_META_PREFIX}/ahm-replacement");
|
||||
match disk.make_volume(&volume).await {
|
||||
Ok(()) | Err(DiskError::VolumeExists) => {}
|
||||
Err(error) => panic!("replacement volume: {error}"),
|
||||
}
|
||||
let path = format!("{}/{}_{}", replacement_prefix(), state.task_id, REPLACEMENT_INTENT_FILE);
|
||||
disk.write_all(RUSTFS_META_BUCKET, &path, serde_json::to_vec(state).unwrap().into())
|
||||
.await
|
||||
.expect("replacement state");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_does_not_delete_claimed_resume_state() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
write_state(&disk, &ResumeState::new(task_id.clone(), "set".into(), "disk".into(), vec![])).await;
|
||||
let report = ResumeGc::default().inspect_disk(&disk).await.expect("inspect");
|
||||
assert_eq!(report.active_skipped, 1);
|
||||
assert!(
|
||||
disk.read_all(RUSTFS_META_BUCKET, &format!("{BUCKET_META_PREFIX}/{task_id}_{RESUME_STATE_FILE}"))
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_generation_mismatch_is_skip() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let mut state = ResumeState::new(task_id.clone(), "set".into(), "disk".into(), vec![]);
|
||||
state.replacement_generation = Some(Uuid::new_v4().to_string());
|
||||
write_state(&disk, &state).await;
|
||||
assert_eq!(ResumeGc::default().inspect_disk(&disk).await.unwrap().generation_skipped, 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn production_gc_rejects_symlink_or_outside_prefix() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let root = EcstoreDiskAPI::path(disk.as_ref());
|
||||
let outside = root.join("outside-resume-state");
|
||||
std::fs::write(&outside, b"must remain").expect("outside fixture");
|
||||
let symlink = root
|
||||
.join(RUSTFS_META_BUCKET)
|
||||
.join(BUCKET_META_PREFIX)
|
||||
.join(format!("{id}_{RESUME_STATE_FILE}"));
|
||||
std::os::unix::fs::symlink(&outside, &symlink).expect("symlink fixture");
|
||||
let report = ResumeGc::default().inspect_disk(&disk).await.expect("inspect");
|
||||
assert_eq!(report.inspected, 0, "symlinks are not eligible artifacts");
|
||||
assert!(outside.exists());
|
||||
assert!(artifact_name(&format!("{id}_{RESUME_STATE_FILE}"), false).is_some());
|
||||
assert!(artifact_name(&format!("../{id}_{RESUME_STATE_FILE}"), false).is_none());
|
||||
assert!(artifact_name(&format!("{id}/link_{RESUME_STATE_FILE}"), false).is_none());
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn production_gc_rejects_symlink_or_outside_prefix() {
|
||||
let id = Uuid::new_v4().to_string();
|
||||
assert!(artifact_name(&format!("{id}_{RESUME_STATE_FILE}"), false).is_some());
|
||||
assert!(artifact_name(&format!("../{id}_{RESUME_STATE_FILE}"), false).is_none());
|
||||
assert!(artifact_name(&format!("{id}/link_{RESUME_STATE_FILE}"), false).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_delete_failure_leaves_recoverable_state() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let mut state = ResumeState::new(task_id.clone(), "set".into(), "disk".into(), vec![]);
|
||||
state.mark_completed();
|
||||
write_state(&disk, &state).await;
|
||||
ResumeGc::default().inspect_disk(&disk).await.expect("inspect");
|
||||
assert!(
|
||||
disk.read_all(RUSTFS_META_BUCKET, &format!("{BUCKET_META_PREFIX}/{task_id}_{RESUME_STATE_FILE}"))
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_handles_clock_skew_and_restart() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let mut state = ResumeState::new(task_id, "set".into(), "disk".into(), vec![]);
|
||||
state.last_update = u64::MAX;
|
||||
write_state(&disk, &state).await;
|
||||
assert_eq!(ResumeGc::default().inspect_disk(&disk).await.unwrap().clock_skew, 1);
|
||||
assert!(persistent_age_seconds(1, 2).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_100k_states_respects_budget() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
for _ in 0..8 {
|
||||
let state = ResumeState::new(Uuid::new_v4().to_string(), "set".into(), "disk".into(), vec![]);
|
||||
write_state(&disk, &state).await;
|
||||
}
|
||||
let config = ResumeGcConfig {
|
||||
max_entries: 2,
|
||||
max_bytes: usize::MAX,
|
||||
};
|
||||
let report = ResumeGc::with_config(config).inspect_disk(&disk).await.unwrap();
|
||||
assert!(report.inspected <= 2);
|
||||
assert!(report.budget_exhausted);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_recovery_namespace_is_not_starved() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let ordinary = ResumeState::new(Uuid::new_v4().to_string(), "set".into(), "disk".into(), vec![]);
|
||||
write_state(&disk, &ordinary).await;
|
||||
let replacement_id = Uuid::new_v4().to_string();
|
||||
let mut replacement = ResumeState::new(replacement_id, "set".into(), "disk".into(), vec![]);
|
||||
replacement.replacement_generation = Some(replacement.task_id.clone());
|
||||
write_replacement_state(&disk, &replacement).await;
|
||||
|
||||
let mut gc = ResumeGc::with_config(ResumeGcConfig {
|
||||
max_entries: 1,
|
||||
max_bytes: usize::MAX,
|
||||
});
|
||||
assert_eq!(gc.inspect_disk(&disk).await.unwrap().inspected, 1);
|
||||
let second = gc.inspect_disk(&disk).await.unwrap();
|
||||
assert_eq!(second.inspected, 1, "the next bounded pass must start at recovery");
|
||||
assert_eq!(second.active_skipped, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_pairs_orphan_checkpoint_and_resume() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let checkpoint = ResumeCheckpoint::new(task_id.clone());
|
||||
let path = format!("{BUCKET_META_PREFIX}/{task_id}_{RESUME_CHECKPOINT_FILE}");
|
||||
disk.write_all(RUSTFS_META_BUCKET, &path, serde_json::to_vec(&checkpoint).unwrap().into())
|
||||
.await
|
||||
.expect("checkpoint");
|
||||
assert_eq!(ResumeGc::default().inspect_disk(&disk).await.unwrap().orphaned, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_does_not_delete_slow_active_task() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let mut state = ResumeState::new(task_id, "set".into(), "disk".into(), vec![]);
|
||||
state.last_update = 1;
|
||||
write_state(&disk, &state).await;
|
||||
assert_eq!(ResumeGc::default().inspect_disk(&disk).await.unwrap().active_skipped, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_disables_on_mixed_version_capability() {
|
||||
assert!(claim_generation_matches(None, None));
|
||||
assert!(!claim_generation_matches(Some("new"), Some("old")));
|
||||
// No #1927 capability means this implementation has no delete path.
|
||||
assert!(ResumeGcConfig::default().max_entries > 0);
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let report = ResumeGc::default().inspect_disk(&disk).await.expect("inspect");
|
||||
assert!(report.destructive_disabled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_future_schema_is_not_mtime_deleted() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let mut state = ResumeState::new(task_id.clone(), "set".into(), "disk".into(), vec![]);
|
||||
state.schema_version = super::super::CURRENT_RESUME_SCHEMA + 1;
|
||||
write_state(&disk, &state).await;
|
||||
let report = ResumeGc::default().inspect_disk(&disk).await.unwrap();
|
||||
assert_eq!(report.quarantine_required, 1);
|
||||
assert!(
|
||||
disk.read_all(RUSTFS_META_BUCKET, &format!("{BUCKET_META_PREFIX}/{task_id}_{RESUME_STATE_FILE}"))
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn production_gc_quarantine_cleanup_is_bounded() {
|
||||
let (_temp, disk) = test_disk().await;
|
||||
for _ in 0..4 {
|
||||
let task_id = Uuid::new_v4().to_string();
|
||||
let path = format!("{BUCKET_META_PREFIX}/{task_id}_{RESUME_STATE_FILE}");
|
||||
disk.write_all(RUSTFS_META_BUCKET, &path, b"corrupt".to_vec().into())
|
||||
.await
|
||||
.expect("corrupt state");
|
||||
}
|
||||
let report = ResumeGc::with_config(ResumeGcConfig {
|
||||
max_entries: 2,
|
||||
max_bytes: 1024,
|
||||
})
|
||||
.inspect_disk(&disk)
|
||||
.await
|
||||
.expect("inspect");
|
||||
assert!(report.quarantine_required <= 2);
|
||||
assert!(report.budget_exhausted);
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,14 @@
|
||||
//!
|
||||
//! `scripts/test/vault_ha_kms_live.sh` owns the official Vault containers and
|
||||
//! kills the active node while this test continuously decrypts through a
|
||||
//! surviving standby. KV2 and Transit requests must remain successful, use a
|
||||
//! bounded number of attempts, and leave the circuit and in-flight gauges at
|
||||
//! zero after a new leader is elected.
|
||||
//! surviving standby. KV2 and Transit must recover after the bounded circuit
|
||||
//! interval, use a bounded number of attempts, and leave the circuit and
|
||||
//! in-flight gauges at zero after a new leader is elected.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use metrics_util::MetricKind;
|
||||
@@ -43,6 +43,11 @@ const OPERATION_ATTEMPTS: &str = "rustfs_kms_backend_operation_attempts";
|
||||
const IN_FLIGHT: &str = "rustfs_kms_backend_in_flight";
|
||||
const CIRCUIT_OPEN: &str = "rustfs_kms_backend_circuit_open";
|
||||
const MAX_ATTEMPTS: u32 = 10;
|
||||
const ATTEMPT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const HEALTHY_PROGRESS_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
// The circuit remains open for 30s after five failed attempts.
|
||||
const POST_FAILOVER_PROGRESS_TIMEOUT: Duration = Duration::from_secs(35);
|
||||
const FAILOVER_ERROR_POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
type MetricEntry = (
|
||||
metrics_util::CompositeKey,
|
||||
@@ -64,7 +69,7 @@ fn config(backend: KmsBackend, backend_config: BackendConfig) -> KmsConfig {
|
||||
backend,
|
||||
backend_config,
|
||||
allow_insecure_dev_defaults: true,
|
||||
timeout: Duration::from_secs(2),
|
||||
timeout: ATTEMPT_TIMEOUT,
|
||||
retry_attempts: MAX_ATTEMPTS,
|
||||
enable_cache: false,
|
||||
..KmsConfig::default()
|
||||
@@ -164,14 +169,31 @@ fn retryable_failures(snapshot: &[MetricEntry], operation: &str) -> u64 {
|
||||
.sum()
|
||||
}
|
||||
|
||||
async fn wait_for_count(counter: &AtomicU64, minimum: u64, description: &str) {
|
||||
tokio::time::timeout(Duration::from_secs(20), async {
|
||||
async fn wait_for_count(
|
||||
counter: &AtomicU64,
|
||||
failure: &Mutex<Option<String>>,
|
||||
minimum: u64,
|
||||
description: &str,
|
||||
timeout: Duration,
|
||||
) {
|
||||
tokio::time::timeout(timeout, async {
|
||||
while counter.load(Ordering::SeqCst) < minimum {
|
||||
if let Some(error) = failure.lock().expect("decrypt failure lock poisoned").as_ref() {
|
||||
panic!(
|
||||
"{description} worker failed after {} successful decrypts: {error}",
|
||||
counter.load(Ordering::SeqCst)
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("timed out waiting for {description}"));
|
||||
.unwrap_or_else(|_| {
|
||||
panic!(
|
||||
"timed out after {timeout:?} waiting for {description}: completed {}, expected {minimum}",
|
||||
counter.load(Ordering::SeqCst)
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
async fn wait_for_file(path: &Path, description: &str) {
|
||||
@@ -189,7 +211,8 @@ async fn decrypt_loop<B: KmsBackendTrait + Send + Sync + 'static>(
|
||||
request: DecryptRequest,
|
||||
expected: Vec<u8>,
|
||||
completed: Arc<AtomicU64>,
|
||||
failed: Arc<AtomicBool>,
|
||||
allow_failover_errors: Arc<AtomicBool>,
|
||||
failure: Arc<Mutex<Option<String>>>,
|
||||
stop: CancellationToken,
|
||||
) {
|
||||
while !stop.is_cancelled() {
|
||||
@@ -197,8 +220,18 @@ async fn decrypt_loop<B: KmsBackendTrait + Send + Sync + 'static>(
|
||||
Ok(response) if response.plaintext == expected => {
|
||||
completed.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
Ok(_) | Err(_) => {
|
||||
failed.store(true, Ordering::SeqCst);
|
||||
Ok(_) => {
|
||||
*failure.lock().expect("decrypt failure lock poisoned") =
|
||||
Some("decrypt returned unexpected plaintext".to_string());
|
||||
return;
|
||||
}
|
||||
Err(rustfs_kms::KmsError::BackendError { .. } | rustfs_kms::KmsError::OperationTimedOut { .. })
|
||||
if allow_failover_errors.load(Ordering::SeqCst) =>
|
||||
{
|
||||
tokio::time::sleep(FAILOVER_ERROR_POLL_INTERVAL).await;
|
||||
}
|
||||
Err(error) => {
|
||||
*failure.lock().expect("decrypt failure lock poisoned") = Some(error.to_string());
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -296,7 +329,9 @@ async fn exercise_failover(snapshotter: &Snapshotter) {
|
||||
);
|
||||
|
||||
let stop = CancellationToken::new();
|
||||
let failed = Arc::new(AtomicBool::new(false));
|
||||
let allow_failover_errors = Arc::new(AtomicBool::new(false));
|
||||
let kv2_failure = Arc::new(Mutex::new(None));
|
||||
let transit_failure = Arc::new(Mutex::new(None));
|
||||
let kv2_completed = Arc::new(AtomicU64::new(0));
|
||||
let transit_completed = Arc::new(AtomicU64::new(0));
|
||||
let kv2_worker = tokio::spawn(decrypt_loop(
|
||||
@@ -304,7 +339,8 @@ async fn exercise_failover(snapshotter: &Snapshotter) {
|
||||
kv2_request,
|
||||
kv2_data_key.plaintext_key,
|
||||
Arc::clone(&kv2_completed),
|
||||
Arc::clone(&failed),
|
||||
Arc::clone(&allow_failover_errors),
|
||||
Arc::clone(&kv2_failure),
|
||||
stop.clone(),
|
||||
));
|
||||
let transit_worker = tokio::spawn(decrypt_loop(
|
||||
@@ -312,12 +348,21 @@ async fn exercise_failover(snapshotter: &Snapshotter) {
|
||||
transit_request,
|
||||
transit_data_key.plaintext_key,
|
||||
Arc::clone(&transit_completed),
|
||||
Arc::clone(&failed),
|
||||
Arc::clone(&allow_failover_errors),
|
||||
Arc::clone(&transit_failure),
|
||||
stop.clone(),
|
||||
));
|
||||
|
||||
wait_for_count(&kv2_completed, 2, "two healthy KV2 decrypts").await;
|
||||
wait_for_count(&transit_completed, 2, "two healthy Transit decrypts").await;
|
||||
wait_for_count(&kv2_completed, &kv2_failure, 2, "two healthy KV2 decrypts", HEALTHY_PROGRESS_TIMEOUT).await;
|
||||
wait_for_count(
|
||||
&transit_completed,
|
||||
&transit_failure,
|
||||
2,
|
||||
"two healthy Transit decrypts",
|
||||
HEALTHY_PROGRESS_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
allow_failover_errors.store(true, Ordering::SeqCst);
|
||||
std::fs::write(&marker, b"ready").expect("publish failover readiness marker");
|
||||
|
||||
wait_for_file(&elected, "the replacement Vault leader").await;
|
||||
@@ -326,18 +371,39 @@ async fn exercise_failover(snapshotter: &Snapshotter) {
|
||||
|
||||
let kv2_after_election = kv2_completed.load(Ordering::SeqCst) + 2;
|
||||
let transit_after_election = transit_completed.load(Ordering::SeqCst) + 2;
|
||||
wait_for_count(&kv2_completed, kv2_after_election, "post-failover KV2 decrypts").await;
|
||||
wait_for_count(&transit_completed, transit_after_election, "post-failover Transit decrypts").await;
|
||||
wait_for_count(
|
||||
&kv2_completed,
|
||||
&kv2_failure,
|
||||
kv2_after_election,
|
||||
"post-failover KV2 decrypts",
|
||||
POST_FAILOVER_PROGRESS_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
wait_for_count(
|
||||
&transit_completed,
|
||||
&transit_failure,
|
||||
transit_after_election,
|
||||
"post-failover Transit decrypts",
|
||||
POST_FAILOVER_PROGRESS_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
|
||||
stop.cancel();
|
||||
kv2_worker.await.expect("KV2 decrypt worker must join");
|
||||
transit_worker.await.expect("Transit decrypt worker must join");
|
||||
assert!(!failed.load(Ordering::SeqCst), "no decrypt may fail or return different plaintext");
|
||||
assert!(
|
||||
kv2_failure.lock().expect("KV2 failure lock poisoned").is_none(),
|
||||
"no KV2 decrypt may fail or return different plaintext"
|
||||
);
|
||||
assert!(
|
||||
transit_failure.lock().expect("Transit failure lock poisoned").is_none(),
|
||||
"no Transit decrypt may fail or return different plaintext"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a real three-node Vault Raft cluster; run scripts/test/vault_ha_kms_live.sh"]
|
||||
fn vault_raft_leader_failure_preserves_kv2_and_transit_decrypts() {
|
||||
fn vault_raft_leader_failure_recovers_kv2_and_transit_decrypts() {
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
metrics::with_local_recorder(&recorder, || {
|
||||
@@ -349,11 +415,6 @@ fn vault_raft_leader_failure_preserves_kv2_and_transit_decrypts() {
|
||||
});
|
||||
let snapshot = snapshotter.snapshot().into_vec();
|
||||
|
||||
assert_eq!(
|
||||
counter_value(&snapshot, OPERATIONS_TOTAL, &[("outcome", "circuit_open")]),
|
||||
0,
|
||||
"a bounded leader election must not open the circuit"
|
||||
);
|
||||
assert_eq!(
|
||||
counter_value(&snapshot, OPERATIONS_TOTAL, &[("outcome", "budget_exhausted")]),
|
||||
0,
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
| fault_proxy | 7 | |
|
||||
| get_codec_streaming_compat_test | 1 | |
|
||||
| get_stream_failure_observability_test | 1 | |
|
||||
| group_delete_test | 1 | |
|
||||
| group_delete_test | 4 | |
|
||||
| head_object_consistency_test | 1 | ✅ |
|
||||
| head_object_range_test | 1 | ✅ |
|
||||
| heal_erasure_disk_rebuild_test | 4 | 🌙 |
|
||||
@@ -99,4 +99,4 @@
|
||||
| tls_hot_reload_test | 1 | ✅ |
|
||||
| version_id_regression_test | 10 | ✅ |
|
||||
|
||||
**Total listed: 575 tests across 82 modules · PR smoke: 163 tests / 36 modules · merge/main full: 453 tests / 73 modules · nightly replication: 55 tests · nightly cluster faults: 28 tests / 7 modules · nightly protocols: 16 tests** · updated 2026-08-23.
|
||||
**Total listed: 578 tests across 82 modules · PR smoke: 163 tests / 36 modules · merge/main full: 456 tests / 73 modules · nightly replication: 55 tests · nightly cluster faults: 28 tests / 7 modules · nightly protocols: 16 tests** · updated 2026-08-23.
|
||||
|
||||
@@ -241,7 +241,7 @@ env \
|
||||
RUSTFS_TEST_VAULT_FAILOVER_MARKER="$MARKER" \
|
||||
RUSTFS_TEST_VAULT_OLD_LEADER="$OLD_LEADER" \
|
||||
cargo test -p rustfs-kms --test vault_ha_failover_live \
|
||||
vault_raft_leader_failure_preserves_kv2_and_transit_decrypts -- \
|
||||
vault_raft_leader_failure_recovers_kv2_and_transit_decrypts -- \
|
||||
--ignored --nocapture --test-threads=1 &
|
||||
TEST_PID=$!
|
||||
|
||||
|
||||
Reference in New Issue
Block a user