Skip to main content

rustfs_obs/
global.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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
24/// Global guard for OpenTelemetry tracing
25static GLOBAL_GUARD: OnceCell<Arc<Mutex<Option<OtelGuard>>>> = OnceCell::const_new();
26
27/// Flag indicating if observability metric is enabled
28pub(crate) static OBSERVABILITY_METRIC_ENABLED: OnceCell<bool> = OnceCell::const_new();
29
30/// Namespaced metrics for cleaner and rolling logging.
31pub(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
42/// Check whether Observability metric is enabled
43pub fn observability_metric_enabled() -> bool {
44    OBSERVABILITY_METRIC_ENABLED.get().copied().unwrap_or(false)
45}
46
47/// Set the global observability metrics flag once.
48///
49/// When this function is called multiple times, only the first value is kept
50/// and later values are ignored to preserve OnceCell semantics.
51pub(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
68/// Initialize the observability module
69///
70/// # Parameters
71/// - `config`: Configuration information
72///
73/// # Returns
74/// A tuple containing the logger and the telemetry guard
75///
76/// # Example
77/// ```no_run
78/// # use rustfs_obs::init_obs;
79///
80/// # #[tokio::main]
81/// # async fn main() {
82/// #    match init_obs(None).await {
83/// #         Ok(guard) => {}
84/// #         Err(e) => { eprintln!("Failed to initialize observability: {}", e); }
85/// #     }
86/// # }
87/// ```
88pub async fn init_obs(endpoint: Option<String>) -> Result<OtelGuard, GlobalError> {
89    // Load the configuration file
90    let config = AppConfig::new_with_endpoint(endpoint);
91    init_obs_with_config(&config.observability).await
92}
93
94/// Initialize the observability module with an explicit [`OtelConfig`].
95///
96/// This is the lower-level counterpart to [`init_obs`]: it accepts a fully
97/// constructed [`OtelConfig`] rather than building one from an endpoint URL.
98/// Useful when the config is already available (e.g., embedded in a larger
99/// application config struct) or when unit-testing with custom settings.
100///
101/// # Parameters
102/// - `config`: A pre-built [`OtelConfig`] to drive all telemetry backends.
103///
104/// # Returns
105/// An [`OtelGuard`] that must be kept alive for the lifetime of the
106/// application. Dropping it flushes and shuts down all providers.
107///
108/// # Errors
109/// Returns [`GlobalError`] when the underlying telemetry backend fails to
110/// initialise (e.g., cannot create the log directory, or an OTLP exporter
111/// cannot connect).
112///
113/// # Example
114/// ```no_run
115/// use rustfs_obs::{AppConfig, init_obs_with_config};
116///
117/// # #[tokio::main]
118/// # async fn main() {
119/// let config = AppConfig::new_with_endpoint(Some("http://localhost:4318".to_string()));
120/// let _guard = init_obs_with_config(&config.observability)
121///     .await
122///     .expect("observability init failed");
123/// # }
124/// ```
125pub async fn init_obs_with_config(config: &OtelConfig) -> Result<OtelGuard, GlobalError> {
126    let otel_guard = init_telemetry(config)?;
127    // Metrics runtime scheduling is exposed by rustfs_obs::init_metrics_runtime().
128    Ok(otel_guard)
129}
130
131/// Set the global guard for OtelGuard
132///
133/// # Arguments
134/// * `guard` - The OtelGuard instance to set globally
135///
136/// # Returns
137/// * `Ok(())` if successful
138/// * `Err(GuardError)` if setting fails
139///
140/// # Example
141/// ```no_run
142/// # use rustfs_obs::{ init_obs, set_global_guard};
143///
144/// # async fn init() -> Result<(), Box<dyn std::error::Error>> {
145/// #    let guard = match init_obs(None).await{
146/// #         Ok(g) => g,
147/// #         Err(e) => { return Err(Box::new(e)); }
148/// #    };
149/// #    set_global_guard(guard)?;
150/// #    Ok(())
151/// # }
152/// ```
153pub 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
166/// Get the global guard for OtelGuard
167///
168/// # Returns
169/// * `Ok(Arc<Mutex<Option<OtelGuard>>>>)` if guard exists
170/// * `Err(GuardError)` if guard not initialized
171///
172/// # Example
173/// ```no_run
174/// # use rustfs_obs::get_global_guard;
175///
176/// # async fn trace_operation() -> Result<(), Box<dyn std::error::Error>> {
177/// #    let guard = get_global_guard()?;
178/// #    let _lock = guard.lock().expect("operation should succeed");
179/// #    // Perform traced operation
180/// #    Ok(())
181/// # }
182/// ```
183pub fn get_global_guard() -> Result<Arc<Mutex<Option<OtelGuard>>>, GlobalError> {
184    GLOBAL_GUARD.get().cloned().ok_or(GlobalError::NotInitialized)
185}
186
187/// Explicitly drop the global guard so telemetry providers can flush before exit.
188pub 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        // Compile-time check: verifies that `init_obs_with_config` is public and
278        // accepts `&OtelConfig`, matching the README documentation.
279        // The future is created but intentionally not polled — this avoids
280        // initialising the global tracing subscriber in a unit-test context.
281        fn _type_check() {
282            let config = OtelConfig::default();
283            let _future = init_obs_with_config(&config);
284        }
285    }
286}