use crate::{AppConfig, GlobalError, OtelConfig, OtelGuard, telemetry::init_telemetry};
use std::sync::{Arc, Mutex};
use tokio::sync::OnceCell;
use tracing::{info, warn};
const LOG_COMPONENT_OBS: &str = "obs";
const LOG_SUBSYSTEM_GLOBAL: &str = "global";
const EVENT_OBS_GLOBAL_STATE: &str = "obs_global_state";
static GLOBAL_GUARD: OnceCell<Arc<Mutex<Option<OtelGuard>>>> = OnceCell::const_new();
pub(crate) static OBSERVABILITY_METRIC_ENABLED: OnceCell<bool> = OnceCell::const_new();
pub(crate) const METRIC_LOG_CLEANER_DELETED_FILES_TOTAL: &str = "rustfs_log_cleaner_deleted_files_total";
pub(crate) const METRIC_LOG_CLEANER_FREED_BYTES_TOTAL: &str = "rustfs_log_cleaner_freed_bytes_total";
pub(crate) const METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS: &str = "rustfs_log_cleaner_compress_duration_seconds";
pub(crate) const METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE: &str = "rustfs_log_cleaner_steal_success_rate";
pub(crate) const METRIC_LOG_CLEANER_RUNS_TOTAL: &str = "rustfs_log_cleaner_runs_total";
pub(crate) const METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL: &str = "rustfs_log_cleaner_run_failures_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_TOTAL: &str = "rustfs_log_cleaner_rotation_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL: &str = "rustfs_log_cleaner_rotation_failures_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS: &str = "rustfs_log_cleaner_rotation_duration_seconds";
pub(crate) const METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES: &str = "rustfs_log_cleaner_active_file_size_bytes";
pub fn observability_metric_enabled() -> bool {
OBSERVABILITY_METRIC_ENABLED.get().copied().unwrap_or(false)
}
pub(crate) fn set_observability_metric_enabled(enabled: bool) {
if OBSERVABILITY_METRIC_ENABLED.set(enabled).is_err()
&& let Some(current) = OBSERVABILITY_METRIC_ENABLED.get()
&& *current != enabled
{
warn!(
event = EVENT_OBS_GLOBAL_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_GLOBAL,
current = *current,
requested = enabled,
result = "metrics_flag_already_initialized",
"obs global state changed"
);
}
}
pub async fn init_obs(endpoint: Option<String>) -> Result<OtelGuard, GlobalError> {
let config = AppConfig::new_with_endpoint(endpoint);
init_obs_with_config(&config.observability).await
}
pub async fn init_obs_with_config(config: &OtelConfig) -> Result<OtelGuard, GlobalError> {
let otel_guard = init_telemetry(config)?;
Ok(otel_guard)
}
pub fn set_global_guard(guard: OtelGuard) -> Result<(), GlobalError> {
info!(
event = EVENT_OBS_GLOBAL_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_GLOBAL,
state = "guard_initializing",
"obs global state changed"
);
GLOBAL_GUARD
.set(Arc::new(Mutex::new(Some(guard))))
.map_err(GlobalError::SetError)
}
pub fn get_global_guard() -> Result<Arc<Mutex<Option<OtelGuard>>>, GlobalError> {
GLOBAL_GUARD.get().cloned().ok_or(GlobalError::NotInitialized)
}
pub fn shutdown_global_guard() -> Result<(), GlobalError> {
let guard_handle = get_global_guard()?;
let guard = {
let mut slot = guard_handle
.lock()
.map_err(|_| GlobalError::GuardPoisoned("global observability guard"))?;
slot.take()
};
drop(guard);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const README: &str = include_str!("../README.md");
const GRAFANA_DASHBOARD: &str = include_str!("../../../.docker/observability/grafana/dashboards/rustfs.json");
#[tokio::test]
async fn test_get_uninitialized_guard() {
let result = get_global_guard();
assert!(matches!(result, Err(GlobalError::NotInitialized)));
}
#[test]
fn test_log_cleaner_metric_constants_use_rustfs_prefix() {
let metrics = [
METRIC_LOG_CLEANER_DELETED_FILES_TOTAL,
METRIC_LOG_CLEANER_FREED_BYTES_TOTAL,
METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS,
METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE,
METRIC_LOG_CLEANER_RUNS_TOTAL,
METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_TOTAL,
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES,
];
for metric in metrics {
assert!(
metric.starts_with("rustfs_log_cleaner_"),
"metric '{metric}' should use rustfs_log_cleaner_* namespace"
);
}
}
#[test]
fn test_readme_contains_grafana_dashboard_draft_section() {
assert!(README.contains("## Cleaner & Rotation Metrics"));
assert!(README.contains("### Grafana Dashboard JSON Draft (Ready to Import)"));
assert!(README.contains("\"uid\": \"rustfs-log-cleaner\""));
assert!(README.contains("rustfs_log_cleaner_runs_total"));
assert!(README.contains("rustfs_log_cleaner_rotation_failures_total"));
}
#[test]
fn test_readme_contains_promql_templates_section() {
assert!(README.contains("### PromQL Templates"));
assert!(README.contains("Cleanup failure ratio"));
assert!(README.contains("histogram_quantile(0.95"));
assert!(README.contains("max(rustfs_log_cleaner_active_file_size_bytes)"));
}
#[test]
fn test_grafana_dashboard_contains_log_cleaner_row() {
assert!(GRAFANA_DASHBOARD.contains("\"title\": \"Log Cleaner\""));
assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_runs_total"));
assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_rotation_failures_total"));
assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_active_file_size_bytes"));
}
#[test]
fn test_grafana_dashboard_deduplicates_cluster_bucket_usage() {
assert!(GRAFANA_DASHBOARD.contains("max by (job, bucket) (rustfs_cluster_usage_buckets_objects_count"));
assert!(GRAFANA_DASHBOARD.contains("max by (job, bucket) (rustfs_cluster_usage_buckets_total_bytes"));
assert!(!GRAFANA_DASHBOARD.contains("sum by (bucket) (rustfs_bucket_api_objects_total"));
assert!(!GRAFANA_DASHBOARD.contains("sum by (bucket) (rustfs_bucket_api_usage_bytes"));
}
#[test]
fn test_readme_mentions_deployed_dashboard_path() {
assert!(README.contains(".docker/observability/grafana/dashboards/rustfs.json"));
assert!(README.contains("row title: `Log Cleaner`"));
}
#[test]
fn test_init_obs_with_config_signature_is_correct() {
fn _type_check() {
let config = OtelConfig::default();
let _future = init_obs_with_config(&config);
}
}
}