mz_ore/
panic.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
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 in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Panic utilities.
17
18use std::any::Any;
19use std::backtrace::Backtrace;
20use std::borrow::Cow;
21use std::cell::RefCell;
22use std::fs::File;
23use std::io::{self, Write as _};
24use std::os::fd::FromRawFd;
25use std::panic::{self, UnwindSafe};
26use std::process;
27use std::sync::{Arc, Mutex};
28use std::time::Duration;
29use std::{env, thread};
30
31#[cfg(feature = "chrono")]
32use chrono::Utc;
33use itertools::Itertools;
34#[cfg(feature = "async")]
35use tokio::task_local;
36
37use crate::iter::IteratorExt;
38
39thread_local! {
40    static CATCHING_UNWIND: RefCell<bool> = const { RefCell::new(false) };
41}
42
43#[cfg(feature = "async")]
44task_local! {
45    pub(crate) static CATCHING_UNWIND_ASYNC: bool;
46}
47
48/// Overwrites the default panic handler with an enhanced panic handler.
49///
50/// The enhanced panic handler:
51///
52///   * Always emits a backtrace, regardless of how `RUST_BACKTRACE` was
53///     configured.
54///
55///   * Writes to stderr as atomically as possible, to minimize interleaving
56///     with concurrent log messages.
57///
58///   * Reports panics to Sentry.
59///
60///     Sentry installs its own panic hook by default that reports the panic and
61///     then forwards it to the previous panic hook. We can't use that hook
62///     because it would also report panics that we catch-unwind afterwards.
63///     Instead we are invoking the Sentry integration manually here, after the
64///     catch-unwind check.
65///
66///   * Instructs the entire process to abort if any thread panics.
67///
68///     By default, when a thread panics in Rust, only that thread is affected,
69///     and other threads continue running unaffected. This is a bad default. In
70///     almost all programs, thread panics are unexpected, unrecoverable, and
71///     leave the overall program in an invalid state. It is therefore typically
72///     less confusing to abort the entire program.
73///
74///     For example, consider a simple program with two threads communicating
75///     through a channel, where the first thread is waiting for the second
76///     thread to send a value over the channel. If the second thread panics,
77///     the first thread will block forever for a value that will never be
78///     produced. Blocking forever will be more confusing to the end user than
79///     aborting the program entirely.
80///
81/// Note that after calling this function, computations in which a panic is
82/// expected must use the special [`catch_unwind`] function in this module to
83/// recover. Note that the `catch_unwind` function in the standard library is
84/// **not** compatible with this improved panic handler.
85pub fn install_enhanced_handler() {
86    panic::set_hook(Box::new(move |panic_info| {
87        // If we're catching an unwind, do nothing to let the unwind handler
88        // run.
89        let catching_unwind = CATCHING_UNWIND.with(|v| *v.borrow());
90        #[cfg(feature = "async")]
91        let catching_unwind_async = CATCHING_UNWIND_ASYNC.try_with(|v| *v).unwrap_or(false);
92        #[cfg(not(feature = "async"))]
93        let catching_unwind_async = false;
94        if catching_unwind || catching_unwind_async {
95            return;
96        }
97
98        // can't use if cfg!() here because that will require chrono::Utc import
99        #[cfg(feature = "chrono")]
100        let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%S%.6fZ  ").to_string();
101        #[cfg(not(feature = "chrono"))]
102        let timestamp = String::new();
103
104        let thread = thread::current();
105        let thread_name = thread.name().unwrap_or("<unnamed>");
106
107        let msg = match panic_info.payload().downcast_ref::<&'static str>() {
108            Some(s) => *s,
109            None => match panic_info.payload().downcast_ref::<String>() {
110                Some(s) => &s[..],
111                None => "Box<Any>",
112            },
113        };
114
115        let location = if let Some(loc) = panic_info.location() {
116            loc.to_string()
117        } else {
118            "<unknown>".to_string()
119        };
120
121        // We unconditionally collect and display a short backtrace, as there's
122        // no practical situation where producing a backtrace in a panic message
123        // is undesirable. Panics are always unexpected, and we don't want to
124        // miss our chance to give ourselves as much context as possible.
125        //
126        // We do support `RUST_BACKTRACE=full` to display a full backtrace
127        // rather than a short backtrace that omits the frames from the runtime
128        // and the panic handler itslef.
129        let mut backtrace = Backtrace::force_capture().to_string();
130        if env::var("RUST_BACKTRACE").as_deref() != Ok("full") {
131            // Rust doesn't provide an API for generating a short backtrace, so
132            // we have to string munge it ourselves. The relevant frames are
133            // between the call to `backtrace::__rust_begin_short_backtrace` and
134            // `backtrace::__rust_end_short_backtrace`, which are easy to sniff
135            // out. To make this string munging as robust as possible, if we
136            // don't find the first marker frame, we  leave the full backtrace
137            // in place.
138            let mut lines = backtrace.lines();
139            if lines
140                .find(|l| l.contains("backtrace::__rust_end_short_backtrace"))
141                .is_some()
142            {
143                lines.next();
144                backtrace = lines
145                    .take_while(|l| !l.contains("backtrace::__rust_begin_short_backtrace"))
146                    .chain_one("note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.\n")
147                    .join("\n");
148            }
149        };
150
151        // Rust uses an unbuffered stderr stream. Build the message in a buffer
152        // first so that we minimize the number of calls to the underlying
153        // `write(2)` system call. This minimizes the chance of (but does not
154        // outright prevent) interleaving output with C or C++ libraries that
155        // may be writing to the stderr stream outside of the Rust runtime.
156        //
157        // See https://github.com/rust-lang/rust/issues/64413 for details.
158        let buf = format!(
159            "{timestamp}thread '{thread_name}' panicked at {location}:\n{msg}\n{backtrace}"
160        );
161
162        // Ideal path: spawn a thread that attempts to lock the Rust-managed
163        // stderr stream and write the panic message there. Acquiring the stderr
164        // lock prevents interleaving with concurrent output from the `tracing`
165        // crate, because `tracing` also acquires the lock before printing
166        // output.
167        //
168        // We put the ideal path in a thread because there is no guarantee that
169        // we'll be able to acquire the lock in a timely fashion, and there is
170        // no API to specify a time out for the lock call.
171        let buf = Arc::new(Mutex::new(Some(buf)));
172        thread::spawn({
173            let buf = Arc::clone(&buf);
174            move || {
175                let mut stderr = io::stderr().lock();
176                let mut buf = buf.lock().unwrap();
177                if let Some(buf) = buf.take() {
178                    let _ = stderr.write_all(buf.as_bytes());
179                }
180
181                // Abort while still holding the stderr lock to ensure the panic
182                // is the last output printed to stderr.
183                process::abort();
184            }
185        });
186
187        // Backup path: wait one second for the ideal path to succeed, then
188        // write the panic message directly to the underlying stderr stream
189        // (file descriptor 2) if it wasn't already written by the ideal path.
190        // This ensures we eventually eke out a panic message, possibly
191        // interleaved with other output, even if another thread is wedged while
192        // holding the stderr lock.
193        thread::sleep(Duration::from_secs(1));
194        let mut buf = buf.lock().unwrap();
195        if let Some(buf) = buf.take() {
196            let mut stderr = unsafe { File::from_raw_fd(2) };
197            let _ = stderr.write_all(buf.as_bytes());
198        }
199
200        // Report the panic to Sentry.
201        sentry_panic::panic_handler(panic_info);
202
203        process::abort();
204    }))
205}
206
207/// Like [`std::panic::catch_unwind`], but can unwind panics even if
208/// [`install_enhanced_handler`] has been called.
209pub fn catch_unwind<F, R>(f: F) -> Result<R, Box<dyn Any + Send + 'static>>
210where
211    F: FnOnce() -> R + UnwindSafe,
212{
213    CATCHING_UNWIND.with(|catching_unwind| {
214        *catching_unwind.borrow_mut() = true;
215        #[allow(clippy::disallowed_methods)]
216        let res = panic::catch_unwind(f);
217        *catching_unwind.borrow_mut() = false;
218        res
219    })
220}
221
222/// Like [`crate::panic::catch_unwind`], but downcasts the returned `Box<dyn Any>` error to a
223/// string which is almost always is.
224///
225/// See: <https://doc.rust-lang.org/stable/std/panic/struct.PanicHookInfo.html#method.payload>
226pub fn catch_unwind_str<F, R>(f: F) -> Result<R, Cow<'static, str>>
227where
228    F: FnOnce() -> R + UnwindSafe,
229{
230    match crate::panic::catch_unwind(f) {
231        Ok(res) => Ok(res),
232        Err(opaque) => match opaque.downcast_ref::<&'static str>() {
233            Some(s) => Err(Cow::Borrowed(*s)),
234            None => match opaque.downcast_ref::<String>() {
235                Some(s) => Err(Cow::Owned(s.to_owned())),
236                None => Err(Cow::Borrowed("Box<Any>")),
237            },
238        },
239    }
240}