mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-01 13:44:49 +00:00
feat(obs): export remote tier inventory and 24h transition gauges (#9803)
This commit is contained in:
@@ -96,4 +96,7 @@ pub use system_process::{
|
||||
ProcessAttributeError, ProcessAttributes, ProcessStats, ProcessStatusType, collect_process_attributes,
|
||||
collect_process_metrics,
|
||||
};
|
||||
pub use tier::{TierRequestStats, collect_tier_request_metrics};
|
||||
pub use tier::{
|
||||
TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier request metrics collector.
|
||||
//! Remote tier request, inventory, and rolling transition metrics collectors.
|
||||
|
||||
use crate::metrics::report::PrometheusMetric;
|
||||
use crate::metrics::schema::tier::*;
|
||||
@@ -25,6 +25,38 @@ pub struct TierRequestStats {
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
/// Cluster-wide stored inventory counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierInventoryEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
pub versions_count: u64,
|
||||
}
|
||||
|
||||
/// Node-local rolling 24-hour transition counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierTransitionLast24hEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
}
|
||||
|
||||
/// Snapshot of configured remote-tier inventory and rolling 24-hour transition activity.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct TierUsageSnapshot {
|
||||
/// Whether the persisted usage snapshot carries per-tier accounting.
|
||||
///
|
||||
/// When `false` (`not-accounted` or `unavailable`), per-tier inventory
|
||||
/// gauges are omitted so callers never mistake an unaccounted tier for an
|
||||
/// empty tier.
|
||||
pub inventory_accounted: bool,
|
||||
pub inventory: Vec<TierInventoryEntry>,
|
||||
pub transitions_last24h: Vec<TierTransitionLast24hEntry>,
|
||||
}
|
||||
|
||||
/// Split the fixed operation/outcome cells over the success and failure
|
||||
/// counters.
|
||||
///
|
||||
@@ -47,6 +79,62 @@ pub fn collect_tier_request_metrics(stats: &[TierRequestStats]) -> Vec<Prometheu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Collect configured remote-tier inventory and node-local rolling 24-hour
|
||||
/// transition gauges.
|
||||
///
|
||||
/// Inventory gauges are emitted only when `snapshot.inventory_accounted` is
|
||||
/// `true`; an unaccounted or unavailable usage snapshot emits
|
||||
/// `rustfs_tier_inventory_accounted = 0` and omits per-tier inventory series
|
||||
/// rather than fabricating zeros.
|
||||
pub fn collect_tier_usage_metrics(snapshot: &TierUsageSnapshot) -> Vec<PrometheusMetric> {
|
||||
let inventory_len = if snapshot.inventory_accounted {
|
||||
snapshot.inventory.len() * 3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut metrics = Vec::with_capacity(1 + inventory_len + snapshot.transitions_last24h.len() * 2);
|
||||
|
||||
metrics.push(PrometheusMetric::from_descriptor(
|
||||
&TIER_INVENTORY_ACCOUNTED_MD,
|
||||
if snapshot.inventory_accounted { 1.0 } else { 0.0 },
|
||||
));
|
||||
|
||||
if snapshot.inventory_accounted {
|
||||
for entry in &snapshot.inventory {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_VERSIONS_COUNT_MD, entry.versions_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for entry in &snapshot.transitions_last24h {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
metrics
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -93,4 +181,114 @@ mod tests {
|
||||
"the failure counter must keep the outcome that produced it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_emit_all_six_gauges_when_inventory_is_accounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 3,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
assert_eq!(metrics.len(), 6);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.all(|metric| metric.metric_type == crate::metrics::schema::MetricType::Gauge),
|
||||
"tier usage metrics must be gauges"
|
||||
);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted");
|
||||
assert_eq!(accounted.value, 1.0);
|
||||
assert!(accounted.labels.is_empty(), "accounted gauge is snapshot-level without tier label");
|
||||
|
||||
for (name, expected) in [
|
||||
("rustfs_tier_inventory_bytes", 4096.0),
|
||||
("rustfs_tier_inventory_objects_count", 12.0),
|
||||
("rustfs_tier_inventory_versions_count", 15.0),
|
||||
("rustfs_tier_transitions_last24h_bytes", 1024.0),
|
||||
("rustfs_tier_transitions_last24h_objects_count", 3.0),
|
||||
] {
|
||||
let metric = metrics
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.unwrap_or_else(|| panic!("expected metric {name} to be emitted"));
|
||||
assert_eq!(metric.value, expected, "unexpected value for {name}");
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_LABEL && v.as_ref() == "COLD"),
|
||||
"{name} must carry tier label"
|
||||
);
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_TYPE_LABEL && v.as_ref() == "s3"),
|
||||
"{name} must carry tier_type label"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_omit_inventory_gauges_when_unaccounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 2,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted when unaccounted");
|
||||
assert_eq!(accounted.value, 0.0);
|
||||
|
||||
for forbidden in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
metrics.iter().all(|metric| metric.name != forbidden),
|
||||
"{forbidden} must not be emitted when inventory_accounted is false"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_bytes" && metric.value == 512.0),
|
||||
"node-local 24h transition bytes must remain populated when inventory is unaccounted"
|
||||
);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_objects_count" && metric.value == 2.0),
|
||||
"node-local 24h transition object count must remain populated when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,9 +33,10 @@ pub use scheduler::{
|
||||
};
|
||||
pub(crate) use storage_api::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor,
|
||||
obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
ObsTierCounter, StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
};
|
||||
|
||||
@@ -78,6 +78,7 @@ use crate::metrics::collectors::{
|
||||
collect_resource_metrics,
|
||||
collect_scanner_runtime_metrics,
|
||||
collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
use crate::metrics::config::{
|
||||
DEFAULT_AUDIT_METRICS_INTERVAL, DEFAULT_BUCKET_METRICS_INTERVAL, DEFAULT_BUCKET_REPLICATION_BANDWIDTH_METRICS_INTERVAL,
|
||||
@@ -140,10 +141,10 @@ use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROC
|
||||
use crate::metrics::stats_collector::{
|
||||
ProcessMetricBundle, collect_api_request_stats, collect_bucket_replication_bandwidth_stats,
|
||||
collect_bucket_replication_stats_bundle, collect_bucket_stats, collect_cluster_config_stats,
|
||||
collect_cluster_storage_snapshot, collect_cluster_usage_metric_stats, collect_compression_cluster_stats,
|
||||
collect_disk_and_system_drive_runtime_stats, collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats,
|
||||
collect_internode_network_stats, collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats,
|
||||
collect_process_metric_bundle_with, collect_replication_stats, collect_scanner_runtime_metric_stats,
|
||||
collect_cluster_storage_snapshot, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
|
||||
collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats, collect_internode_network_stats,
|
||||
collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats, collect_process_metric_bundle_with,
|
||||
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_supplementary_usage_metric_stats,
|
||||
collect_system_cpu_and_memory_stats_with, collect_tier_request_metric_stats,
|
||||
};
|
||||
use crate::metrics::storage_snapshot::StorageSnapshotMetrics;
|
||||
@@ -1614,6 +1615,7 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
let tombstone_cycles = config.replication_bandwidth_zero_tombstone_cycles;
|
||||
let mut has_seen_bucket_usage_snapshot = false;
|
||||
let mut bucket_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut tier_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut prev_bucket_usage_keys: HashSet<BucketKey> = HashSet::new();
|
||||
let mut bucket_usage_zero_tombstones: HashMap<BucketKey, u8> = HashMap::new();
|
||||
let mut prev_bucket_usage_object_size_keys: HashSet<BucketRangeKey> = HashSet::new();
|
||||
@@ -1640,7 +1642,8 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
}
|
||||
|
||||
let usage_collection_started = std::time::Instant::now();
|
||||
if let Some((cluster_usage, bucket_usage)) = collect_cluster_usage_metric_stats().await {
|
||||
let (cluster_bucket_usage, tier_usage) = collect_supplementary_usage_metric_stats().await;
|
||||
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage {
|
||||
let mut usage_metrics = collect_cluster_usage_metrics(&cluster_usage);
|
||||
usage_metrics.extend(collect_bucket_usage_metrics(&bucket_usage));
|
||||
update_series_zero_tombstones(
|
||||
@@ -1681,6 +1684,11 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
|
||||
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
if !metrics.is_empty() {
|
||||
report_metrics(&metrics);
|
||||
}
|
||||
|
||||
@@ -135,9 +135,15 @@ pub enum MetricName {
|
||||
TransitionedObjects,
|
||||
TransitionedVersions,
|
||||
|
||||
//Tier request metrics
|
||||
// Tier metrics
|
||||
TierRequestsSuccess,
|
||||
TierRequestsFailure,
|
||||
TierInventoryBytes,
|
||||
TierInventoryObjectsCount,
|
||||
TierInventoryVersionsCount,
|
||||
TierInventoryAccounted,
|
||||
TierTransitionsLast24hBytes,
|
||||
TierTransitionsLast24hObjectsCount,
|
||||
|
||||
// KMS metrics
|
||||
KmsOnline,
|
||||
@@ -560,6 +566,12 @@ impl MetricName {
|
||||
|
||||
Self::TierRequestsSuccess => "requests_success",
|
||||
Self::TierRequestsFailure => "requests_failure",
|
||||
Self::TierInventoryBytes => "inventory_bytes",
|
||||
Self::TierInventoryObjectsCount => "inventory_objects_count",
|
||||
Self::TierInventoryVersionsCount => "inventory_versions_count",
|
||||
Self::TierInventoryAccounted => "inventory_accounted",
|
||||
Self::TierTransitionsLast24hBytes => "transitions_last24h_bytes",
|
||||
Self::TierTransitionsLast24hObjectsCount => "transitions_last24h_objects_count",
|
||||
|
||||
Self::KmsOnline => "online",
|
||||
Self::KmsRequestsSuccess => "request_success",
|
||||
|
||||
@@ -12,17 +12,23 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier request metric descriptors.
|
||||
//! Remote tier metric descriptors.
|
||||
//!
|
||||
//! The label set is fixed by the operation and outcome enums the recording
|
||||
//! site uses, so the series count is bounded by construction and cannot grow
|
||||
//! with tier names, endpoints or object keys.
|
||||
//! Request counters (`rustfs_tier_requests_*`) keep a closed label set fixed by
|
||||
//! the operation and outcome enums so request hot paths never depend on tier
|
||||
//! names, endpoints, or object keys.
|
||||
//!
|
||||
//! Inventory and rolling 24-hour transition gauges are published from periodic
|
||||
//! snapshots and carry configured remote tier identity (`tier`, `tier_type`),
|
||||
//! never endpoints, credentials, or object keys.
|
||||
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, subsystems};
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, new_gauge_md, subsystems};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub const OPERATION_LABEL: &str = "operation";
|
||||
pub const OUTCOME_LABEL: &str = "outcome";
|
||||
pub const TIER_LABEL: &str = "tier";
|
||||
pub const TIER_TYPE_LABEL: &str = "tier_type";
|
||||
|
||||
pub static TIER_REQUESTS_SUCCESS_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_counter_md(
|
||||
@@ -41,3 +47,57 @@ pub static TIER_REQUESTS_FAILURE_MD: LazyLock<MetricDescriptor> = LazyLock::new(
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryBytes,
|
||||
"Cluster-wide logical bytes currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryObjectsCount,
|
||||
"Cluster-wide object count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_VERSIONS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryVersionsCount,
|
||||
"Cluster-wide object version count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_ACCOUNTED_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryAccounted,
|
||||
"Whether the persisted usage snapshot includes per-tier inventory accounting (1 = accounted, 0 = not-accounted or unavailable)",
|
||||
&[],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hBytes,
|
||||
"Node-local logical bytes committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hObjectsCount,
|
||||
"Node-local objects committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -28,15 +28,16 @@ use crate::metrics::collectors::{
|
||||
DriveDetailedStats, DriveRuntimeDetailedStats, ErasureSetStats, HostNetworkStats, IamStats, IlmActionTaskStats,
|
||||
IlmBackpressureStats, IlmQueueTaskStats, IlmRuntimeStats, IlmStats, IlmTaskEventStats, MemoryStats, NetworkStats,
|
||||
OdmBackfillRuntimeStats, OnDemandMigrationBucketStats, ProcessStats, ProcessStatusType, ReplicationMetricsSnapshot,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierRequestStats,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry,
|
||||
TierUsageSnapshot,
|
||||
};
|
||||
use crate::metrics::runtime_sources::{ObsIlmRuntimeSnapshot, bucket_monitor_handle, iam_metrics_snapshot, ilm_runtime_snapshot};
|
||||
use crate::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, StorageAdminApi,
|
||||
obs_bucket_replication_stats_snapshot, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot,
|
||||
obs_resolve_object_store_handle,
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
};
|
||||
use crate::node_identity::current_local_node_identity;
|
||||
use jiff::Timestamp;
|
||||
@@ -76,6 +77,7 @@ struct ObsDataUsageInfo {
|
||||
delete_markers_total_count: u64,
|
||||
objects_total_size: u64,
|
||||
buckets_usage: HashMap<String, ObsBucketUsageInfo>,
|
||||
tier_stats: Option<HashMap<String, ObsTierCounter>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -130,6 +132,22 @@ async fn load_obs_data_usage_from_backend(store: Arc<ObsStore>) -> ObsEcstoreRes
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
tier_stats: data_usage.tier_stats.map(|all_tiers| {
|
||||
all_tiers
|
||||
.tiers
|
||||
.into_iter()
|
||||
.map(|(tier, stats)| {
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: stats.total_size,
|
||||
num_objects: stats.num_objects,
|
||||
num_versions: stats.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1251,6 +1269,109 @@ pub async fn collect_cluster_usage_metric_stats() -> Option<(ClusterUsageStats,
|
||||
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await
|
||||
}
|
||||
|
||||
/// Collect cluster/bucket usage and configured remote-tier usage from one
|
||||
/// shared backend data-usage snapshot read.
|
||||
///
|
||||
/// Remote-tier inventory is extracted before the bucket-namespace completeness
|
||||
/// check so OTLP tier metrics match `GET /rustfs/admin/v3/tier-stats`, and a
|
||||
/// backend usage read failure still yields `inventory_accounted = false` plus
|
||||
/// node-local 24-hour transition counters when remote tiers are configured.
|
||||
pub(crate) async fn collect_supplementary_usage_metric_stats()
|
||||
-> (Option<(ClusterUsageStats, Vec<BucketUsageStats>)>, Option<TierUsageSnapshot>) {
|
||||
let configured_tiers = obs_configured_remote_tier_types().await;
|
||||
let store = resolve_obs_object_store_handle();
|
||||
let data_usage = match store.as_ref() {
|
||||
Some(store) => load_obs_data_usage_from_backend(store.clone()).await.ok(),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let tier_usage = if configured_tiers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let local_daily_stats = obs_local_tier_daily_stats();
|
||||
tier_usage_snapshot_from_parts(
|
||||
&configured_tiers,
|
||||
data_usage.as_ref().and_then(|usage| usage.tier_stats.as_ref()),
|
||||
&local_daily_stats,
|
||||
)
|
||||
};
|
||||
|
||||
let cluster_bucket_usage = match (store, data_usage) {
|
||||
(Some(store), Some(data_usage)) => {
|
||||
let bucket_namespace = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.map(|buckets| {
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter(|bucket| !bucket.name.starts_with('.'))
|
||||
.map(|bucket| bucket.name)
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
match bucket_namespace {
|
||||
Some(bucket_namespace) => collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await,
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
(cluster_bucket_usage, tier_usage)
|
||||
}
|
||||
|
||||
fn tier_usage_snapshot_from_parts(
|
||||
configured_tiers: &HashMap<String, String>,
|
||||
data_usage_tier_stats: Option<&HashMap<String, ObsTierCounter>>,
|
||||
local_daily_stats: &HashMap<String, ObsTierCounter>,
|
||||
) -> Option<TierUsageSnapshot> {
|
||||
if configured_tiers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut tiers: Vec<(&str, &str)> = configured_tiers
|
||||
.iter()
|
||||
.map(|(name, tier_type)| (name.as_str(), tier_type.as_str()))
|
||||
.collect();
|
||||
tiers.sort_unstable_by(|a, b| a.0.cmp(b.0));
|
||||
|
||||
let inventory_accounted = data_usage_tier_stats.is_some();
|
||||
let mut inventory = Vec::new();
|
||||
let mut transitions_last24h = Vec::with_capacity(tiers.len());
|
||||
|
||||
for (tier, tier_type) in tiers {
|
||||
if let Some(inv_map) = data_usage_tier_stats
|
||||
&& let Some(stats) = inv_map.get(tier)
|
||||
{
|
||||
inventory.push(TierInventoryEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: stats.total_size,
|
||||
objects_count: stats.num_objects,
|
||||
versions_count: stats.num_versions,
|
||||
});
|
||||
}
|
||||
|
||||
let daily = local_daily_stats.get(tier).copied().unwrap_or_default();
|
||||
transitions_last24h.push(TierTransitionLast24hEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: daily.total_size,
|
||||
objects_count: daily.num_objects,
|
||||
});
|
||||
}
|
||||
|
||||
Some(TierUsageSnapshot {
|
||||
inventory_accounted,
|
||||
inventory,
|
||||
transitions_last24h,
|
||||
})
|
||||
}
|
||||
|
||||
async fn collect_cluster_usage_metric_stats_from_data_usage(
|
||||
data_usage: ObsDataUsageInfo,
|
||||
bucket_namespace: &HashSet<String>,
|
||||
@@ -1946,6 +2067,136 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_returns_none_when_no_remote_tiers_configured() {
|
||||
let configured = HashMap::new();
|
||||
let data_usage_tiers = HashMap::from([(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 4096,
|
||||
num_objects: 2,
|
||||
num_versions: 2,
|
||||
},
|
||||
)]);
|
||||
let daily = HashMap::new();
|
||||
|
||||
assert!(tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_excludes_local_classes_unconfigured_tiers_and_unscanned_zeros() {
|
||||
let configured = HashMap::from([
|
||||
("COLD".to_string(), "rustfs".to_string()),
|
||||
("ARCHIVE".to_string(), "s3".to_string()),
|
||||
]);
|
||||
let data_usage_tiers = HashMap::from([
|
||||
(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 99_999,
|
||||
num_objects: 99,
|
||||
num_versions: 120,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 8_192,
|
||||
num_objects: 4,
|
||||
num_versions: 4,
|
||||
},
|
||||
),
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 5,
|
||||
num_versions: 7,
|
||||
},
|
||||
),
|
||||
]);
|
||||
let daily = HashMap::from([
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 512,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 128,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily)
|
||||
.expect("configured remote tiers should yield a tier usage snapshot");
|
||||
|
||||
assert!(snapshot.inventory_accounted);
|
||||
assert_eq!(
|
||||
snapshot.inventory,
|
||||
vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 5,
|
||||
versions_count: 7,
|
||||
}],
|
||||
"only accounted configured remote tiers must appear in inventory; local classes, removed tiers, and unscanned tiers must not"
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "rustfs".to_string(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
"all configured remote tiers should report deterministic sorted node-local 24h transitions"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_preserves_local_transitions_when_inventory_is_not_accounted() {
|
||||
let configured = HashMap::from([("COLD".to_string(), "s3".to_string())]);
|
||||
let daily = HashMap::from([(
|
||||
"COLD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 1024,
|
||||
num_objects: 2,
|
||||
num_versions: 3,
|
||||
},
|
||||
)]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, None, &daily)
|
||||
.expect("configured remote tier should still emit snapshot when usage is unaccounted");
|
||||
|
||||
assert!(!snapshot.inventory_accounted);
|
||||
assert!(snapshot.inventory.is_empty());
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 2,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cluster_config_stats_accept_homogeneous_backend_parities() {
|
||||
let stats = cluster_config_stats_from_backend_parities(Some(1), Some(2))
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) use rustfs_ecstore::api::bucket::bandwidth::monitor::Monitor as ObsBucketBandwidthMonitor;
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::LastDayTierStats as ObsLastDayTierStats;
|
||||
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::get_quota_config as obs_get_quota_config;
|
||||
use rustfs_ecstore::api::bucket::replication::{
|
||||
BucketReplicationStats as SourceBucketReplicationStats, DurableMrfBucketBacklog, DurableMrfTargetBacklog,
|
||||
@@ -32,7 +33,8 @@ pub(crate) use rustfs_ecstore::api::data_usage::load_compression_total_from_memo
|
||||
pub(crate) use rustfs_ecstore::api::error::Result as ObsEcstoreResult;
|
||||
pub(crate) use rustfs_ecstore::api::runtime::{
|
||||
bucket_monitor as obs_get_global_bucket_monitor, expiry_state_handle as obs_expiry_state_handle,
|
||||
object_store_handle as obs_resolve_object_store_handle, transition_state_handle as obs_transition_state_handle,
|
||||
global_tier_config_mgr as obs_global_tier_config_mgr, object_store_handle as obs_resolve_object_store_handle,
|
||||
transition_state_handle as obs_transition_state_handle,
|
||||
};
|
||||
pub(crate) use rustfs_ecstore::api::storage::ECStore as ObsStore;
|
||||
use rustfs_storage_api as storage_contracts;
|
||||
@@ -534,6 +536,54 @@ pub(crate) async fn obs_replication_site_stats_snapshot(current_data_transfer_ra
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal counter tuple bridged from `ecstore` tier snapshots.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ObsTierCounter {
|
||||
pub(crate) total_size: u64,
|
||||
pub(crate) num_objects: u64,
|
||||
pub(crate) num_versions: u64,
|
||||
}
|
||||
|
||||
/// Snapshot configured remote tiers (`name -> lowercase tier_type`) without
|
||||
/// holding the tier config read lock across downstream work.
|
||||
pub(crate) async fn obs_configured_remote_tier_types() -> HashMap<String, String> {
|
||||
let tier_config_mgr = obs_global_tier_config_mgr();
|
||||
let guard = tier_config_mgr.read().await;
|
||||
guard
|
||||
.list_tiers()
|
||||
.into_iter()
|
||||
.map(|tier| (tier.name, tier.tier_type.as_lowercase()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Snapshot this node's rolling 24-hour tier transition counters, aged forward
|
||||
/// to the current UTC hour so expired bins drop out even when no new
|
||||
/// transitions have committed recently.
|
||||
pub(crate) fn obs_local_tier_daily_stats() -> HashMap<String, ObsTierCounter> {
|
||||
let now_ring = ObsLastDayTierStats::default();
|
||||
age_local_tier_daily_stats(obs_transition_state_handle().get_daily_all_tier_stats(), &now_ring)
|
||||
}
|
||||
|
||||
fn age_local_tier_daily_stats(
|
||||
stats: HashMap<String, ObsLastDayTierStats>,
|
||||
now_ring: &ObsLastDayTierStats,
|
||||
) -> HashMap<String, ObsTierCounter> {
|
||||
stats
|
||||
.into_iter()
|
||||
.map(|(tier, ring)| {
|
||||
let total = ring.merge(now_ring.clone()).total();
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: total.total_size,
|
||||
num_objects: total.num_objects,
|
||||
num_versions: total.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -774,17 +824,72 @@ mod tests {
|
||||
assert_eq!(snapshot.durable_mrf_backlog_count, 0);
|
||||
assert_eq!(snapshot.durable_mrf_backlog_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_local_tier_daily_stats_expires_bins_older_than_24_hours() {
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::TierDailyStatsWire;
|
||||
|
||||
let now_unix = 1_700_100_000_i64;
|
||||
let empty_bins = ObsLastDayTierStats::default().to_wire().bins;
|
||||
let now_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: empty_bins.clone(),
|
||||
updated_at_unix_secs: now_unix,
|
||||
})
|
||||
.expect("current reference ring should decode");
|
||||
|
||||
let mut stale_bins = empty_bins.clone();
|
||||
stale_bins[0].total_size = 4096;
|
||||
stale_bins[0].num_versions = 3;
|
||||
stale_bins[0].num_objects = 2;
|
||||
let stale_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: stale_bins,
|
||||
updated_at_unix_secs: now_unix - 25 * 3600,
|
||||
})
|
||||
.expect("stale ring should decode");
|
||||
|
||||
let fresh_updated = now_unix - 2 * 3600;
|
||||
let fresh_hour = usize::try_from((fresh_updated / 3600).rem_euclid(24)).expect("hour fits in usize");
|
||||
let mut fresh_bins = empty_bins;
|
||||
fresh_bins[fresh_hour].total_size = 2048;
|
||||
fresh_bins[fresh_hour].num_versions = 2;
|
||||
fresh_bins[fresh_hour].num_objects = 1;
|
||||
let fresh_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: fresh_bins,
|
||||
updated_at_unix_secs: fresh_updated,
|
||||
})
|
||||
.expect("fresh ring should decode");
|
||||
|
||||
let aged = age_local_tier_daily_stats(
|
||||
HashMap::from([("STALE".to_string(), stale_ring), ("FRESH".to_string(), fresh_ring)]),
|
||||
&now_ring,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
aged.get("STALE"),
|
||||
Some(&ObsTierCounter::default()),
|
||||
"bins older than 24h must age to zero"
|
||||
);
|
||||
assert_eq!(
|
||||
aged.get("FRESH"),
|
||||
Some(&ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 1,
|
||||
num_versions: 2,
|
||||
}),
|
||||
"recent bins still inside the 24h window must be preserved"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod metrics {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, BucketOptions, StorageAdminApi};
|
||||
|
||||
pub(crate) use super::{
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_expiry_state_handle,
|
||||
obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free,
|
||||
obs_is_disk_compression_enabled, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot,
|
||||
obs_replication_site_stats_snapshot, obs_resolve_object_store_handle, obs_transition_state_handle,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -471,6 +471,187 @@ mod tests {
|
||||
provider.shutdown().expect("shut down bucket usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros() {
|
||||
use crate::metrics::collectors::{
|
||||
TierInventoryEntry, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_usage_metrics,
|
||||
};
|
||||
|
||||
let (provider, exporter, mut snapshot) = setup_unscoped();
|
||||
|
||||
let extract_tier_points = |points: &[ExportedPoint], metric_name: &str| {
|
||||
let mut entries = points
|
||||
.iter()
|
||||
.filter(|point| point.name == metric_name)
|
||||
.map(|point| {
|
||||
let tier = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier")
|
||||
.expect("tier metric must carry tier attribute")
|
||||
.value
|
||||
.to_string();
|
||||
let tier_type = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier_type")
|
||||
.expect("tier metric must carry tier_type attribute")
|
||||
.value
|
||||
.to_string();
|
||||
(tier, tier_type, point.value)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
entries
|
||||
};
|
||||
|
||||
// 1. Accounted snapshot with two configured remote tiers.
|
||||
let initial = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![
|
||||
TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 8192,
|
||||
objects_count: 4,
|
||||
versions_count: 6,
|
||||
},
|
||||
TierInventoryEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 2,
|
||||
versions_count: 3,
|
||||
},
|
||||
],
|
||||
transitions_last24h: vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&initial))
|
||||
.expect("publish initial tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must be exported")
|
||||
.value,
|
||||
1.0
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![
|
||||
("ARCHIVE".into(), "s3".into(), 8192.0),
|
||||
("COLD".into(), "rustfs".into(), 4096.0),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 4.0), ("COLD".into(), "rustfs".into(), 2.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_versions_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 6.0), ("COLD".into(), "rustfs".into(), 3.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 2048.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
|
||||
// 2. Removing COLD and decreasing ARCHIVE inventory stops exporting COLD immediately.
|
||||
let decreased = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
versions_count: 1,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&decreased))
|
||||
.expect("publish decreased tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
|
||||
// 3. Becoming unaccounted flips accounted to 0 and withdraws inventory gauges without emitting zeros.
|
||||
let unaccounted = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: Vec::new(),
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&unaccounted))
|
||||
.expect("publish unaccounted tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must stay exported with value 0")
|
||||
.value,
|
||||
0.0
|
||||
);
|
||||
for metric_name in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
extract_tier_points(&points, metric_name).is_empty(),
|
||||
"{metric_name} must be withdrawn when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 512.0)]
|
||||
);
|
||||
|
||||
// 4. Removing the last configured tier withdraws all tier gauges cleanly.
|
||||
snapshot
|
||||
.replace(Vec::new())
|
||||
.expect("clear tier snapshot when no remote tiers remain");
|
||||
assert!(flush(&provider, &exporter).is_empty());
|
||||
|
||||
provider.shutdown().expect("shut down tier usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_or_stalled_collection_cannot_refresh_last_success_or_export_old_points() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Tier Stats Contract
|
||||
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`.
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request, inventory snapshot, or rolling transition counter.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`, `crates/obs/src/metrics/collectors/tier.rs`, `crates/obs/src/metrics/stats_collector.rs`, `crates/obs/src/metrics/scheduler.rs`.
|
||||
|
||||
## Two quantities, never one
|
||||
|
||||
@@ -41,3 +41,15 @@ The label set is closed by two enums in `crates/scanner-metrics/src/metrics.rs`:
|
||||
`timeout` and `cancelled` are recognised from `std::io::ErrorKind`, never from an error message, so a message that mentions an endpoint cannot reach a label. Until the transition client grows bounded deadlines (rustfs/backlog#2204), few failures actually carry `TimedOut`, so most land in `backend_error`; the classification is the seam that work extends, not a claim that timeouts are already distinguishable.
|
||||
|
||||
The outcome classifies the request only. A transition whose remote PUT succeeded and whose local commit then failed is a `success` here: the remote service did perform the request, and recording it as a tier failure would hide a leaked remote object behind an apparent backend outage. Local commit failure is observable through the ILM task-event metrics instead.
|
||||
|
||||
## Tier inventory and transition metrics
|
||||
|
||||
Periodic OTLP gauges in `crates/obs/src/metrics/schema/tier.rs` expose the same two quantities as `GET /rustfs/admin/v3/tier-stats` whenever at least one remote tier is configured:
|
||||
|
||||
- **Cluster-wide stored inventory** — `rustfs_tier_inventory_bytes`, `rustfs_tier_inventory_objects_count`, and `rustfs_tier_inventory_versions_count` carry `tier` and `tier_type` labels for configured remote tiers present in `DataUsageInfo::tier_stats`. Local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and unconfigured tiers are excluded so summing cold-tier inventory does not include hot local data.
|
||||
- **Inventory accounting status** — `rustfs_tier_inventory_accounted` (unlabeled, snapshot-wide) reports `1` when the persisted usage snapshot carries `tier_stats` and `0` when it is `not-accounted` or `unavailable`. Whenever status is `0` or a configured tier is absent from `DataUsageInfo::tier_stats`, per-tier inventory gauges are omitted and never fabricated as `0`.
|
||||
- **Node-local rolling 24h activity** — `rustfs_tier_transitions_last24h_bytes` and `rustfs_tier_transitions_last24h_objects_count` carry `tier` and `tier_type` labels and export each node's local `LastDayTierStats` ring aged forward to the current UTC hour (`merge(LastDayTierStats::default())`). Exporting node-local values avoids periodic all-to-all internode RPCs during metric scrapes; Prometheus/OTLP consumers sum across reporting nodes (`sum by (rustfs_cluster_id, tier, tier_type)`).
|
||||
|
||||
Unlike hot-path request counters (`rustfs_tier_requests_*`), these periodic snapshot gauges carry configured remote tier names (`tier`) and lowercase provider types (`tier_type`), matching the bounded cardinality of configured tiers. Endpoints, credentials, and object keys remain strictly forbidden as labels.
|
||||
|
||||
Inventory and transition gauges are published through an unscoped `StorageSnapshotMetrics` instance without zero tombstones: removing a tier or losing inventory accounting withdraws the series immediately rather than emitting synthetic zeros. See [bucket usage metrics](../operations/bucket-usage-metrics.md#remote-tier-inventory-and-transition-metrics) for query examples and the relationship to `rustfs_cluster_usage_buckets_total_bytes`.
|
||||
|
||||
@@ -104,6 +104,47 @@ usage snapshot. A shorter scrape interval cannot repair an incomplete scanner
|
||||
snapshot. The scanner publication and cache path is shared with the Console's
|
||||
usage display.
|
||||
|
||||
## Remote tier inventory and transition metrics
|
||||
|
||||
When at least one remote tier is configured, RustFS exports six OpenTelemetry gauges aligned with `GET /rustfs/admin/v3/tier-stats` (see [tier stats contract](../architecture/tier-stats-contract.md)) from the same cached scanner usage snapshot and local 24-hour transition ring:
|
||||
|
||||
| Metric | Labels | Scope | Admin API mapping (`GET /rustfs/admin/v3/tier-stats`) |
|
||||
|---|---|---|---|
|
||||
| `rustfs_tier_inventory_bytes` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.totalSize` |
|
||||
| `rustfs_tier_inventory_objects_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numObjects` |
|
||||
| `rustfs_tier_inventory_versions_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numVersions` |
|
||||
| `rustfs_tier_inventory_accounted` | *(none)* | Cluster-wide snapshot | `1` when `inventory.status == "accounted"`, else `0` |
|
||||
| `rustfs_tier_transitions_last24h_bytes` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.totalSize` |
|
||||
| `rustfs_tier_transitions_last24h_objects_count` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.numObjects` |
|
||||
|
||||
### How bucket usage, local disk capacity, and cold-tier inventory relate
|
||||
|
||||
- **Bucket logical usage** (`rustfs_cluster_usage_buckets_total_bytes`) counts logical bytes across retained versions in the bucket, including versions transitioned to remote tiers (excluding delete markers and erasure-coding overhead).
|
||||
- **Remote tier inventory** (`rustfs_tier_inventory_bytes`) is the subset of logical bytes currently accounted on a configured remote tier. It excludes local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and does not reconcile the entire remote bucket's physical billing total outside RustFS accounting.
|
||||
- **Local physical or usable disk capacity** reflects data stored on local cluster drives (including erasure-coding parity and compression) and excludes object payloads already transitioned to remote tiers.
|
||||
|
||||
### Querying remote tier gauges
|
||||
|
||||
Because every node exports the same cluster-wide inventory snapshot, deduplicate reporting nodes instead of summing them, and guard queries with `rustfs_tier_inventory_accounted == 1`:
|
||||
|
||||
```promql
|
||||
max by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_inventory_bytes{rustfs_cluster_id="production-a"}
|
||||
) and on (rustfs_cluster_id) (
|
||||
max by (rustfs_cluster_id) (rustfs_tier_inventory_accounted{rustfs_cluster_id="production-a"}) == 1
|
||||
)
|
||||
```
|
||||
|
||||
Because each node exports only its own committed transitions from the rolling 24-hour ring (aged forward to the current UTC hour), sum across reporting nodes for the cluster total:
|
||||
|
||||
```promql
|
||||
sum by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_transitions_last24h_bytes{rustfs_cluster_id="production-a"}
|
||||
)
|
||||
```
|
||||
|
||||
When `inventory.status` is `not-accounted` or `unavailable`, or when a newly configured tier has not yet appeared in the scanner snapshot, RustFS omits `rustfs_tier_inventory_{bytes,objects_count,versions_count}` rather than publishing `0`. When no remote tiers are configured, none of these six gauges are exported.
|
||||
|
||||
## Regression checks
|
||||
|
||||
The SDK test uses the production bucket collector and an actual OpenTelemetry
|
||||
@@ -114,6 +155,12 @@ usage, and removal from subsequent exports:
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_bucket_size_and_object_count_as_current_gauges --lib
|
||||
```
|
||||
|
||||
The tier SDK regression test verifies accounted remote-tier inventory, decreasing values, tier removal, and withdrawal of inventory gauges when the snapshot becomes unaccounted:
|
||||
|
||||
```bash
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros --lib
|
||||
```
|
||||
|
||||
The PromQL fixture checks same-name buckets in separate clusters and multiple
|
||||
reporting nodes. Run it from `.docker/observability/tests`:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user