Skip to main content

mz_ore/
process.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//! Process utilities.
17
18/// The exit code of [`halt!`](crate::halt).
19///
20/// Antithesis fails a run for every container exit code other than 0, 137 and
21/// 143, so its build flavor halts with 143, the exit code of a SIGTERM.
22pub const HALT_EXIT_CODE: i32 = if cfg!(feature = "antithesis") {
23    143
24} else {
25    166
26};
27
28/// The exit code of [`restart_in_place!`](crate::restart_in_place).
29///
30/// This is `EX_TEMPFAIL` from `sysexits.h`. Shells, tini and Kubernetes report
31/// a process killed by signal N as exit code 128 + N, so a code below 128 can
32/// only come from an explicit exit.
33pub const RESTART_IN_PLACE_EXIT_CODE: i32 = 75;
34
35/// Halts the process.
36///
37/// `halt` forwards the provided arguments to the [`tracing::warn`] macro, then
38/// terminates the process with [`HALT_EXIT_CODE`].
39///
40/// Halting a process is a middle ground between a graceful shutdown and a
41/// panic. Use halts for errors that are severe enough to require shutting down
42/// the process, but not severe enough to be considered a crash. Halts are not
43/// intended to be reported to error tracking tools (e.g., Sentry).
44///
45/// There are two common classes of errors that trigger a halt:
46///
47///   * An error that indicates a new process has taken over (e.g., an error
48///     indicating that the process's leader epoch has expired).
49///
50///   * A retriable error where granular retry logic would be tricky enough to
51///     write that it has not yet been worth it. Since restarting from a fresh
52///     process must *always* be correct, forcing a restart is an easy way to
53///     tap into the existing whole-process retry logic. Use halt judiciously in
54///     these cases, as restarting a process can be inefficient (e.g., mandatory
55///     restart backoff, rehydrating expensive state).
56#[cfg_attr(nightly_doc_features, doc(cfg(feature = "tracing")))]
57#[cfg(feature = "tracing")]
58#[macro_export]
59macro_rules! halt {
60    ($($arg:expr),* $(,)?) => {{
61        $crate::__private::tracing::warn!("halting process: {}", format!($($arg),*));
62        $crate::process::exit_thread_safe($crate::process::HALT_EXIT_CODE);
63    }}
64}
65
66/// Halts the process and asks its supervisor to restart it in place.
67///
68/// `restart_in_place` behaves like [`halt!`](crate::halt), but terminates the
69/// process with [`RESTART_IN_PLACE_EXIT_CODE`]. The environmentd container
70/// entrypoint restarts the process right away on this exit code instead of
71/// exiting the container, which avoids Kubernetes crash backoff when a process
72/// halts repeatedly.
73///
74/// The restarted process runs even if Kubernetes has replaced the process's pod
75/// in the meantime, for example after a node failure. Only use this macro while
76/// the deployment is read-only, where the entrypoint's restart marker keeps the
77/// restarted process from booting writable next to the replacement. Use
78/// [`halt!`](crate::halt) everywhere else, in particular after the process has
79/// been fenced out.
80#[cfg_attr(nightly_doc_features, doc(cfg(feature = "tracing")))]
81#[cfg(feature = "tracing")]
82#[macro_export]
83macro_rules! restart_in_place {
84    ($($arg:expr),* $(,)?) => {{
85        $crate::__private::tracing::warn!("halting process for restart in place: {}", format!($($arg),*));
86        $crate::process::exit_thread_safe($crate::process::RESTART_IN_PLACE_EXIT_CODE);
87    }}
88}
89
90/// Prints the given message and exits the process.
91///
92/// `exit!` forwards the provided arguments to the [`tracing::info`] macro, then
93/// terminates the process with given exit code.
94#[cfg_attr(nightly_doc_features, doc(cfg(feature = "tracing")))]
95#[cfg(feature = "tracing")]
96#[macro_export]
97macro_rules! exit {
98    ($exit_code:literal, $($arg:expr),* $(,)?) => {{
99        $crate::__private::tracing::info!("exiting process (0): {}", format!($($arg),*));
100        $crate::process::exit_thread_safe($exit_code);
101    }};
102}
103
104/// Like [`halt!`], but exits with [`halt_exit_code`] of the given code, so that
105/// a restart with a specific cause can be told apart from a routine halt.
106#[cfg_attr(nightly_doc_features, doc(cfg(feature = "tracing")))]
107#[cfg(feature = "tracing")]
108pub fn halt_with_code(exit_code: i32, message: std::fmt::Arguments<'_>) -> ! {
109    crate::__private::tracing::warn!("halting process: {message}");
110    exit_thread_safe(halt_exit_code(exit_code))
111}
112
113/// The exit code [`halt_with_code`] uses for `exit_code`. The Antithesis build
114/// flavor always exits with [`HALT_EXIT_CODE`].
115pub const fn halt_exit_code(exit_code: i32) -> i32 {
116    if cfg!(feature = "antithesis") {
117        HALT_EXIT_CODE
118    } else {
119        exit_code
120    }
121}
122
123/// Helper for exiting macros.
124///
125/// This function exists to avoid that all callers of `halt!` have to explicitly depend on `libc`.
126pub fn exit_thread_safe(error_code: i32) -> ! {
127    // Using `std::process::exit` here would be unsound as that function invokes libc's `exit`
128    // function, which is not thread-safe [1]. There are two viable work arounds for this:
129    //
130    //  * Calling libc's `_exit` function instead, which is thread-safe by virtue of not performing
131    //    any cleanup work.
132    //  * Introducing a global lock to ensure only a single thread gets to call `exit` at a time.
133    //
134    // We chose the former approach because it's simpler and has the additional benefit of
135    // protecting us from third-party code that installs thread-unsafe exit handlers.
136    //
137    // Note that we are fine with not running any cleanup code here. This behaves just like an
138    // abort we'd do in response to a panic. Any code that relies on cleanup code to run before
139    // process termination is already unsound in the face of panics and hardware failure.
140    //
141    // [1]: https://github.com/rust-lang/rust/issues/126600
142    unsafe { libc::_exit(error_code) };
143}
144
145/// Sets the OS-level name of the calling thread, visible to tools like `top -H`, `perf`,
146/// `samply`, and `/proc/<pid>/task/*/comm`.
147///
148/// Linux truncates thread names to 15 bytes (16 with the NUL terminator); `name` is truncated to
149/// fit. Best-effort: a no-op on non-Linux platforms, and silently does nothing if the underlying
150/// syscall fails.
151pub fn set_current_thread_name(name: &str) {
152    #[cfg(target_os = "linux")]
153    {
154        let mut truncated = name.to_string();
155        while truncated.len() > 15 {
156            truncated.pop();
157        }
158        if let Ok(name) = std::ffi::CString::new(truncated) {
159            unsafe {
160                libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
161            }
162        }
163    }
164    #[cfg(not(target_os = "linux"))]
165    {
166        let _ = name;
167    }
168}