mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-03 06:36:35 +00:00
fix(admin): restore the persisted scanner snapshot views
This commit is contained in:
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
|
||||
Ok(response.error_for_status()?.json().await?)
|
||||
}
|
||||
|
||||
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
|
||||
let account: serde_json::Value = admin(env, resource).await?;
|
||||
account["buckets"]
|
||||
.as_array()
|
||||
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
|
||||
}
|
||||
|
||||
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
|
||||
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
|
||||
let mut sizes = BTreeMap::new();
|
||||
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
// The checkpoint and its display companion commit independently. Wait for
|
||||
// both before terminating the process to exercise the actual first-scan API.
|
||||
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
if row["initial_scan"] != true {
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
|
||||
let progress = &row["scan_progress"];
|
||||
assert_eq!(progress["sources_observed"], 1);
|
||||
assert_eq!(progress["sources_total"], 1);
|
||||
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
|
||||
assert_eq!(progress["partial"], true);
|
||||
assert_eq!(progress["converged"], false);
|
||||
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
|
||||
}
|
||||
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
|
||||
let ordinary = account_bucket(&env, "accountinfo").await?;
|
||||
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
|
||||
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
assert!(
|
||||
partial
|
||||
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
let bytes = expected.values().sum::<u64>();
|
||||
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
|
||||
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
|
||||
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
assert_eq!(completed["initial_scan"], false);
|
||||
assert!(completed.get("scan_progress").is_none());
|
||||
assert_eq!(completed["objects"], count);
|
||||
assert_eq!(completed["size"], bytes);
|
||||
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
|
||||
assert_eq!(snapshot["snapshot_view"], true);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
|
||||
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
|
||||
eprintln!(
|
||||
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
|
||||
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
|
||||
|
||||
@@ -368,7 +368,7 @@ Periodic snapshots include the suspended ancestor accounting needed to connect a
|
||||
|
||||
A resumed walk retains its previous durable coverage while initial enumeration has not recopied the covered subtrees. Unfinished out-of-order heal revisits cannot be certified as completed prefix work, including in cancellation snapshots.
|
||||
|
||||
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter includes validated coverage adoption by the forward sweep.
|
||||
Shared compacted accumulators defer periodic emission until the owning subtree completes; replay inside that compacted subtree remains possible after an interruption. When bucket checkpoint preparation returns `Reset` for existing resume state, it logs `checkpoint_reset` with the validation reason. The `scan_checkpoint_used` counter records adoption of a validated walk position, including a cursor without a coverage receipt. Only a validated coverage receipt can authorize skipping previously visited prefixes.
|
||||
|
||||
Fenced per-bucket checkpoints keep small payloads inline. Large checkpoints stage immutable, checksum-addressed pages and then conditionally replace a small manifest. The primary and backup use separate page objects. Interruption before the manifest write leaves the prior checkpoint readable. A staging marker identifies a new page bundle before any pages are written. If a later commit uses an inline checkpoint or a different bundle, that commit records the abandoned bundle for fenced cleanup, which a later save can retry after a restart. Cold recovery uses background disk admission, verifies the referenced pages, and can carry verified restore progress across local time slices. A reader that predates the page format can rebuild a partial checkpoint and can read compact complete totals when the compatibility projection fits the manifest.
|
||||
|
||||
@@ -919,6 +919,14 @@ Admin usage reads cache the selected scanner baseline for the existing 30-second
|
||||
|
||||
Missing, failed, timed-out, nil, mismatched, or legacy absent identities leave the bucket value absent (unknown), rather than returning the predecessor's value or a confirmed zero. Legacy statistics become visible after a scanner snapshot supplies the current identity. Account-info and usage display apply the existing single-process memory overlay before the final identity filter; distributed local counters are not promoted. When a projection omits values or changes an overlay, totals are partial and `usage_snapshot_converged=false`, and per-tier/replication aggregates are unavailable. Verified cold bucket values remain visible. Such response-only projections cannot be persisted, used for quota admission, or acknowledge dirty work.
|
||||
|
||||
### Persisted usage snapshot and initial progress
|
||||
|
||||
Use `GET /rustfs/admin/v3/accountinfo?view=snapshot` for stable completed counters on buckets visible to the caller. Completed rows include their original certification time. When a first scan has eligible progress, `initial_scan=true` identifies the sample in `scan_progress`. The top-level `objects` and `size` fields are reserved for completed usage, including measured zero. Progress can report enumeration or missing sources without counts. Samples from one logical source replace earlier samples from that source, so the response is neither a count of cycle work nor a total for a changing bucket.
|
||||
|
||||
`GET /rustfs/admin/v3/datausageinfo?view=snapshot` returns the same persisted view with `snapshot_view`, `initial_scan_progress`, and `unmeasured_buckets`. A small bucket certified on every expected source can be published in `buckets/.usage.buckets.json` while a larger bucket is still scanning. The scanner writes its completed-incarnation marker to the primary first, so loss of the separate file cannot reopen initial progress. First-scan eligibility requires an intact primary with explicit first-scan metadata and verified bucket identity. Backup, reset, recovery, or unreadable history can leave the bucket pending. The display data cannot authorize quota admission, whole-cycle convergence, or dirty-usage acknowledgement.
|
||||
|
||||
`metrics.scan_progress_prepare_timeouts`, `metrics.scan_progress_writes`, and `metrics.scan_progress_write_failures` report progress companion publication. Companion failure leaves a committed checkpoint available for subsequent recovery.
|
||||
|
||||
## Reading Scanner Work Observations
|
||||
|
||||
`GET /rustfs/admin/v3/scanner/status` exposes `metrics.scan_observation` for the responding node. Capture timestamped snapshots on every node, including the scanner leader, and compare their deltas over the same workload window. These process-lifetime counters reset on restart; a missing field on an older node means unobserved. They are loaded independently and may briefly disagree while operations finish. This telemetry does not change scan cadence, cached usage reads, quota authority, dirty acknowledgement, or maintenance requirements.
|
||||
|
||||
@@ -22,7 +22,7 @@ use rustfs_iam::store::Store;
|
||||
use rustfs_iam::sys::IamSys;
|
||||
use rustfs_policy::policy::{
|
||||
Args,
|
||||
action::{Action, AdminAction},
|
||||
action::{Action, AdminAction, S3Action},
|
||||
};
|
||||
use rustfs_s3_types::{S3Result, s3_error};
|
||||
use rustfs_trusted_proxies::ClientInfo;
|
||||
@@ -467,6 +467,64 @@ pub async fn authorize_admin_envelope(req: &RequestEnvelope, actions: Vec<Action
|
||||
authorize_admin_envelope_with_scope(req, actions, AdminResourceScope::bucket_object("", "")).await
|
||||
}
|
||||
|
||||
pub(crate) const DATA_USAGE_INFO_ACTIONS: [Action; 2] = [
|
||||
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
|
||||
Action::S3Action(S3Action::ListBucketAction),
|
||||
];
|
||||
|
||||
pub(crate) struct UsageSnapshotAccess<S: Store> {
|
||||
iam: Arc<IamSys<S>>,
|
||||
cred: Credentials,
|
||||
owner: bool,
|
||||
global: bool,
|
||||
}
|
||||
|
||||
impl<S: Store> UsageSnapshotAccess<S> {
|
||||
async fn for_iam(req: &AdminRequest, iam: Arc<IamSys<S>>, cred: Credentials, owner: bool) -> S3Result<Self> {
|
||||
let mut access = Self {
|
||||
iam,
|
||||
cred,
|
||||
owner,
|
||||
global: false,
|
||||
};
|
||||
let [admin_usage, list] = DATA_USAGE_INFO_ACTIONS;
|
||||
access.global = access.check(req, admin_usage, "").await.is_ok();
|
||||
if !access.global {
|
||||
access.check(req, list, "").await?;
|
||||
}
|
||||
Ok(access)
|
||||
}
|
||||
|
||||
async fn check(&self, req: &AdminRequest, action: Action, bucket: &str) -> S3Result<()> {
|
||||
validate_admin_action_with_bucket_object_for_iam(
|
||||
self.iam.clone(),
|
||||
req.headers(),
|
||||
&self.cred,
|
||||
self.owner,
|
||||
action,
|
||||
req.envelope(),
|
||||
AdminResourceScope::bucket(bucket),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn allows(&self, req: &AdminRequest, bucket: &str) -> bool {
|
||||
self.global || self.check(req, DATA_USAGE_INFO_ACTIONS[1], bucket).await.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Authenticate the inventory in the same server domain as its storage.
|
||||
pub(crate) async fn usage_snapshot_access(
|
||||
req: &AdminRequest,
|
||||
) -> S3Result<UsageSnapshotAccess<rustfs_iam::store::object::ObjectStore>> {
|
||||
let input = req
|
||||
.credentials()
|
||||
.ok_or_else(|| s3_error!(InvalidRequest, "get cred failed"))?;
|
||||
let (cred, owner) = authenticate_envelope_credentials_with_context(input, req.envelope()).await?;
|
||||
let iam = ready_iam_handle_from_envelope(Some(req.envelope()))?;
|
||||
UsageSnapshotAccess::for_iam(req, iam, cred, owner).await
|
||||
}
|
||||
|
||||
/// Full admin gate over RustFS-owned request facts scoped to a bucket/object
|
||||
/// resource against the process-ambient IAM domain (matching ambient-store
|
||||
/// admin handlers).
|
||||
@@ -1228,6 +1286,41 @@ mod tests {
|
||||
assert!(res.is_ok(), "an absent key id must keep the pre-resource-scoping verdict");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_snapshot_keeps_cluster_gate_and_checks_list_only_names() {
|
||||
let req = crate::admin::operation::test_support::TestRequest::new(
|
||||
http::Method::GET,
|
||||
"/rustfs/admin/v3/datausageinfo?view=snapshot",
|
||||
)
|
||||
.build();
|
||||
for (allow, resource, expected) in [
|
||||
("s3:ListBucket", "arn:aws:s3:::public", None),
|
||||
("s3:ListBucket", "arn:aws:s3:::*", Some(false)),
|
||||
("admin:DataUsageInfo", "*", Some(true)),
|
||||
] {
|
||||
let doc = serde_json::json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[
|
||||
{"Effect":"Allow","Action":[allow],"Resource":[resource]},
|
||||
{"Effect":"Deny","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::private"]}
|
||||
]
|
||||
});
|
||||
let cred = Credentials {
|
||||
access_key: "reader".to_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let iam = iam_sys_with_policy("reader", &doc.to_string());
|
||||
let result = UsageSnapshotAccess::for_iam(&req, iam, cred, false).await;
|
||||
if let Some(see_private) = expected {
|
||||
let filter = result.expect("global inventory grant");
|
||||
assert!(filter.allows(&req, "public").await);
|
||||
assert_eq!(filter.allows(&req, "private").await, see_private);
|
||||
} else {
|
||||
assert!(matches!(result, Err(err) if err.code() == &rustfs_s3_types::S3ErrorCode::AccessDenied));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The multi-action loop authorizes as soon as one candidate action passes
|
||||
/// (owner short-circuits every action), and denies when none pass.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -22,7 +22,10 @@ use crate::admin::service::caller_identity::{OidcProfileFields, oidc_profile_fie
|
||||
use crate::admin::storage_api::bucket::versioning_sys::BucketVersioningSys;
|
||||
use crate::admin::storage_api::contract::admin::StorageAdminApi;
|
||||
use crate::admin::storage_api::contract::bucket::{BucketOperations, BucketOptions};
|
||||
use crate::admin::storage_api::data_usage::{load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin};
|
||||
use crate::admin::storage_api::data_usage::{
|
||||
load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot, load_bucket_scan_progress_for_admin,
|
||||
verified_account_bucket_usage,
|
||||
};
|
||||
use crate::admin::storage_api::metadata_sys;
|
||||
use crate::auth::get_condition_values_with_client_info;
|
||||
use crate::server::ADMIN_PREFIX;
|
||||
@@ -30,7 +33,7 @@ use http::header::CONTENT_TYPE;
|
||||
use http::{HeaderMap, HeaderValue};
|
||||
use hyper::{Method, StatusCode};
|
||||
use matchit::Params;
|
||||
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState, DataUsageInfo};
|
||||
use rustfs_data_usage::{BucketScanStage, BucketUsageInfo, BucketUsageValueState};
|
||||
use rustfs_gateway_types::dto::Status;
|
||||
use rustfs_gateway_types::persistence::PersistedObjectLockConfiguration as ObjectLockConfiguration;
|
||||
use rustfs_gateway_types::persistence::PersistedReplicationConfiguration;
|
||||
@@ -44,8 +47,14 @@ use std::sync::Arc;
|
||||
|
||||
const DATA_USAGE_LOAD_ERROR_MESSAGE: &str = "failed to load data usage";
|
||||
|
||||
fn map_data_usage_result<E>(result: Result<DataUsageInfo, E>) -> S3Result<DataUsageInfo> {
|
||||
result.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE))
|
||||
fn data_usage_load_error<E>(_: E) -> S3Error {
|
||||
S3Error::with_message(S3ErrorCode::InternalError, DATA_USAGE_LOAD_ERROR_MESSAGE)
|
||||
}
|
||||
|
||||
pub(super) fn requests_usage_snapshot(uri: &http::Uri) -> bool {
|
||||
uri.query().is_some_and(|query| {
|
||||
url::form_urlencoded::parse(query.as_bytes()).any(|(key, value)| key == "view" && value == "snapshot")
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Default)]
|
||||
@@ -317,14 +326,6 @@ impl Operation for AccountInfoHandler {
|
||||
.await
|
||||
.map_err(|e| S3Error::with_message(S3ErrorCode::InternalError, e.to_string()))?;
|
||||
|
||||
// Serve the last persisted scanner snapshot plus an authoritative
|
||||
// single-process overlay. Distributed nodes must not promote their
|
||||
// process-local absolute counters to cluster-wide bucket totals.
|
||||
// This path never triggers a live full-version listing
|
||||
// (rustfs/backlog#1306); freshness is owned by the scanner.
|
||||
let data_usage_info = map_data_usage_result(load_admin_data_usage_with_memory_overlay(store.clone()).await)?;
|
||||
account_info.usage_snapshot_converged = data_usage_info.usage_snapshot_converged;
|
||||
|
||||
for bucket in buckets.iter() {
|
||||
let (rd, wr) = is_allow(bucket.name.clone()).await;
|
||||
if rd || wr {
|
||||
@@ -350,16 +351,25 @@ impl Operation for AccountInfoHandler {
|
||||
.iter()
|
||||
.map(|bucket| bucket.name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &data_usage_info).await;
|
||||
let measured = crate::admin::storage_api::data_usage::verified_account_bucket_usage(
|
||||
store,
|
||||
data_usage_info.buckets_usage,
|
||||
visible_buckets,
|
||||
)
|
||||
.await;
|
||||
let snapshot_view = requests_usage_snapshot(req.uri());
|
||||
let (converged, measured, mut progress) = if snapshot_view {
|
||||
let view = load_admin_usage_snapshot(store, &visible_buckets)
|
||||
.await
|
||||
.map_err(data_usage_load_error)?;
|
||||
(view.usage.usage_snapshot_converged, view.usage.buckets_usage, view.initial_scan_progress)
|
||||
} else {
|
||||
let usage = load_admin_data_usage_with_memory_overlay(store.clone())
|
||||
.await
|
||||
.map_err(data_usage_load_error)?;
|
||||
let progress = load_bucket_scan_progress_for_admin(store.clone(), &visible_buckets, &usage).await;
|
||||
let measured = verified_account_bucket_usage(store, usage.buckets_usage, visible_buckets).await;
|
||||
(usage.usage_snapshot_converged, measured, progress)
|
||||
};
|
||||
account_info.usage_snapshot_converged = converged;
|
||||
for bucket in &mut account_info.buckets {
|
||||
apply_usage_to_bucket_access_info(bucket, measured.get(&bucket.name));
|
||||
bucket.scan_progress = progress.remove(&bucket.name).map(bucket_scan_progress_response);
|
||||
bucket.initial_scan = snapshot_view.then_some(bucket.scan_progress.is_some());
|
||||
}
|
||||
|
||||
let data = serde_json::to_vec(&AccountInfoResponse {
|
||||
@@ -518,6 +528,21 @@ mod tests {
|
||||
assert_eq!(bucket_info.scan_progress.expect("separate partial view").objects, Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_selects_only_the_explicit_snapshot_view() {
|
||||
for (query, expected) in [
|
||||
("", false),
|
||||
("?view=other", false),
|
||||
("?snapshot=true", false),
|
||||
("?other=view%3Dsnapshot", false),
|
||||
("?view=snapshot", true),
|
||||
("?client=console&view=%73napshot", true),
|
||||
] {
|
||||
let uri = format!("/rustfs/admin/v3/accountinfo{query}").parse().expect("test URI");
|
||||
assert_eq!(requests_usage_snapshot(&uri), expected, "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accountinfo_scan_progress_projection_preserves_wire_contract() {
|
||||
for (stage, objects, size, sources_observed) in [
|
||||
@@ -566,7 +591,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn accountinfo_data_usage_error_message_is_generic() {
|
||||
let err = map_data_usage_result::<&str>(Err("sensitive disk path")).expect_err("load failure must reach the response");
|
||||
let err = data_usage_load_error("sensitive disk path");
|
||||
|
||||
assert_eq!(err.code(), &S3ErrorCode::InternalError);
|
||||
assert_eq!(err.message(), Some("failed to load data usage"));
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
|
||||
use super::{cluster_snapshot, realtime};
|
||||
use crate::admin::auth::{
|
||||
AdminResourceScope, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
|
||||
resolve_admin_object_read_sse_kms_principal,
|
||||
AdminResourceScope, DATA_USAGE_INFO_ACTIONS, authorize_admin_envelope, authorize_admin_envelope_with_context_and_scope,
|
||||
resolve_admin_object_read_sse_kms_principal, usage_snapshot_access,
|
||||
};
|
||||
use crate::admin::handlers::account::{ACCOUNT_INFO_ROUTE, ACCOUNT_PASSWORD_ROUTE};
|
||||
use crate::admin::handlers::mfa::{ACCOUNT_MFA_ROUTE, MFA_CHALLENGE_ROUTE, USER_MFA_ROUTE};
|
||||
@@ -35,6 +35,8 @@ use crate::admin::storage_api::bucket::replication::{
|
||||
use crate::admin::storage_api::cluster::{
|
||||
CapabilityState, CapabilityStatus, ObservabilitySnapshotProvider, TopologySnapshot, TopologySnapshotProvider,
|
||||
};
|
||||
use crate::admin::storage_api::contract::bucket::{BucketOperations as _, BucketOptions};
|
||||
use crate::admin::storage_api::data_usage::load_admin_usage_snapshot;
|
||||
use crate::admin::storage_api::storageclass as storage_class_contract;
|
||||
use crate::admin::utils::is_compat_admin_request;
|
||||
use crate::runtime_capabilities::{EndpointTopologySnapshotProvider, RustFsObservabilitySnapshotProvider};
|
||||
@@ -46,7 +48,7 @@ use hyper::{Method, StatusCode};
|
||||
use matchit::Params;
|
||||
use rustfs_concurrency::WorkloadAdmissionRegistrySnapshot;
|
||||
use rustfs_madmin::{InfoMessage, StorageInfo};
|
||||
use rustfs_policy::policy::action::{Action, AdminAction, S3Action};
|
||||
use rustfs_policy::policy::action::{Action, AdminAction};
|
||||
use rustfs_s3_types::{Body, S3Error, S3ErrorCode, S3Result, s3_error};
|
||||
use rustfs_security_governance::{AdminRouteSpec, HttpMethod};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -1261,10 +1263,7 @@ impl Operation for RuntimeCapabilitiesHandler {
|
||||
/// dedicated admin action OR the bucket listing action. Pinned by a unit test
|
||||
/// so the gate cannot silently narrow or widen (rustfs/backlog#1306).
|
||||
pub(crate) fn data_usage_info_gate_actions() -> Vec<Action> {
|
||||
vec![
|
||||
Action::AdminAction(AdminAction::DataUsageInfoAdminAction),
|
||||
Action::S3Action(S3Action::ListBucketAction),
|
||||
]
|
||||
DATA_USAGE_INFO_ACTIONS.to_vec()
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -1275,12 +1274,37 @@ impl Operation for DataUsageInfoHandler {
|
||||
return Err(s3_error!(InvalidRequest, "get cred failed"));
|
||||
}
|
||||
|
||||
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
|
||||
|
||||
let usecase = default_admin_usecase();
|
||||
let info = usecase.execute_query_data_usage_info().await.map_err(S3Error::from)?;
|
||||
|
||||
let data = serde_json::to_vec(&info).map_err(|e| {
|
||||
let data = if super::account_info::requests_usage_snapshot(req.uri()) {
|
||||
let visible = usage_snapshot_access(&req).await?;
|
||||
let store = object_store_from_envelope(req.envelope())
|
||||
.ok_or_else(|| S3Error::with_message(S3ErrorCode::InternalError, "Object store unavailable"))?;
|
||||
let buckets = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
|
||||
let mut names = Vec::with_capacity(buckets.len());
|
||||
for bucket in buckets {
|
||||
if visible.allows(&req, &bucket.name).await {
|
||||
names.push(bucket.name);
|
||||
}
|
||||
}
|
||||
let view = load_admin_usage_snapshot(store, &names)
|
||||
.await
|
||||
.map_err(|_| S3Error::with_message(S3ErrorCode::InternalError, "Usage snapshot unavailable"))?;
|
||||
serde_json::to_vec(&view)
|
||||
} else {
|
||||
authorize_admin_envelope(req.envelope(), data_usage_info_gate_actions()).await?;
|
||||
let info = default_admin_usecase()
|
||||
.execute_query_data_usage_info()
|
||||
.await
|
||||
.map_err(S3Error::from)?;
|
||||
serde_json::to_vec(&info)
|
||||
}
|
||||
.map_err(|e| {
|
||||
log_system_request_failed!("query_data_usage_info", "serialize_data_usage_info_failed", e);
|
||||
S3Error::with_message(S3ErrorCode::InternalError, "parse DataUsageInfo failed")
|
||||
})?;
|
||||
|
||||
@@ -947,7 +947,7 @@ pub(crate) static ERR_TIER_NOT_FOUND: AdminErrorRef = AdminErrorRef(|| &ecstore_
|
||||
pub(crate) static ERR_TIER_RESERVED_NAME: AdminErrorRef = AdminErrorRef(|| &ecstore_tier::tier_handlers::ERR_TIER_RESERVED_NAME);
|
||||
|
||||
pub(crate) mod data_usage {
|
||||
pub(crate) use crate::storage::storage_api::ecstore_data_usage::verified_account_bucket_usage;
|
||||
pub(crate) use crate::storage::storage_api::ecstore_data_usage::{load_admin_usage_snapshot, verified_account_bucket_usage};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) async fn load_bucket_scan_progress_for_admin(
|
||||
|
||||
@@ -583,7 +583,7 @@ pub(crate) mod ecstore_config {
|
||||
pub(crate) mod ecstore_data_usage {
|
||||
pub(crate) use rustfs_ecstore::api::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, get_bucket_usage_memory, init_compression_total_memory_from_backend,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay, load_admin_usage_snapshot,
|
||||
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached, load_data_usage_from_backend,
|
||||
lookup_degraded_bucket_usage_baseline, quota_object_size, record_bucket_delete_marker_memory,
|
||||
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
|
||||
|
||||
Reference in New Issue
Block a user