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