diff --git a/.github/actions/setup-self-hosted/action.yml b/.github/actions/setup-self-hosted/action.yml index 543bd13f..4624d8ea 100644 --- a/.github/actions/setup-self-hosted/action.yml +++ b/.github/actions/setup-self-hosted/action.yml @@ -50,6 +50,9 @@ runs: add_pkg() { local pkg="$1" local existing + if [[ "$(dpkg-query -W -f='${Status}' "${pkg}" 2>/dev/null || true)" == "install ok installed" ]]; then + return + fi if ((${#packages[@]} > 0)); then for existing in "${packages[@]}"; do if [[ "${existing}" == "${pkg}" ]]; then @@ -109,9 +112,56 @@ runs: add_pkg unzip fi + apt_tmp="" + trap '[[ -z "${apt_tmp}" ]] || sudo rm -rf "${apt_tmp}"' EXIT + prepare_apt() { + if [[ -n "${apt_tmp}" ]]; then return; fi + apt_tmp="$(mktemp -d)" + chmod 755 "${apt_tmp}" + mkdir -p "${apt_tmp}/lists/partial" + . /etc/os-release + case "${ID}" in + ubuntu) + case "$(dpkg --print-architecture)" in + amd64) + apt_archive="http://archive.ubuntu.com/ubuntu" + apt_security="http://security.ubuntu.com/ubuntu" + ;; + arm64) + apt_archive="http://ports.ubuntu.com/ubuntu-ports" + apt_security="${apt_archive}" + ;; + *) echo "Unsupported Ubuntu architecture" >&2; exit 1 ;; + esac + apt_keyring="/usr/share/keyrings/ubuntu-archive-keyring.gpg" + apt_components="main universe" + ;; + debian) + apt_archive="http://deb.debian.org/debian" + apt_security="http://security.debian.org/debian-security" + apt_keyring="/usr/share/keyrings/debian-archive-keyring.gpg" + apt_components="main" + ;; + *) echo "Unsupported APT distribution: ${ID}" >&2; exit 1 ;; + esac + : "${VERSION_CODENAME:?Distribution codename is required}" + [[ -f "${apt_keyring}" ]] || { echo "Distribution signing keyring is missing" >&2; exit 1; } + { + echo "deb [signed-by=${apt_keyring}] ${apt_archive} ${VERSION_CODENAME} ${apt_components}" + echo "deb [signed-by=${apt_keyring}] ${apt_archive} ${VERSION_CODENAME}-updates ${apt_components}" + echo "deb [signed-by=${apt_keyring}] ${apt_security} ${VERSION_CODENAME}-security ${apt_components}" + } > "${apt_tmp}/sources.list" + # The runner's unrelated PPAs must not gate basic build tools or + # contribute higher-priority packages to this installation. + apt_options=(-o "Dir::Etc::sourcelist=${apt_tmp}/sources.list" + -o Dir::Etc::sourceparts=- -o "Dir::State::lists=${apt_tmp}/lists" + -o APT::Update::Error-Mode=any -o Acquire::Retries=3) + } + if ((${#packages[@]} > 0)); then - sudo DEBIAN_FRONTEND=noninteractive apt-get update - sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "${packages[@]}" + prepare_apt + sudo DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" update + sudo DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" install --no-upgrade -y "${packages[@]}" fi if has awscli && ! command -v aws >/dev/null 2>&1; then @@ -133,12 +183,12 @@ runs: if has github-cli && ! command -v gh >/dev/null 2>&1; then # Ubuntu's own gh package is not always present on the minimal # runner image. Use the upstream GitHub CLI apt repository. - sudo mkdir -p -m 755 /etc/apt/keyrings + prepare_apt curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \ - | sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg >/dev/null - sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg - echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \ - | sudo tee /etc/apt/sources.list.d/github-cli.list >/dev/null - sudo DEBIAN_FRONTEND=noninteractive apt-get update - sudo DEBIAN_FRONTEND=noninteractive apt-get install -y gh + > "${apt_tmp}/githubcli-archive-keyring.gpg" + chmod go+r "${apt_tmp}/githubcli-archive-keyring.gpg" + echo "deb [arch=$(dpkg --print-architecture) signed-by=${apt_tmp}/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \ + >> "${apt_tmp}/sources.list" + sudo DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" update + sudo DEBIAN_FRONTEND=noninteractive apt-get "${apt_options[@]}" install --no-upgrade -y gh fi diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index a551af74..78c03665 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -50,7 +50,7 @@ jobs: - name: Validate RustFS compatibility contract run: | - python3 -m unittest scripts/tests/test_rustfs_compatibility.py + python3 -m unittest scripts/tests/test_rustfs_compatibility.py scripts/tests/test_setup_self_hosted.py python3 scripts/rustfs_compatibility.py --check-repository smoke-compatibility: diff --git a/Cargo.lock b/Cargo.lock index 989ec6c8..63612d27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1253,9 +1253,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3691,9 +3691,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.toml b/Cargo.toml index af94344a..a5b7e272 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ jiff = { version = "0.2", features = ["serde"] } humansize = "2.1" fundu = { version = "2.1.1", default-features = false, features = ["custom"] } bytes = "1.11" -url = "2.5" +url = "2.5.9" futures = "0.3" async-trait = "0.1" mime_guess = "2.0" diff --git a/crates/cli/src/commands/du.rs b/crates/cli/src/commands/du.rs index 6dce8ea2..eda4dfce 100644 --- a/crates/cli/src/commands/du.rs +++ b/crates/cli/src/commands/du.rs @@ -58,6 +58,12 @@ struct UsageSuccessOutput { #[derive(Debug, Serialize, PartialEq, Eq)] struct UsageData { + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + bucket_snapshot_at: std::collections::BTreeMap, + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + initial_statistics: std::collections::BTreeMap, + #[serde(skip_serializing_if = "Vec::is_empty")] + unmeasured_buckets: Vec, scope: &'static str, path: Option, source: &'static str, @@ -276,7 +282,13 @@ fn emit_report( if report.partial { if !formatter.is_json() { - formatter.warning("Usage scan is partial; one or more buckets could not be read."); + formatter.warning(if !report.initial_statistics.is_empty() { + "Initial statistics are incomplete." + } else if !report.unmeasured_buckets.is_empty() { + "Server statistics are unavailable for one or more buckets." + } else { + "Usage scan is partial; one or more buckets could not be read." + }); } ExitCode::NetworkError } else { @@ -310,6 +322,11 @@ fn scope_snapshot( report.scope = request.scope(); report.path = request.path(alias); let Some(bucket_name) = request.bucket.as_deref() else { + if report.buckets.is_empty() && !report.unmeasured_buckets.is_empty() { + return Err(Error::UnsupportedFeature( + "Server usage statistics are pending or unavailable".into(), + )); + } return Ok(report); }; @@ -319,11 +336,30 @@ fn scope_snapshot( .find(|bucket| bucket.name == bucket_name) .cloned() .ok_or_else(|| { + if report.unmeasured_buckets.iter().any(|bucket| bucket == bucket_name) { + return Error::UnsupportedFeature(format!("Usage statistics for existing bucket '{alias}/{bucket_name}' are pending or unavailable")); + } Error::NotFound(format!( "Bucket '{alias}/{bucket_name}' is absent from the server usage snapshot" )) })?; report.buckets = vec![bucket]; + report + .bucket_snapshot_at + .retain(|bucket, _| bucket == bucket_name); + if let Some(timestamp) = report.bucket_snapshot_at.get(bucket_name) { + report.snapshot_at = Some(*timestamp); + } + report + .initial_statistics + .retain(|bucket, _| bucket == bucket_name); + report.unmeasured_buckets.clear(); + report.partial = !report.initial_statistics.is_empty(); + if let Some(timestamp) = report.initial_statistics.get(bucket_name) { + report.snapshot_at = Some(*timestamp); + report.version_count = None; + report.delete_marker_count = None; + } report.finish(); Ok(report) } @@ -341,6 +377,9 @@ fn success_output( output_type: USAGE_FAMILY, status: "success", data: UsageData { + bucket_snapshot_at: report.bucket_snapshot_at.clone(), + initial_statistics: report.initial_statistics.clone(), + unmeasured_buckets: report.unmeasured_buckets.clone(), scope: report.scope.as_str(), path: report.path.clone(), source: report.source.as_str(), @@ -387,6 +426,9 @@ fn age_seconds(now: Timestamp, snapshot: Timestamp) -> u64 { fn print_human(report: &UsageReport, now: Timestamp, formatter: &Formatter) { formatter.println(&format!("Source: {}", report.source.as_str())); formatter.println(&format!("Scope: {}", report.scope.as_str())); + if !report.initial_statistics.is_empty() { + formatter.println("State: initial statistics (partial)"); + } if let Some(path) = &report.path { formatter.println(&format!("Path: {}", formatter.sanitize_text(path))); } @@ -572,6 +614,9 @@ mod tests { fn snapshot(timestamp: i64) -> UsageReport { UsageReport { + bucket_snapshot_at: Default::default(), + initial_statistics: Default::default(), + unmeasured_buckets: Vec::new(), source: UsageSource::ServerSnapshot, scope: UsageScope::Cluster, path: None, @@ -596,6 +641,48 @@ mod tests { } } + #[test] + fn scoping_a_snapshot_keeps_full_measurements_separate_from_initial_rows() { + let mut report = snapshot(100); + let first = report.buckets[0].name.clone(); + report.initial_statistics.insert( + "initial".into(), + Timestamp::from_second(200).expect("checkpoint time"), + ); + report.push_bucket(UsageBucket { + name: "initial".into(), + total_bytes: 71, + object_count: 7, + version_count: None, + delete_marker_count: None, + incomplete_upload_count: None, + incomplete_upload_bytes: None, + }); + let request = |bucket| UsageScanRequest { + bucket: Some(bucket), + prefix: None, + include_versions: false, + include_incomplete_uploads: false, + }; + let complete = + scope_snapshot(report.clone(), "alias", &request(first)).expect("full bucket"); + assert!(!complete.partial); + assert!(complete.initial_statistics.is_empty()); + assert_eq!( + complete.snapshot_at, + Some(Timestamp::from_second(100).expect("full time")) + ); + let initial = + scope_snapshot(report, "alias", &request("initial".into())).expect("initial bucket"); + assert!(initial.partial); + assert_eq!( + initial.snapshot_at, + Some(Timestamp::from_second(200).expect("initial time")) + ); + assert_eq!(initial.version_count, None); + assert_eq!(initial.object_count, 7); + } + #[tokio::test] async fn du_uses_advertised_server_snapshot_without_scanning() { let target = parse_target("local").expect("valid target"); diff --git a/crates/cli/tests/admin_recovery.rs b/crates/cli/tests/admin_recovery.rs index 79fd5a32..c1228471 100644 --- a/crates/cli/tests/admin_recovery.rs +++ b/crates/cli/tests/admin_recovery.rs @@ -731,8 +731,15 @@ impl DiscardFaultServer { let stream = acceptor.accept(stream).await.unwrap(); assert_eq!(stream.get_ref().1.alpn_protocol(), Some(b"h2".as_slice())); let mut connection = h2::server::handshake(stream).await.unwrap(); + let mut fault_injected = false; while let Some(request) = connection.accept().await { - let (request, mut response) = request.unwrap(); + let (request, mut response) = match request { + Ok(request) => request, + Err(error) if fault_injected && error.get_io().is_some_and(|error| matches!( + error.kind(), std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset + )) => return, + Err(error) => panic!("fault server request failed before an expected client disconnect: {error}"), + }; assert_eq!(request.method(), "POST"); assert_eq!(request.uri().path(), "/rustfs/admin/v4/heal/delete-residue/discard"); assert!(request.headers()["authorization"].to_str().unwrap().starts_with("AWS4-HMAC-SHA256 ")); @@ -748,6 +755,7 @@ impl DiscardFaultServer { extra = connection.accept() => panic!("unexpected stream before fault injection: {extra:?}"), }; requests.lock().unwrap().push(serde_json::from_slice(&bytes).unwrap()); + fault_injected = true; match fault { DiscardFault::RefusedStream => response.send_reset(h2::Reason::REFUSED_STREAM), DiscardFault::LostResponse => return, diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index 9586a6c7..8cdc1c9c 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -140,6 +140,16 @@ pub struct UsageFailure { /// Complete or partial usage result. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct UsageReport { + /// Original complete measurement times, independent of owner fencing. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub bucket_snapshot_at: std::collections::BTreeMap, + /// Initial measurements, keyed by bucket and original checkpoint time. + /// These rows are partial and never replace complete server measurements. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub initial_statistics: std::collections::BTreeMap, + /// Existing buckets for which no usable server measurement is available. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unmeasured_buckets: Vec, /// Data source used for the report. pub source: UsageSource, /// Scope represented by the report. @@ -172,6 +182,9 @@ impl UsageReport { /// Create an empty report that can be populated with bucket rows. pub fn empty(source: UsageSource, scope: UsageScope, path: Option) -> Self { Self { + initial_statistics: Default::default(), + bucket_snapshot_at: Default::default(), + unmeasured_buckets: Vec::new(), source, scope, path, diff --git a/crates/s3/src/ops.rs b/crates/s3/src/ops.rs index 5825b0d5..8d8d02e3 100644 --- a/crates/s3/src/ops.rs +++ b/crates/s3/src/ops.rs @@ -1,6 +1,6 @@ //! RustFS operational endpoints and portable S3 usage scanning. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::time::{Duration, Instant}; use async_trait::async_trait; @@ -86,6 +86,16 @@ impl HealthApi for AdminClient { #[derive(Debug, Deserialize)] struct DataUsageInfo { + #[serde(default)] + snapshot_view: bool, + #[serde(default)] + usage_snapshot_observational: bool, + #[serde(default)] + usage_snapshot_admin_projection: bool, + #[serde(default)] + initial_scan_progress: HashMap, + #[serde(default)] + unmeasured_buckets: Vec, #[serde(default, alias = "lastUpdate")] last_update: Option, #[serde(default, alias = "objectsTotalCount")] @@ -103,16 +113,20 @@ struct DataUsageInfo { #[derive(Debug, Deserialize)] struct BucketUsageInfo { #[serde(default)] - size: u64, + usage_value_state: Option, + #[serde(default)] + usage_certification: Option, + #[serde(default)] + size: Option, #[serde(default, alias = "objectsCount")] - objects_count: u64, + objects_count: Option, #[serde(default, alias = "versionsCount")] versions_count: u64, #[serde(default, alias = "deleteMarkersCount")] delete_markers_count: u64, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Clone, Copy, Deserialize)] #[serde(untagged)] enum RustfsTimestamp { Text(Timestamp), @@ -123,6 +137,11 @@ enum RustfsTimestamp { }, } +#[derive(Debug, Deserialize)] +struct UsageCertificationTime { + certified_at: RustfsTimestamp, +} + impl RustfsTimestamp { fn into_timestamp(self) -> Option { match self { @@ -145,29 +164,81 @@ impl RustfsTimestamp { impl UsageSnapshotApi for AdminClient { async fn usage_snapshot(&self) -> Result { let response: DataUsageInfo = self - .request(Method::GET, "/datausageinfo", None, None) + .request( + Method::GET, + "/datausageinfo", + Some(&[("view", "snapshot")]), + None, + ) .await?; - Ok(snapshot_report(response)) + snapshot_report(response) } } -fn snapshot_report(response: DataUsageInfo) -> UsageReport { - let mut buckets = response +fn snapshot_report(response: DataUsageInfo) -> Result { + if response .buckets_usage - .into_iter() - .map(|(name, bucket)| UsageBucket { + .values() + .any(|bucket| bucket.usage_value_state.as_deref() == Some("observed")) + { + return Err(Error::UnsupportedFeature( + "Server returned observed bucket values instead of complete statistics".into(), + )); + } + if response.usage_snapshot_observational + || (!response.snapshot_view && response.usage_snapshot_admin_projection) + { + return Err(Error::UnsupportedFeature( + "Server returned an observational usage view instead of a persisted snapshot".into(), + )); + } + let completed_names = response + .buckets_usage + .keys() + .cloned() + .collect::>(); + let mut unmeasured = if response.snapshot_view { + response + .unmeasured_buckets + .into_iter() + .filter(|name| !name.is_empty()) + .collect::>() + } else { + HashSet::new() + }; + let mut bucket_snapshot_at = BTreeMap::new(); + let mut buckets = Vec::with_capacity(response.buckets_usage.len()); + for (name, bucket) in response.buckets_usage { + let (Some(size), Some(objects)) = (bucket.size, bucket.objects_count) else { + if !name.is_empty() { + unmeasured.insert(name); + } + continue; + }; + if let Some(time) = bucket + .usage_certification + .as_ref() + .and_then(|value| value.certified_at.into_timestamp()) + { + bucket_snapshot_at.insert(name.clone(), time); + } + unmeasured.remove(&name); + buckets.push(UsageBucket { name, - total_bytes: bucket.size, - object_count: bucket.objects_count, + total_bytes: size, + object_count: objects, version_count: Some(bucket.versions_count), delete_marker_count: Some(bucket.delete_markers_count), incomplete_upload_count: None, incomplete_upload_bytes: None, - }) - .collect::>(); + }); + } buckets.sort_by(|left, right| left.name.cmp(&right.name)); - UsageReport { + let mut report = UsageReport { + initial_statistics: Default::default(), + bucket_snapshot_at, + unmeasured_buckets: Vec::new(), source: UsageSource::ServerSnapshot, scope: rc_core::ops::UsageScope::Cluster, path: None, @@ -183,7 +254,68 @@ fn snapshot_report(response: DataUsageInfo) -> UsageReport { buckets, partial: false, failures: Vec::new(), + }; + if response.snapshot_view { + for (name, value) in response.initial_scan_progress { + if name.is_empty() || completed_names.contains(&name) { + continue; + } + // A named scan remains pending when its numeric progress is invalid. + unmeasured.insert(name.clone()); + let Ok(progress) = serde_json::from_value::(value) else { + continue; + }; + if !matches!( + progress.stage.as_str(), + "enumerating" | "scanning" | "awaiting_sources" | "completed" + ) || progress.updated_at <= 0 + || progress.sources_observed == 0 + || progress.sources_observed > progress.sources_total + || progress.stage == "enumerating" + || (progress.stage == "completed" + && progress.sources_observed != progress.sources_total) + { + continue; + } + let Ok(timestamp) = Timestamp::from_millisecond(progress.updated_at) else { + continue; + }; + let (Some(objects), Some(size)) = (progress.objects, progress.size) else { + continue; + }; + report.initial_statistics.insert(name.clone(), timestamp); + unmeasured.remove(&name); + report.push_bucket(UsageBucket { + name, + total_bytes: size, + object_count: objects, + version_count: None, + delete_marker_count: None, + incomplete_upload_count: None, + incomplete_upload_bytes: None, + }); + } + report.partial = !report.initial_statistics.is_empty() || !unmeasured.is_empty(); + if !report.initial_statistics.is_empty() { + report.version_count = None; + report.delete_marker_count = None; + } + report.finish(); } + report.unmeasured_buckets = unmeasured.into_iter().collect(); + report.unmeasured_buckets.sort(); + report.partial |= !report.unmeasured_buckets.is_empty(); + Ok(report) +} + +#[derive(Deserialize)] +struct InitialProgress { + stage: String, + updated_at: i64, + objects: Option, + size: Option, + sources_observed: u64, + sources_total: u64, } #[async_trait] @@ -490,6 +622,127 @@ mod tests { use super::*; + #[test] + fn initial_snapshot_rows_are_explicit_partial_and_complete_rows_win() { + let value = serde_json::json!({ + "snapshot_view": true, "last_update": "2026-11-23T00:00:00Z", + "objects_total_size": 900, "objects_total_count": 90, + "buckets_usage": {"complete": {"size": 900, "objects_count": 90, + "usage_value_state": "certified", "usage_certification": {"certified_at": "2026-11-22T00:00:00Z"}}}, + "unmeasured_buckets": ["initial", "waiting"], + "initial_scan_progress": { + "initial": {"stage": "scanning", "updated_at": 1000, "objects": 7, "size": 71, "sources_observed": 1, "sources_total": 2}, + "complete": {"stage": "scanning", "updated_at": 2000, "objects": 999, "size": 9999, "sources_observed": 1, "sources_total": 2} + } + }); + let report = snapshot_report(serde_json::from_value(value).expect("snapshot response")) + .expect("partial first view"); + assert!(report.partial); + assert_eq!(report.total_bytes, 971); + assert_eq!(report.object_count, 97); + assert_eq!( + report + .buckets + .iter() + .find(|bucket| bucket.name == "complete") + .expect("complete row") + .object_count, + 90 + ); + assert_eq!(report.initial_statistics.len(), 1); + assert_eq!(report.unmeasured_buckets, ["waiting"]); + assert_eq!(report.version_count, None); + assert_eq!(report.delete_marker_count, None); + assert_eq!( + report.bucket_snapshot_at["complete"].to_string(), + "2026-11-22T00:00:00Z" + ); + } + + #[test] + fn legacy_or_malformed_initial_data_never_replaces_valid_snapshot() { + for snapshot_view in [false, true] { + for progress in [ + serde_json::json!({"stage":"future"}), + serde_json::json!({"stage":"scanning", "updated_at":1000, + "objects":-1, "size":71, "sources_observed":1, "sources_total":1}), + ] { + let value = serde_json::json!({"snapshot_view": snapshot_view, + "buckets_usage": {"complete":{"objects_count":0,"size":0}}, + "initial_scan_progress":{"initial":progress}, "unmeasured_buckets":["initial"]}); + let report = snapshot_report(serde_json::from_value(value).expect("wire shape")) + .expect("full values survive"); + assert_eq!(report.buckets.len(), 1); + assert_eq!(report.buckets[0].object_count, 0); + assert!(report.initial_statistics.is_empty()); + } + } + } + + #[test] + fn initial_scan_without_numeric_progress_is_pending_even_without_unmeasured_metadata() { + for progress in [ + serde_json::json!({"stage":"enumerating", "updated_at":1000, + "sources_observed":1, "sources_total":1}), + serde_json::json!({"stage":"scanning", "updated_at":1000, + "objects":-1, "size":71, "sources_observed":1, "sources_total":1}), + ] { + let value = serde_json::json!({"snapshot_view":true, "buckets_usage":{}, + "initial_scan_progress":{"initial":progress}}); + let report = snapshot_report(serde_json::from_value(value).expect("wire shape")) + .expect("pending scan remains reportable"); + assert!(report.partial); + assert_eq!(report.unmeasured_buckets, ["initial"]); + assert!(report.buckets.is_empty()); + } + } + + #[test] + fn incomplete_completed_rows_remain_unmeasured_and_do_not_authorize_initial_fallback() { + for row in [ + serde_json::json!({}), + serde_json::json!({"size": 0}), + serde_json::json!({"objects_count": 0}), + ] { + let response = serde_json::json!({"snapshot_view":true, + "buckets_usage":{"photos":row}, "unmeasured_buckets":["photos"], + "initial_scan_progress":{"photos":{"stage":"scanning", "updated_at":1000, + "objects":7,"size":71,"sources_observed":1,"sources_total":1}}}); + let report = snapshot_report(serde_json::from_value(response).expect("wire shape")) + .expect("pending report"); + assert!(report.buckets.is_empty()); + assert!(report.initial_statistics.is_empty()); + assert_eq!(report.unmeasured_buckets, ["photos"]); + assert!(report.partial); + } + } + + #[test] + fn many_initial_buckets_are_deduplicated_without_losing_pending_names() { + let progress = (0..10_000).map(|index| (format!("bucket-{index}"), serde_json::json!({ + "stage":"scanning", "updated_at":1000, "objects":1, "size":1, "sources_observed":1, "sources_total":1 + }))).collect::>(); + let names = progress + .keys() + .cloned() + .chain(["waiting".to_owned(), "waiting".to_owned()]) + .collect::>(); + let response = serde_json::json!({"snapshot_view":true, "buckets_usage":{}, + "initial_scan_progress":progress, "unmeasured_buckets":names}); + let report = snapshot_report(serde_json::from_value(response).expect("wire shape")) + .expect("large initial namespace"); + assert_eq!(report.buckets.len(), 10_000); + assert_eq!(report.unmeasured_buckets, ["waiting"]); + assert_eq!(report.object_count, 10_000); + } + + #[test] + fn snapshot_adapter_refuses_observational_views() { + let value = serde_json::json!({"usage_snapshot_observational":true, + "buckets_usage":{"complete":{"objects_count":1,"size":2}}}); + assert!(snapshot_report(serde_json::from_value(value).expect("wire shape")).is_err()); + } + struct TestResponse { status: &'static str, body: &'static str, @@ -557,7 +810,7 @@ mod tests { ) .expect("RustFS beta.10 data usage response should parse"); - let report = snapshot_report(raw); + let report = snapshot_report(raw).expect("valid snapshot"); assert_eq!(report.source, UsageSource::ServerSnapshot); assert_eq!( report.snapshot_at.map(Timestamp::as_second), diff --git a/nixl/Cargo.lock b/nixl/Cargo.lock index c1cb7a7e..b0c88c33 100644 --- a/nixl/Cargo.lock +++ b/nixl/Cargo.lock @@ -1335,9 +1335,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3812,9 +3812,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/schemas/output_v3.json b/schemas/output_v3.json index 3f557cb7..4224f37f 100644 --- a/schemas/output_v3.json +++ b/schemas/output_v3.json @@ -664,6 +664,9 @@ "enum": ["server_snapshot", "client_scan"] }, "snapshot_at": { "$ref": "#/definitions/nullableTimestamp" }, + "bucket_snapshot_at": { "type": "object", "additionalProperties": { "$ref": "#/definitions/nullableTimestamp" } }, + "initial_statistics": { "type": "object", "additionalProperties": { "$ref": "#/definitions/nullableTimestamp" } }, + "unmeasured_buckets": { "type": "array", "items": { "type": "string" } }, "snapshot_age_seconds": { "type": ["integer", "null"], "minimum": 0 }, "stale": { "type": "boolean" }, "incomplete_upload_count": { "type": ["integer", "null"], "minimum": 0 }, diff --git a/scripts/tests/test_setup_self_hosted.py b/scripts/tests/test_setup_self_hosted.py new file mode 100644 index 00000000..c2e6e4df --- /dev/null +++ b/scripts/tests/test_setup_self_hosted.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Exercise the real composite action with isolated package-manager doubles.""" + +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +ACTION = ROOT / ".github/actions/setup-self-hosted/action.yml" + + +class HostSetupTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.cwd = Path(temp.name) + self.log = self.cwd / "apt.jsonl" + self.release = self.cwd / "os-release" + self.release.write_text("ID=ubuntu\nVERSION_CODENAME=noble\n") + keyring = self.cwd / "archive-keyring.gpg" + keyring.write_text("fixture signing keyring") + body = ACTION.read_text().split(" run: |\n", 1)[1] + body = "\n".join(line[8:] if line.startswith(" ") else line for line in body.splitlines()) + body = body.replace(". /etc/os-release", f'. "{self.release}"') + for distro in ("ubuntu", "debian"): + body = body.replace(f"/usr/share/keyrings/{distro}-archive-keyring.gpg", str(keyring)) + self.script = self.cwd / "setup.sh" + self.script.write_text(body) + self.env = dict(os.environ, PATH=str(self.cwd) + os.pathsep + os.environ["PATH"], + APT_TEST_LOG=str(self.log), PROFILE="curl", INSTALLED_PACKAGES="all", APT_TEST_ARCH="amd64") + self.stub("sudo", '#!/bin/bash\nif [[ "$1" == DEBIAN_FRONTEND=* ]]; then shift; fi\nexec "$@"\n') + self.stub("dpkg", '#!/bin/sh\nprintf "%s\\n" "$APT_TEST_ARCH"\n') + self.stub("dpkg-query", '''#!/usr/bin/env python3 +import os, sys +installed = os.environ["INSTALLED_PACKAGES"].split() +if "all" in installed or sys.argv[-1] in installed: + print("install ok installed", end="") +else: + sys.exit(1) +''') + self.stub("apt-get", '''#!/usr/bin/env python3 +import json, os, sys +from pathlib import Path +args = sys.argv[1:] +source = next(value.split("=", 1)[1] for value in args if value.startswith("Dir::Etc::sourcelist=")) +with open(os.environ["APT_TEST_LOG"], "a") as log: + log.write(json.dumps({"args": args, "sources": Path(source).read_text()}) + "\\n") +operation = "install" if "install" in args else "update" +code = os.environ.get("APT_TEST_EXIT", "0") if os.environ.get("APT_TEST_FAIL_OPERATION", operation) == operation else "0" +sys.exit(int(code)) +''') + + def stub(self, name, content): + executable = self.cwd / name + executable.write_text(content) + executable.chmod(0o755) + + def run_setup(self): + return subprocess.run(["bash", str(self.script)], env=self.env, capture_output=True, text=True, check=False) + + def apt_calls(self): + return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else [] + + def test_installed_tools_do_not_contact_any_apt_repository(self): + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.apt_calls(), []) + + def test_missing_build_tools_use_the_same_isolated_signed_sources_for_update_and_install(self): + self.env.update(PROFILE="rust-build", INSTALLED_PACKAGES="git curl ca-certificates") + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + update, install = self.apt_calls() + self.assertIn("update", update["args"]) + self.assertIn("install", install["args"]) + options = lambda call: [value for value in call["args"] if value.startswith("Dir::")] + self.assertEqual(options(update), options(install)) + self.assertIn("Dir::Etc::sourceparts=-", update["args"]) + self.assertIn("signed-by=", update["sources"]) + self.assertIn("http://archive.ubuntu.com/ubuntu noble main universe", update["sources"]) + self.assertIn("http://security.ubuntu.com/ubuntu noble-security", update["sources"]) + self.assertNotIn("git", install["args"]) + self.assertIn("--no-upgrade", install["args"]) + + def test_arm64_uses_the_official_ubuntu_ports_archive(self): + self.env.update(INSTALLED_PACKAGES="", APT_TEST_ARCH="arm64") + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("http://ports.ubuntu.com/ubuntu-ports", self.apt_calls()[0]["sources"]) + + def test_debian_uses_its_distribution_keyring_and_security_archive(self): + self.release.write_text("ID=debian\nVERSION_CODENAME=trixie\n") + self.env["INSTALLED_PACKAGES"] = "" + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("http://security.debian.org/debian-security trixie-security main", self.apt_calls()[0]["sources"]) + + def test_repository_failure_stops_before_installing(self): + self.env.update(INSTALLED_PACKAGES="", APT_TEST_EXIT="100") + result = self.run_setup() + self.assertEqual(result.returncode, 100, result.stderr) + self.assertEqual(len(self.apt_calls()), 1) + + def test_unknown_profile_is_rejected_without_package_operations(self): + self.env["PROFILE"] = "unexpected" + result = self.run_setup() + self.assertNotEqual(result.returncode, 0) + self.assertIn("Unknown setup profile", result.stderr) + self.assertEqual(self.apt_calls(), []) + + def test_install_failure_is_not_swallowed(self): + self.env.update(INSTALLED_PACKAGES="", APT_TEST_EXIT="100", APT_TEST_FAIL_OPERATION="install") + result = self.run_setup() + self.assertEqual(result.returncode, 100, result.stderr) + self.assertEqual(len(self.apt_calls()), 2) + + def test_github_cli_adds_its_signed_source_only_to_the_temporary_context(self): + self.env["PROFILE"] = "github-cli" + self.stub("curl", '#!/bin/sh\nprintf "fixture keyring"\n') + self.script.write_text('''command() { + if [[ "$1" == "-v" && "$2" == "gh" ]]; then return 1; fi + builtin command "$@" +} +''' + self.script.read_text()) + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + update, install = self.apt_calls() + self.assertIn("https://cli.github.com/packages stable main", update["sources"]) + self.assertIn("Dir::Etc::sourceparts=-", install["args"]) + self.assertEqual(install["args"][-1], "gh") + + +if __name__ == "__main__": + unittest.main()