mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-23 04:39:04 +00:00
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| eb00b0f956 | |||
| 23a2c7d776 | |||
| 5f72209446 | |||
| 70237b30b5 | |||
| 6e26e4bed3 | |||
| 1deb589077 | |||
| 9559be02bc | |||
| 95cc94f27c |
@@ -325,8 +325,8 @@ slow-timeout = { period = "60s", terminate-after = 2, grace-period = "10s" }
|
||||
#
|
||||
# Wired by .github/workflows/e2e-replication-nightly.yml (schedule +
|
||||
# workflow_dispatch), which builds the rustfs binary once, installs awscurl so
|
||||
# the STS dual-node test actually exercises its path (it skips gracefully with
|
||||
# a visible log line when awscurl is absent), and routes scheduled failures
|
||||
# the STS dual-node test actually exercises its path (the test fails when
|
||||
# awscurl is absent), and routes scheduled failures
|
||||
# through .github/actions/schedule-failure-issue (ci-8). Explicit division of
|
||||
# labor with e2e-full: these tests run only in the consolidated nightly
|
||||
# workflow, not in the merge/main lane.
|
||||
|
||||
@@ -681,6 +681,19 @@ jobs:
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install awscurl
|
||||
run: |
|
||||
python3 -m pip install --user --upgrade pip "awscurl==0.44"
|
||||
echo "AWSCURL_PATH=$HOME/.local/bin/awscurl" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify awscurl
|
||||
run: test -x "$AWSCURL_PATH"
|
||||
|
||||
# Download after the cache restore so the freshly built binary from the
|
||||
# build job always wins over anything restored into target/debug.
|
||||
- name: Download debug binary
|
||||
@@ -803,6 +816,20 @@ jobs:
|
||||
- name: Verify awscurl
|
||||
run: test -x "$AWSCURL_PATH"
|
||||
|
||||
- name: Install mc
|
||||
env:
|
||||
MC_VERSION: RELEASE.2025-08-13T08-35-41Z
|
||||
MC_SHA256: 01f866e9c5f9b87c2b09116fa5d7c06695b106242d829a8bb32990c00312e891
|
||||
run: |
|
||||
MC_BINARY="mc.linux-amd64.${MC_VERSION}"
|
||||
curl -fsSLo "$RUNNER_TEMP/mc" "https://github.com/minio/mc/releases/download/${MC_VERSION}/${MC_BINARY}"
|
||||
echo "${MC_SHA256} $RUNNER_TEMP/mc" | sha256sum --check --status
|
||||
chmod +x "$RUNNER_TEMP/mc"
|
||||
echo "$RUNNER_TEMP" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Verify mc
|
||||
run: mc --version
|
||||
|
||||
- name: Install Vault
|
||||
run: |
|
||||
VAULT_VERSION="1.17.6"
|
||||
|
||||
@@ -75,11 +75,7 @@ jobs:
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# awscurl lets the STS dual-node test actually exercise its path. Without
|
||||
# it the test skips gracefully with a visible log line
|
||||
# (`awscurl_available()` in crates/e2e_test/src/common.rs), so the lane
|
||||
# still passes — installing it just upgrades that one test from skip to
|
||||
# real coverage.
|
||||
# The STS dual-node test requires awscurl and fails if it is unavailable.
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
|
||||
with:
|
||||
@@ -87,7 +83,7 @@ jobs:
|
||||
|
||||
- name: Install awscurl
|
||||
run: |
|
||||
python3 -m pip install --user --upgrade pip awscurl
|
||||
python3 -m pip install --user --upgrade pip "awscurl==0.44"
|
||||
echo "AWSCURL_PATH=$HOME/.local/bin/awscurl" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify awscurl
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -123,7 +123,7 @@ via `create_s3_client(idx)` / `create_all_clients()`. See
|
||||
| `find_available_port` | Random free port (isolation primitive) |
|
||||
| `rustfs_binary_path` / `_with_features` | Locate/build the binary; honors `RUSTFS_BUILD_FEATURES` |
|
||||
| `requested_rustfs_build_features` / `rustfs_build_feature_enabled` | Feature-gate a test to what the binary was built with |
|
||||
| `awscurl_available` + `execute_awscurl` / `awscurl_post` / `_get` / `_put` / `_delete` / `awscurl_post_sts_form_urlencoded` | Admin/STS API calls via `awscurl` (skip gracefully when absent) |
|
||||
| `execute_awscurl` / `awscurl_post` / `_get` / `_put` / `_delete` / `awscurl_post_sts_form_urlencoded` | Admin/STS API calls via `awscurl`; missing binaries are test failures |
|
||||
| `replication_fast_env` | Env vars that shrink replication timers (from repl-4); pass to `start_rustfs_server_with_env` |
|
||||
| `local_http_client` / `init_logging` | Loopback HTTP client; idempotent tracing init |
|
||||
| `RustFSTestClusterEnvironment` (`new`/`start`/`start_node`/`stop_node`/`create_all_clients`) | Multi-node harness |
|
||||
@@ -189,7 +189,7 @@ cargo nextest run --profile e2e-smoke -p e2e_test
|
||||
cargo nextest run --profile e2e-full -p e2e_test
|
||||
# Cluster fault nightly lane
|
||||
cargo nextest run --profile e2e-nightly -p e2e_test
|
||||
# Replication nightly lane; install awscurl so STS paths do not skip
|
||||
# Replication nightly lane; awscurl is required for STS paths
|
||||
cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
||||
# Fixed-port protocol nightly lane
|
||||
RUSTFS_BUILD_FEATURES=ftps,webdav,sftp \
|
||||
@@ -221,9 +221,8 @@ The `s3s-e2e` CI job selects a random `RUSTFS_TEST_PORT` (see the `e2e-tests`
|
||||
job) to dodge this; local single-node tests already use random ports, so a
|
||||
lingering orphan is usually the cause of a spurious bind failure.
|
||||
|
||||
**`awscurl` not found.** `awscurl`-dependent tests skip gracefully with a
|
||||
visible log line (`awscurl_available()`); install `awscurl` to actually run
|
||||
them.
|
||||
**`awscurl` not found.** `awscurl`-dependent tests fail closed with a process
|
||||
spawn error. Install the pinned CI version before running their profiles.
|
||||
|
||||
## Related
|
||||
|
||||
@@ -258,10 +257,9 @@ A test module may join the smoke filter only if every test in it is:
|
||||
2. **Single-node** — spawns its own server via
|
||||
`RustFSTestEnvironment`/`start_rustfs_server` on a random port with an
|
||||
isolated temp dir. No `RustFSTestClusterEnvironment`, no fixed ports.
|
||||
3. **Dependency-free** — no pre-started server at `localhost:9000`, no Vault,
|
||||
no fixed protocol ports. Tools that may be absent on the runner (e.g.
|
||||
`awscurl`) are acceptable only when the test skips gracefully with a
|
||||
visible log line (see `bucket_policy_check_test.rs`).
|
||||
3. **Hermetic dependencies** — no pre-started server at `localhost:9000`, no
|
||||
Vault, and no fixed protocol ports. Any required CLI must be pinned and
|
||||
installed by the workflow; a missing CLI must fail the test.
|
||||
4. **Not `#[ignore]`** — ignored tests are activation work (backlog#1149
|
||||
ci-13 / backlog#1148 ilm-3), not smoke candidates.
|
||||
|
||||
|
||||
@@ -52,10 +52,6 @@ fn create_user_client(env: &RustFSTestEnvironment, access_key: &str, secret_key:
|
||||
#[tokio::test]
|
||||
async fn test_bucket_policy_authenticated_user() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !crate::common::awscurl_available() {
|
||||
info!("Skipping test_bucket_policy_authenticated_user because awscurl is not available");
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting test_bucket_policy_authenticated_user...");
|
||||
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
|
||||
@@ -494,17 +494,6 @@ fn awscurl_binary_path() -> PathBuf {
|
||||
.unwrap_or_else(|| PathBuf::from("awscurl"))
|
||||
}
|
||||
|
||||
pub fn awscurl_available() -> bool {
|
||||
let path = awscurl_binary_path();
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
return path.is_file();
|
||||
}
|
||||
|
||||
std::env::var_os("PATH")
|
||||
.map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(&path).is_file()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
// Global initialization
|
||||
static INIT: Once = Once::new();
|
||||
|
||||
|
||||
@@ -16,9 +16,7 @@
|
||||
//! session policy** (`Policy` parameter) via `awscurl --service sts` with explicit
|
||||
//! `Content-Type: application/x-www-form-urlencoded` on `POST /`.
|
||||
|
||||
use crate::common::{
|
||||
RustFSTestEnvironment, awscurl_available, awscurl_delete, awscurl_post_sts_form_urlencoded, awscurl_put, init_logging,
|
||||
};
|
||||
use crate::common::{RustFSTestEnvironment, awscurl_delete, awscurl_post_sts_form_urlencoded, awscurl_put, init_logging};
|
||||
use aws_sdk_s3::config::{Credentials, Region};
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::{Delete, ObjectIdentifier, Tag, Tagging};
|
||||
@@ -175,11 +173,6 @@ async fn cleanup_bucket_and_object(admin: &Client, bucket: &str, key: &str) {
|
||||
#[tokio::test]
|
||||
async fn test_e2e_iam_policy_existing_object_tag_get_object() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !awscurl_available() {
|
||||
info!("Skipping test_e2e_iam_policy_existing_object_tag_get_object: awscurl not available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let suffix = Uuid::new_v4();
|
||||
let user = format!("e2eiamtag-{suffix}");
|
||||
let user_secret = "longSecretKeyForTest123!";
|
||||
@@ -233,11 +226,6 @@ async fn test_e2e_iam_policy_existing_object_tag_get_object() -> Result<(), Box<
|
||||
#[tokio::test]
|
||||
async fn test_e2e_bucket_policy_existing_object_tag_get_object() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !awscurl_available() {
|
||||
info!("Skipping test_e2e_bucket_policy_existing_object_tag_get_object: awscurl not available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let suffix = Uuid::new_v4();
|
||||
let user = format!("e2ebptag-{suffix}");
|
||||
let user_secret = "longSecretKeyForTest456!";
|
||||
@@ -294,11 +282,6 @@ async fn test_e2e_bucket_policy_existing_object_tag_get_object() -> Result<(), B
|
||||
#[tokio::test]
|
||||
async fn test_e2e_sts_assume_role_session_policy_existing_object_tag() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !awscurl_available() {
|
||||
info!("Skipping test_e2e_sts_assume_role_session_policy_existing_object_tag: awscurl not available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let suffix = Uuid::new_v4();
|
||||
let parent = format!("e2e-sts-par-{suffix}");
|
||||
let parent_secret = "longSecretKeyForParentSts99!";
|
||||
@@ -370,11 +353,6 @@ async fn test_e2e_sts_assume_role_session_policy_existing_object_tag() -> Result
|
||||
#[tokio::test]
|
||||
async fn test_e2e_sts_session_policy_delete_objects_object_prefix_only() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !awscurl_available() {
|
||||
info!("Skipping test_e2e_sts_session_policy_delete_objects_object_prefix_only: awscurl not available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let suffix = Uuid::new_v4();
|
||||
let parent = format!("e2e-sts-del-par-{suffix}");
|
||||
let parent_secret = "longSecretKeyForParentDelete99!";
|
||||
|
||||
@@ -22,9 +22,7 @@
|
||||
//! - KMS backend configuration (Local and Vault)
|
||||
//! - SSE encryption testing utilities
|
||||
|
||||
use crate::common::{
|
||||
RustFSTestEnvironment, awscurl_available, awscurl_get, awscurl_post, init_logging as common_init_logging, local_http_client,
|
||||
};
|
||||
use crate::common::{RustFSTestEnvironment, awscurl_get, awscurl_post, init_logging as common_init_logging, local_http_client};
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::ServerSideEncryption;
|
||||
@@ -59,15 +57,6 @@ pub fn init_logging() {
|
||||
// Additional KMS-specific logging configuration can be added here if needed
|
||||
}
|
||||
|
||||
pub fn skip_if_kms_admin_tool_unavailable(test_name: &str) -> bool {
|
||||
if awscurl_available() {
|
||||
return false;
|
||||
}
|
||||
|
||||
info!("Skipping {} because awscurl is not available in PATH", test_name);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn sse_customer_key_md5_base64(key: &str) -> String {
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(key.as_bytes());
|
||||
@@ -490,10 +479,6 @@ pub async fn test_kms_key_management(
|
||||
access_key: &str,
|
||||
secret_key: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
if skip_if_kms_admin_tool_unavailable("test_kms_key_management") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!("Testing KMS key management APIs");
|
||||
|
||||
// Test CreateKey
|
||||
|
||||
@@ -20,8 +20,7 @@
|
||||
//! - Complete encryption/decryption lifecycle
|
||||
|
||||
use super::common::{
|
||||
LocalKMSTestEnvironment, get_kms_status, skip_if_kms_admin_tool_unavailable, sse_customer_key_md5_base64,
|
||||
test_kms_key_management, test_sse_c_encryption,
|
||||
LocalKMSTestEnvironment, get_kms_status, sse_customer_key_md5_base64, test_kms_key_management, test_sse_c_encryption,
|
||||
};
|
||||
use crate::common::{TEST_BUCKET, init_logging};
|
||||
use tracing::{error, info};
|
||||
@@ -29,9 +28,6 @@ use tracing::{error, info};
|
||||
#[tokio::test]
|
||||
async fn test_local_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_local_kms_end_to_end") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Local KMS End-to-End Test");
|
||||
|
||||
// Create LocalKMS test environment
|
||||
|
||||
@@ -22,8 +22,8 @@ use crate::common::{TEST_BUCKET, init_logging};
|
||||
use tracing::{error, info};
|
||||
|
||||
use super::common::{
|
||||
VAULT_KEY_NAME, VaultTestEnvironment, get_kms_status, skip_if_kms_admin_tool_unavailable, sse_customer_key_md5_base64,
|
||||
start_kms, test_all_multipart_encryption_types, test_error_scenarios, test_kms_key_management, test_sse_c_encryption,
|
||||
VAULT_KEY_NAME, VaultTestEnvironment, get_kms_status, sse_customer_key_md5_base64, start_kms,
|
||||
test_all_multipart_encryption_types, test_error_scenarios, test_kms_key_management, test_sse_c_encryption,
|
||||
test_sse_kms_encryption, test_sse_s3_encryption,
|
||||
};
|
||||
|
||||
@@ -62,9 +62,6 @@ impl VaultKmsTestContext {
|
||||
#[tokio::test]
|
||||
async fn test_vault_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_end_to_end") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Vault KMS End-to-End Test with default key {}", VAULT_KEY_NAME);
|
||||
|
||||
let context = VaultKmsTestContext::new().await?;
|
||||
@@ -117,9 +114,6 @@ async fn test_vault_kms_end_to_end() -> Result<(), Box<dyn std::error::Error + S
|
||||
#[tokio::test]
|
||||
async fn test_vault_kms_key_isolation() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_isolation") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Vault KMS SSE-C key isolation test");
|
||||
|
||||
let context = VaultKmsTestContext::new().await?;
|
||||
@@ -203,9 +197,6 @@ async fn test_vault_kms_key_isolation() -> Result<(), Box<dyn std::error::Error
|
||||
#[tokio::test]
|
||||
async fn test_vault_kms_large_file() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_large_file") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Vault KMS large file SSE-S3 test");
|
||||
|
||||
let context = VaultKmsTestContext::new().await?;
|
||||
@@ -267,9 +258,6 @@ async fn test_vault_kms_large_file() -> Result<(), Box<dyn std::error::Error + S
|
||||
#[tokio::test]
|
||||
async fn test_vault_kms_multipart_upload() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_multipart_upload") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Vault KMS multipart upload encryption suite");
|
||||
|
||||
let context = VaultKmsTestContext::new().await?;
|
||||
@@ -297,9 +285,6 @@ async fn test_vault_kms_multipart_upload() -> Result<(), Box<dyn std::error::Err
|
||||
#[tokio::test]
|
||||
async fn test_vault_kms_key_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_if_kms_admin_tool_unavailable("test_vault_kms_key_operations") {
|
||||
return Ok(());
|
||||
}
|
||||
info!("Starting Vault KMS key operations test (CRUD)");
|
||||
|
||||
let context = VaultKmsTestContext::new().await?;
|
||||
|
||||
@@ -41,13 +41,6 @@ async fn create_issue_3107_fixture(root: &Path) -> TestResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mc_available() -> bool {
|
||||
Command::new("mc")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}
|
||||
|
||||
fn run_mc(args: &[&str]) -> TestResult {
|
||||
let output = Command::new("mc").args(args).output()?;
|
||||
if !output.status.success() {
|
||||
@@ -75,10 +68,7 @@ fn count_files(root: &Path) -> usize {
|
||||
async fn test_mc_mirror_small_bucket_completes_without_list_timeout() -> TestResult {
|
||||
crate::common::init_logging();
|
||||
info!("Starting issue #3107 mc mirror regression test");
|
||||
if !mc_available() {
|
||||
info!("Skipping issue #3107 mc mirror regression test because mc is not installed");
|
||||
return Ok(());
|
||||
}
|
||||
run_mc(&["--version"])?;
|
||||
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
env.start_rustfs_server(vec![]).await?;
|
||||
|
||||
@@ -4278,10 +4278,6 @@ async fn test_signed_put_object_extract_preserves_pax_metadata_and_version_id()
|
||||
async fn test_signed_put_object_extract_authorizes_each_pax_privilege_and_retention_conditions()
|
||||
-> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !crate::common::awscurl_available() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
env.start_rustfs_server(vec![]).await?;
|
||||
|
||||
|
||||
@@ -18,15 +18,6 @@ use http::{Method, StatusCode};
|
||||
use tokio::time::{Duration, sleep, timeout};
|
||||
use tracing::{debug, info};
|
||||
|
||||
fn skip_without_awscurl() -> bool {
|
||||
if crate::common::awscurl_available() {
|
||||
return false;
|
||||
}
|
||||
|
||||
info!("Skipping quota test because awscurl is not available");
|
||||
true
|
||||
}
|
||||
|
||||
/// Test environment setup for quota tests
|
||||
pub struct QuotaTestEnv {
|
||||
pub env: RustFSTestEnvironment,
|
||||
@@ -276,9 +267,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_basic_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
// Create test bucket
|
||||
@@ -320,9 +308,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_admission_aws_chunked_declared_encoding() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
env.create_bucket().await?;
|
||||
|
||||
@@ -371,9 +356,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_update_and_clear() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -406,9 +388,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_delete_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -442,9 +421,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_usage_tracking() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -480,9 +456,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_statistics() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -513,9 +486,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_check_api() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -553,9 +523,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_multiple_buckets() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
// Create two buckets in the same environment
|
||||
@@ -593,9 +560,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_error_handling() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -628,9 +592,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_http_endpoints() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -689,9 +650,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_normal_user_permissions() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
env.create_bucket().await?;
|
||||
|
||||
@@ -744,9 +702,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_copy_operations() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -789,9 +744,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_batch_delete() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
@@ -847,9 +799,6 @@ mod integration_tests {
|
||||
#[tokio::test]
|
||||
async fn test_quota_multipart_upload() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if skip_without_awscurl() {
|
||||
return Ok(());
|
||||
}
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
|
||||
env.create_bucket().await?;
|
||||
|
||||
@@ -13,9 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use crate::common::{
|
||||
RustFSTestEnvironment, admin_create_user, awscurl_available, awscurl_post_sts_form_urlencoded, init_logging,
|
||||
local_http_client, replication_fast_env, rustfs_binary_path, signed_request, signed_request_with_client,
|
||||
signed_request_with_session_token,
|
||||
RustFSTestEnvironment, admin_create_user, awscurl_post_sts_form_urlencoded, init_logging, local_http_client,
|
||||
replication_fast_env, rustfs_binary_path, signed_request, signed_request_with_client, signed_request_with_session_token,
|
||||
};
|
||||
use crate::fake_s3_target::{
|
||||
FAKE_ACCESS_KEY, FAKE_SECRET_KEY, FakeS3Target, FaultAction as FakeTargetFault, Operation as FakeTargetOperation,
|
||||
@@ -7281,11 +7280,6 @@ async fn test_site_replication_replicates_multiple_service_accounts_real_dual_no
|
||||
async fn test_site_replication_replicates_service_accounts_created_from_sts_session_real_dual_node() -> TestResult {
|
||||
init_logging();
|
||||
|
||||
if !awscurl_available() {
|
||||
eprintln!("Skipping STS site replication service-account test because awscurl is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut source_env = RustFSTestEnvironment::new().await?;
|
||||
source_env
|
||||
.start_rustfs_server_with_env(vec![], LOOPBACK_REPLICATION_TARGET_ENV)
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
//! - SSRF prevention (internal/private endpoints rejected for tiering)
|
||||
//! - Race condition handling (concurrent writes converge without corruption)
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, awscurl_available, awscurl_put, init_logging};
|
||||
use crate::common::{RustFSTestEnvironment, awscurl_put, init_logging};
|
||||
use aws_sdk_s3::error::ProvideErrorMetadata;
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart, Tag, Tagging};
|
||||
@@ -225,16 +225,11 @@ async fn test_concurrent_object_operations() -> Result<(), Box<dyn Error + Send
|
||||
/// outcome — the internal endpoint is not accepted — is asserted here.
|
||||
///
|
||||
/// The admin API is exercised via signed `awscurl` requests, matching the
|
||||
/// pattern used by the other admin-API E2E tests in this crate; the test is
|
||||
/// skipped when `awscurl` is not installed.
|
||||
/// pattern used by the other admin-API E2E tests in this crate. The full E2E
|
||||
/// lane installs and verifies the pinned `awscurl` prerequisite.
|
||||
#[tokio::test]
|
||||
async fn test_tiering_url_validation() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
init_logging();
|
||||
if !awscurl_available() {
|
||||
info!("Skipping tiering URL validation test because awscurl is not available");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
env.start_rustfs_server(vec![]).await?;
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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