1use crate::{AppConfig, GlobalError, OtelConfig, OtelGuard, telemetry::init_telemetry};
16use std::sync::{Arc, Mutex};
17use tokio::sync::OnceCell;
18use tracing::{info, warn};
19
20const LOG_COMPONENT_OBS: &str = "obs";
21const LOG_SUBSYSTEM_GLOBAL: &str = "global";
22const EVENT_OBS_GLOBAL_STATE: &str = "obs_global_state";
23
24static GLOBAL_GUARD: OnceCell<Arc<Mutex<Option<OtelGuard>>>> = OnceCell::const_new();
26
27pub(crate) static OBSERVABILITY_METRIC_ENABLED: OnceCell<bool> = OnceCell::const_new();
29
30pub(crate) const METRIC_LOG_CLEANER_DELETED_FILES_TOTAL: &str = "rustfs_log_cleaner_deleted_files_total";
32pub(crate) const METRIC_LOG_CLEANER_FREED_BYTES_TOTAL: &str = "rustfs_log_cleaner_freed_bytes_total";
33pub(crate) const METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS: &str = "rustfs_log_cleaner_compress_duration_seconds";
34pub(crate) const METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE: &str = "rustfs_log_cleaner_steal_success_rate";
35pub(crate) const METRIC_LOG_CLEANER_RUNS_TOTAL: &str = "rustfs_log_cleaner_runs_total";
36pub(crate) const METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL: &str = "rustfs_log_cleaner_run_failures_total";
37pub(crate) const METRIC_LOG_CLEANER_ROTATION_TOTAL: &str = "rustfs_log_cleaner_rotation_total";
38pub(crate) const METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL: &str = "rustfs_log_cleaner_rotation_failures_total";
39pub(crate) const METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS: &str = "rustfs_log_cleaner_rotation_duration_seconds";
40pub(crate) const METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES: &str = "rustfs_log_cleaner_active_file_size_bytes";
41
42pub fn observability_metric_enabled() -> bool {
44 OBSERVABILITY_METRIC_ENABLED.get().copied().unwrap_or(false)
45}
46
47pub(crate) fn set_observability_metric_enabled(enabled: bool) {
52 if OBSERVABILITY_METRIC_ENABLED.set(enabled).is_err()
53 && let Some(current) = OBSERVABILITY_METRIC_ENABLED.get()
54 && *current != enabled
55 {
56 warn!(
57 event = EVENT_OBS_GLOBAL_STATE,
58 component = LOG_COMPONENT_OBS,
59 subsystem = LOG_SUBSYSTEM_GLOBAL,
60 current = *current,
61 requested = enabled,
62 result = "metrics_flag_already_initialized",
63 "obs global state changed"
64 );
65 }
66}
67
68pub async fn init_obs(endpoint: Option<String>) -> Result<OtelGuard, GlobalError> {
89 let config = AppConfig::new_with_endpoint(endpoint);
91 init_obs_with_config(&config.observability).await
92}
93
94pub async fn init_obs_with_config(config: &OtelConfig) -> Result<OtelGuard, GlobalError> {
126 let otel_guard = init_telemetry(config)?;
127 Ok(otel_guard)
129}
130
131pub fn set_global_guard(guard: OtelGuard) -> Result<(), GlobalError> {
154 info!(
155 event = EVENT_OBS_GLOBAL_STATE,
156 component = LOG_COMPONENT_OBS,
157 subsystem = LOG_SUBSYSTEM_GLOBAL,
158 state = "guard_initializing",
159 "obs global state changed"
160 );
161 GLOBAL_GUARD
162 .set(Arc::new(Mutex::new(Some(guard))))
163 .map_err(GlobalError::SetError)
164}
165
166pub fn get_global_guard() -> Result<Arc<Mutex<Option<OtelGuard>>>, GlobalError> {
184 GLOBAL_GUARD.get().cloned().ok_or(GlobalError::NotInitialized)
185}
186
187pub fn shutdown_global_guard() -> Result<(), GlobalError> {
189 let guard_handle = get_global_guard()?;
190 let guard = {
191 let mut slot = guard_handle
192 .lock()
193 .map_err(|_| GlobalError::GuardPoisoned("global observability guard"))?;
194 slot.take()
195 };
196 drop(guard);
197 Ok(())
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 const README: &str = include_str!("../README.md");
205 const GRAFANA_DASHBOARD: &str = include_str!("../../../.docker/observability/grafana/dashboards/rustfs.json");
206
207 #[tokio::test]
208 async fn test_get_uninitialized_guard() {
209 let result = get_global_guard();
210 assert!(matches!(result, Err(GlobalError::NotInitialized)));
211 }
212
213 #[test]
214 fn test_log_cleaner_metric_constants_use_rustfs_prefix() {
215 let metrics = [
216 METRIC_LOG_CLEANER_DELETED_FILES_TOTAL,
217 METRIC_LOG_CLEANER_FREED_BYTES_TOTAL,
218 METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS,
219 METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE,
220 METRIC_LOG_CLEANER_RUNS_TOTAL,
221 METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL,
222 METRIC_LOG_CLEANER_ROTATION_TOTAL,
223 METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL,
224 METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
225 METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES,
226 ];
227
228 for metric in metrics {
229 assert!(
230 metric.starts_with("rustfs_log_cleaner_"),
231 "metric '{metric}' should use rustfs_log_cleaner_* namespace"
232 );
233 }
234 }
235
236 #[test]
237 fn test_readme_contains_grafana_dashboard_draft_section() {
238 assert!(README.contains("## Cleaner & Rotation Metrics"));
239 assert!(README.contains("### Grafana Dashboard JSON Draft (Ready to Import)"));
240 assert!(README.contains("\"uid\": \"rustfs-log-cleaner\""));
241 assert!(README.contains("rustfs_log_cleaner_runs_total"));
242 assert!(README.contains("rustfs_log_cleaner_rotation_failures_total"));
243 }
244
245 #[test]
246 fn test_readme_contains_promql_templates_section() {
247 assert!(README.contains("### PromQL Templates"));
248 assert!(README.contains("Cleanup failure ratio"));
249 assert!(README.contains("histogram_quantile(0.95"));
250 assert!(README.contains("max(rustfs_log_cleaner_active_file_size_bytes)"));
251 }
252
253 #[test]
254 fn test_grafana_dashboard_contains_log_cleaner_row() {
255 assert!(GRAFANA_DASHBOARD.contains("\"title\": \"Log Cleaner\""));
256 assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_runs_total"));
257 assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_rotation_failures_total"));
258 assert!(GRAFANA_DASHBOARD.contains("rustfs_log_cleaner_active_file_size_bytes"));
259 }
260
261 #[test]
262 fn test_grafana_dashboard_deduplicates_cluster_bucket_usage() {
263 assert!(GRAFANA_DASHBOARD.contains("max by (job, bucket) (rustfs_cluster_usage_buckets_objects_count"));
264 assert!(GRAFANA_DASHBOARD.contains("max by (job, bucket) (rustfs_cluster_usage_buckets_total_bytes"));
265 assert!(!GRAFANA_DASHBOARD.contains("sum by (bucket) (rustfs_bucket_api_objects_total"));
266 assert!(!GRAFANA_DASHBOARD.contains("sum by (bucket) (rustfs_bucket_api_usage_bytes"));
267 }
268
269 #[test]
270 fn test_readme_mentions_deployed_dashboard_path() {
271 assert!(README.contains(".docker/observability/grafana/dashboards/rustfs.json"));
272 assert!(README.contains("row title: `Log Cleaner`"));
273 }
274
275 #[test]
276 fn test_init_obs_with_config_signature_is_correct() {
277 fn _type_check() {
282 let config = OtelConfig::default();
283 let _future = init_obs_with_config(&config);
284 }
285 }
286}