Skip to main content

rustfs_obs/telemetry/
guard.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
15//! RAII guard for OpenTelemetry provider lifecycle management.
16//!
17//! [`OtelGuard`] holds all runtime resources created during telemetry
18//! initialisation. Dropping it triggers an ordered shutdown:
19//!
20//! 1. Tracer provider — flushes pending spans.
21//! 2. Meter provider — flushes pending metrics.
22//! 3. Logger provider — flushes pending log records.
23//! 4. Profiling agent — flushes pending profiles.
24//! 5. Cleanup task — aborted to prevent lingering background work.
25//! 6. Tracing worker guard — flushes buffered log lines written by
26//!    `tracing_appender`.
27//! 7. Stdout worker guard — flushes buffered log lines written to stdout.
28
29use opentelemetry_sdk::{logs::SdkLoggerProvider, metrics::SdkMeterProvider, trace::SdkTracerProvider};
30use tracing::{debug, error};
31
32#[cfg(all(
33    feature = "pyroscope",
34    any(target_os = "macos", all(target_os = "linux", target_env = "gnu", target_arch = "x86_64"))
35))]
36pub(crate) type ProfilingAgent = pyroscope::PyroscopeAgent<pyroscope::pyroscope::PyroscopeAgentRunning>;
37#[cfg(not(all(
38    feature = "pyroscope",
39    any(target_os = "macos", all(target_os = "linux", target_env = "gnu", target_arch = "x86_64"))
40)))]
41pub(crate) type ProfilingAgent = ();
42
43const LOG_COMPONENT_OBS: &str = "obs";
44const LOG_SUBSYSTEM_GUARD: &str = "guard";
45const EVENT_OBS_GUARD_SHUTDOWN: &str = "obs_guard_shutdown";
46const STDERR_ERROR_PREFIX: &str = "[ERROR]";
47
48fn format_guard_shutdown_stderr_message(resource: &str, error: impl std::fmt::Display) -> String {
49    format!("{STDERR_ERROR_PREFIX} observability guard shutdown failed: resource={resource} error={error}")
50}
51
52/// RAII guard that owns all active OpenTelemetry providers and the
53/// `tracing_appender` worker guard.
54///
55/// Construct this via the `init_*` functions in [`crate::telemetry`] rather
56/// than directly.  The guard must be kept alive for the entire duration of the
57/// application — once dropped, all telemetry pipelines are shut down.
58pub struct OtelGuard {
59    /// Optional tracer provider for distributed tracing.
60    pub(crate) tracer_provider: Option<SdkTracerProvider>,
61    /// Optional meter provider for metrics collection.
62    pub(crate) meter_provider: Option<SdkMeterProvider>,
63    /// Optional logger provider for OTLP log export.
64    pub(crate) logger_provider: Option<SdkLoggerProvider>,
65    pub(crate) profiling_agent: Option<ProfilingAgent>,
66    /// Handle to the background log-cleanup task; aborted on drop.
67    pub(crate) cleanup_handle: Option<tokio::task::JoinHandle<()>>,
68    /// Worker guard that keeps the non-blocking `tracing_appender` thread
69    /// alive.  Dropping it blocks until all buffered records are flushed.
70    pub(crate) tracing_guard: Option<tracing_appender::non_blocking::WorkerGuard>,
71    /// Optional guard for stdout logging; kept separate to allow independent flushing and shutdown.
72    pub(crate) stdout_guard: Option<tracing_appender::non_blocking::WorkerGuard>,
73}
74
75impl std::fmt::Debug for OtelGuard {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        let mut s = f.debug_struct("OtelGuard");
78        s.field("tracer_provider", &self.tracer_provider.is_some())
79            .field("meter_provider", &self.meter_provider.is_some())
80            .field("logger_provider", &self.logger_provider.is_some())
81            .field("profiling_agent", &self.profiling_agent.is_some())
82            .field("cleanup_handle", &self.cleanup_handle.is_some())
83            .field("tracing_guard", &self.tracing_guard.is_some())
84            .field("stdout_guard", &self.stdout_guard.is_some())
85            .finish()
86    }
87}
88
89impl Drop for OtelGuard {
90    /// Shut down all telemetry providers in order.
91    ///
92    /// Errors are emitted before tracing resources are dropped so shutdown
93    /// diagnostics remain structured and low-noise.
94    fn drop(&mut self) {
95        if let Some(provider) = self.tracer_provider.take()
96            && let Err(err) = provider.shutdown()
97        {
98            if tracing::dispatcher::has_been_set() {
99                error!(
100                    event = EVENT_OBS_GUARD_SHUTDOWN,
101                    component = LOG_COMPONENT_OBS,
102                    subsystem = LOG_SUBSYSTEM_GUARD,
103                    resource = "tracer_provider",
104                    result = "shutdown_failed",
105                    error = %err,
106                    "observability guard shutdown failed"
107                );
108            } else {
109                eprintln!("{}", format_guard_shutdown_stderr_message("tracer_provider", err));
110            }
111        }
112
113        if let Some(provider) = self.meter_provider.take()
114            && let Err(err) = provider.shutdown()
115        {
116            if tracing::dispatcher::has_been_set() {
117                error!(
118                    event = EVENT_OBS_GUARD_SHUTDOWN,
119                    component = LOG_COMPONENT_OBS,
120                    subsystem = LOG_SUBSYSTEM_GUARD,
121                    resource = "meter_provider",
122                    result = "shutdown_failed",
123                    error = %err,
124                    "observability guard shutdown failed"
125                );
126            } else {
127                eprintln!("{}", format_guard_shutdown_stderr_message("meter_provider", err));
128            }
129        }
130
131        #[cfg(all(
132            feature = "pyroscope",
133            any(target_os = "macos", all(target_os = "linux", target_env = "gnu", target_arch = "x86_64"))
134        ))]
135        if let Some(agent) = self.profiling_agent.take() {
136            match agent.stop() {
137                Err(err) => {
138                    if tracing::dispatcher::has_been_set() {
139                        error!(
140                            event = EVENT_OBS_GUARD_SHUTDOWN,
141                            component = LOG_COMPONENT_OBS,
142                            subsystem = LOG_SUBSYSTEM_GUARD,
143                            resource = "profiling_agent",
144                            result = "shutdown_failed",
145                            error = %err,
146                            "observability guard shutdown failed"
147                        );
148                    } else {
149                        eprintln!("{}", format_guard_shutdown_stderr_message("profiling_agent", err));
150                    }
151                }
152                Ok(stopped) => {
153                    stopped.shutdown();
154                }
155            }
156        }
157
158        if let Some(handle) = self.cleanup_handle.take() {
159            debug!(
160                event = EVENT_OBS_GUARD_SHUTDOWN,
161                component = LOG_COMPONENT_OBS,
162                subsystem = LOG_SUBSYSTEM_GUARD,
163                resource = "log_cleaner",
164                result = "abort_requested",
165                "observability guard resource shutdown requested"
166            );
167            handle.abort();
168        }
169
170        if let Some(provider) = self.logger_provider.take()
171            && let Err(err) = provider.shutdown()
172        {
173            // After logger shutdown, the OTLP log bridge is no longer a reliable
174            // sink for its own failure path, so fall back to stderr.
175            // resource = "logger_provider"
176            eprintln!("{}", format_guard_shutdown_stderr_message("logger_provider", err));
177        }
178
179        if let Some(guard) = self.tracing_guard.take() {
180            debug!(
181                event = EVENT_OBS_GUARD_SHUTDOWN,
182                component = LOG_COMPONENT_OBS,
183                subsystem = LOG_SUBSYSTEM_GUARD,
184                resource = "tracing_guard",
185                result = "flush_requested",
186                "observability guard resource flush requested"
187            );
188            drop(guard);
189        }
190
191        if let Some(guard) = self.stdout_guard.take() {
192            debug!(
193                event = EVENT_OBS_GUARD_SHUTDOWN,
194                component = LOG_COMPONENT_OBS,
195                subsystem = LOG_SUBSYSTEM_GUARD,
196                resource = "stdout_guard",
197                result = "flush_requested",
198                "observability guard resource flush requested"
199            );
200            drop(guard);
201        }
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn test_guard_shutdown_stderr_message_is_actionable() {
211        let message = format_guard_shutdown_stderr_message("logger_provider", "flush failed");
212
213        assert!(message.starts_with(STDERR_ERROR_PREFIX));
214        assert!(message.contains("resource=logger_provider"));
215        assert!(message.contains("error=flush failed"));
216    }
217}