Line data Source code
1 : //! Spawns and kills background processes that are needed by Neon CLI.
2 : //! Applies common set-up such as log and pid files (if needed) to every process.
3 : //!
4 : //! Neon CLI does not run in background, so it needs to store the information about
5 : //! spawned processes, which it does in this module.
6 : //! We do that by storing the pid of the process in the "${process_name}.pid" file.
7 : //! The pid file can be created by the process itself
8 : //! (Neon storage binaries do that and also ensure that a lock is taken onto that file)
9 : //! or we create such file after starting the process
10 : //! (non-Neon binaries don't necessarily follow our pidfile conventions).
11 : //! The pid stored in the file is later used to stop the service.
12 : //!
13 : //! See the [`lock_file`](utils::lock_file) module for more info.
14 :
15 : use std::ffi::OsStr;
16 : use std::io::Write;
17 : use std::os::unix::prelude::AsRawFd;
18 : use std::os::unix::process::CommandExt;
19 : use std::path::Path;
20 : use std::process::Command;
21 : use std::time::Duration;
22 : use std::{fs, io, thread};
23 :
24 : use anyhow::Context;
25 : use camino::{Utf8Path, Utf8PathBuf};
26 : use nix::errno::Errno;
27 : use nix::fcntl::{FcntlArg, FdFlag};
28 : use nix::sys::signal::{kill, Signal};
29 : use nix::unistd::Pid;
30 : use utils::pid_file::{self, PidFileRead};
31 :
32 : // These constants control the loop used to poll for process start / stop.
33 : //
34 : // The loop waits for at most 10 seconds, polling every 100 ms.
35 : // Once a second, it prints a dot ("."), to give the user an indication that
36 : // it's waiting. If the process hasn't started/stopped after 5 seconds,
37 : // it prints a notice that it's taking long, but keeps waiting.
38 : //
39 : const RETRY_UNTIL_SECS: u64 = 10;
40 : const RETRIES: u64 = (RETRY_UNTIL_SECS * 1000) / RETRY_INTERVAL_MILLIS;
41 : const RETRY_INTERVAL_MILLIS: u64 = 100;
42 : const DOT_EVERY_RETRIES: u64 = 10;
43 : const NOTICE_AFTER_RETRIES: u64 = 50;
44 :
45 : /// Argument to `start_process`, to indicate whether it should create pidfile or if the process creates
46 : /// it itself.
47 : pub enum InitialPidFile {
48 : /// Create a pidfile, to allow future CLI invocations to manipulate the process.
49 : Create(Utf8PathBuf),
50 : /// The process will create the pidfile itself, need to wait for that event.
51 : Expect(Utf8PathBuf),
52 : }
53 :
54 : /// Start a background child process using the parameters given.
55 0 : pub async fn start_process<F, Fut, AI, A, EI>(
56 0 : process_name: &str,
57 0 : datadir: &Path,
58 0 : command: &Path,
59 0 : args: AI,
60 0 : envs: EI,
61 0 : initial_pid_file: InitialPidFile,
62 0 : process_status_check: F,
63 0 : ) -> anyhow::Result<()>
64 0 : where
65 0 : F: Fn() -> Fut,
66 0 : Fut: std::future::Future<Output = anyhow::Result<bool>>,
67 0 : AI: IntoIterator<Item = A>,
68 0 : A: AsRef<OsStr>,
69 0 : // Not generic AsRef<OsStr>, otherwise empty `envs` prevents type inference
70 0 : EI: IntoIterator<Item = (String, String)>,
71 0 : {
72 0 : let log_path = datadir.join(format!("{process_name}.log"));
73 0 : let process_log_file = fs::OpenOptions::new()
74 0 : .create(true)
75 0 : .append(true)
76 0 : .open(&log_path)
77 0 : .with_context(|| {
78 0 : format!("Could not open {process_name} log file {log_path:?} for writing")
79 0 : })?;
80 0 : let same_file_for_stderr = process_log_file.try_clone().with_context(|| {
81 0 : format!("Could not reuse {process_name} log file {log_path:?} for writing stderr")
82 0 : })?;
83 :
84 0 : let mut command = Command::new(command);
85 0 : let background_command = command
86 0 : .stdout(process_log_file)
87 0 : .stderr(same_file_for_stderr)
88 0 : .args(args);
89 0 :
90 0 : let filled_cmd = fill_env_vars_prefixed_neon(fill_remote_storage_secrets_vars(
91 0 : fill_rust_env_vars(background_command),
92 0 : ));
93 0 : filled_cmd.envs(envs);
94 :
95 0 : let pid_file_to_check = match &initial_pid_file {
96 0 : InitialPidFile::Create(path) => {
97 0 : pre_exec_create_pidfile(filled_cmd, path);
98 0 : path
99 : }
100 0 : InitialPidFile::Expect(path) => path,
101 : };
102 :
103 0 : let spawned_process = filled_cmd.spawn().with_context(|| {
104 0 : format!("Could not spawn {process_name}, see console output and log files for details.")
105 0 : })?;
106 0 : let pid = spawned_process.id();
107 0 : let pid = Pid::from_raw(
108 0 : i32::try_from(pid)
109 0 : .with_context(|| format!("Subprocess {process_name} has invalid pid {pid}"))?,
110 : );
111 : // set up a scopeguard to kill & wait for the child in case we panic or bail below
112 0 : let spawned_process = scopeguard::guard(spawned_process, |mut spawned_process| {
113 0 : println!("SIGKILL & wait the started process");
114 0 : (|| {
115 0 : // TODO: use another signal that can be caught by the child so it can clean up any children it spawned (e..g, walredo).
116 0 : spawned_process.kill().context("SIGKILL child")?;
117 0 : spawned_process.wait().context("wait() for child process")?;
118 0 : anyhow::Ok(())
119 0 : })()
120 0 : .with_context(|| format!("scopeguard kill&wait child {process_name:?}"))
121 0 : .unwrap();
122 0 : });
123 :
124 0 : for retries in 0..RETRIES {
125 0 : match process_started(pid, pid_file_to_check, &process_status_check).await {
126 : Ok(true) => {
127 0 : println!("\n{process_name} started and passed status check, pid: {pid}");
128 0 : // leak the child process, it'll outlive this neon_local invocation
129 0 : drop(scopeguard::ScopeGuard::into_inner(spawned_process));
130 0 : return Ok(());
131 : }
132 : Ok(false) => {
133 0 : if retries == NOTICE_AFTER_RETRIES {
134 0 : // The process is taking a long time to start up. Keep waiting, but
135 0 : // print a message
136 0 : print!("\n{process_name} has not started yet, continuing to wait");
137 0 : }
138 0 : if retries % DOT_EVERY_RETRIES == 0 {
139 0 : print!(".");
140 0 : io::stdout().flush().unwrap();
141 0 : }
142 0 : thread::sleep(Duration::from_millis(RETRY_INTERVAL_MILLIS));
143 : }
144 0 : Err(e) => {
145 0 : println!("error starting process {process_name:?}: {e:#}");
146 0 : return Err(e);
147 : }
148 : }
149 : }
150 0 : println!();
151 0 : anyhow::bail!(
152 0 : "{process_name} did not start+pass status checks within {RETRY_UNTIL_SECS} seconds"
153 0 : );
154 0 : }
155 :
156 : /// Stops the process, using the pid file given. Returns Ok also if the process is already not running.
157 0 : pub fn stop_process(
158 0 : immediate: bool,
159 0 : process_name: &str,
160 0 : pid_file: &Utf8Path,
161 0 : ) -> anyhow::Result<()> {
162 0 : let pid = match pid_file::read(pid_file)
163 0 : .with_context(|| format!("read pid_file {pid_file:?}"))?
164 : {
165 : PidFileRead::NotExist => {
166 0 : println!("{process_name} is already stopped: no pid file present at {pid_file:?}");
167 0 : return Ok(());
168 : }
169 : PidFileRead::NotHeldByAnyProcess(_) => {
170 : // Don't try to kill according to file contents beacuse the pid might have been re-used by another process.
171 : // Don't delete the file either, it can race with new pid file creation.
172 : // Read `pid_file` module comment for details.
173 0 : println!(
174 0 : "No process is holding the pidfile. The process must have already exited. Leave in place to avoid race conditions: {pid_file:?}"
175 0 : );
176 0 : return Ok(());
177 : }
178 0 : PidFileRead::LockedByOtherProcess(pid) => pid,
179 : };
180 : // XXX the pid could become invalid (and recycled) at any time before the kill() below.
181 :
182 : // send signal
183 0 : let sig = if immediate {
184 0 : print!("Stopping {process_name} with pid {pid} immediately..");
185 0 : Signal::SIGQUIT
186 : } else {
187 0 : print!("Stopping {process_name} with pid {pid} gracefully..");
188 0 : Signal::SIGTERM
189 : };
190 0 : io::stdout().flush().unwrap();
191 0 : match kill(pid, sig) {
192 0 : Ok(()) => (),
193 : Err(Errno::ESRCH) => {
194 : // Again, don't delete the pid file. The unlink can race with a new pid file being created.
195 0 : println!(
196 0 : "{process_name} with pid {pid} does not exist, but a pid file {pid_file:?} was found. Likely the pid got recycled. Lucky we didn't harm anyone."
197 0 : );
198 0 : return Ok(());
199 : }
200 0 : Err(e) => anyhow::bail!("Failed to send signal to {process_name} with pid {pid}: {e}"),
201 : }
202 :
203 : // Wait until process is gone
204 0 : wait_until_stopped(process_name, pid)?;
205 0 : Ok(())
206 0 : }
207 :
208 0 : pub fn wait_until_stopped(process_name: &str, pid: Pid) -> anyhow::Result<()> {
209 0 : for retries in 0..RETRIES {
210 0 : match process_has_stopped(pid) {
211 : Ok(true) => {
212 0 : println!("\n{process_name} stopped");
213 0 : return Ok(());
214 : }
215 : Ok(false) => {
216 0 : if retries == NOTICE_AFTER_RETRIES {
217 0 : // The process is taking a long time to start up. Keep waiting, but
218 0 : // print a message
219 0 : print!("\n{process_name} has not stopped yet, continuing to wait");
220 0 : }
221 0 : if retries % DOT_EVERY_RETRIES == 0 {
222 0 : print!(".");
223 0 : io::stdout().flush().unwrap();
224 0 : }
225 0 : thread::sleep(Duration::from_millis(RETRY_INTERVAL_MILLIS));
226 : }
227 0 : Err(e) => {
228 0 : println!("{process_name} with pid {pid} failed to stop: {e:#}");
229 0 : return Err(e);
230 : }
231 : }
232 : }
233 0 : println!();
234 0 : anyhow::bail!("{process_name} with pid {pid} did not stop in {RETRY_UNTIL_SECS} seconds");
235 0 : }
236 :
237 0 : fn fill_rust_env_vars(cmd: &mut Command) -> &mut Command {
238 0 : // If RUST_BACKTRACE is set, pass it through. But if it's not set, default
239 0 : // to RUST_BACKTRACE=1.
240 0 : let backtrace_setting = std::env::var_os("RUST_BACKTRACE");
241 0 : let backtrace_setting = backtrace_setting
242 0 : .as_deref()
243 0 : .unwrap_or_else(|| OsStr::new("1"));
244 0 :
245 0 : let mut filled_cmd = cmd.env_clear().env("RUST_BACKTRACE", backtrace_setting);
246 :
247 : // Pass through these environment variables to the command
248 0 : for var in ["LLVM_PROFILE_FILE", "FAILPOINTS", "RUST_LOG"] {
249 0 : if let Some(val) = std::env::var_os(var) {
250 0 : filled_cmd = filled_cmd.env(var, val);
251 0 : }
252 : }
253 :
254 0 : filled_cmd
255 0 : }
256 :
257 0 : fn fill_remote_storage_secrets_vars(mut cmd: &mut Command) -> &mut Command {
258 0 : for env_key in [
259 : "AWS_ACCESS_KEY_ID",
260 0 : "AWS_SECRET_ACCESS_KEY",
261 0 : "AWS_PROFILE",
262 0 : // HOME is needed in combination with `AWS_PROFILE` to pick up the SSO sessions.
263 0 : "HOME",
264 0 : "AZURE_STORAGE_ACCOUNT",
265 0 : "AZURE_STORAGE_ACCESS_KEY",
266 : ] {
267 0 : if let Ok(value) = std::env::var(env_key) {
268 0 : cmd = cmd.env(env_key, value);
269 0 : }
270 : }
271 0 : cmd
272 0 : }
273 :
274 0 : fn fill_env_vars_prefixed_neon(mut cmd: &mut Command) -> &mut Command {
275 0 : for (var, val) in std::env::vars() {
276 0 : if var.starts_with("NEON_PAGESERVER_") {
277 0 : cmd = cmd.env(var, val);
278 0 : }
279 : }
280 0 : cmd
281 0 : }
282 :
283 : /// Add a `pre_exec` to the cmd that, inbetween fork() and exec(),
284 : /// 1. Claims a pidfile with a fcntl lock on it and
285 : /// 2. Sets up the pidfile's file descriptor so that it (and the lock)
286 : /// will remain held until the cmd exits.
287 0 : fn pre_exec_create_pidfile<P>(cmd: &mut Command, path: P) -> &mut Command
288 0 : where
289 0 : P: Into<Utf8PathBuf>,
290 0 : {
291 0 : let path: Utf8PathBuf = path.into();
292 0 : // SAFETY:
293 0 : // pre_exec is marked unsafe because it runs between fork and exec.
294 0 : // Why is that dangerous in various ways?
295 0 : // Long answer: https://github.com/rust-lang/rust/issues/39575
296 0 : // Short answer: in a multi-threaded program, other threads may have
297 0 : // been inside of critical sections at the time of fork. In the
298 0 : // original process, that was allright, assuming they protected
299 0 : // the critical sections appropriately, e.g., through locks.
300 0 : // Fork adds another process to the mix that
301 0 : // 1. Has a single thread T
302 0 : // 2. In an exact copy of the address space at the time of fork.
303 0 : // A variety of problems scan occur now:
304 0 : // 1. T tries to grab a lock that was locked at the time of fork.
305 0 : // It will wait forever since in its address space, the lock
306 0 : // is in state 'taken' but the thread that would unlock it is
307 0 : // not there.
308 0 : // 2. A rust object that represented some external resource in the
309 0 : // parent now got implicitly copied by the fork, even though
310 0 : // the object's type is not `Copy`. The parent program may use
311 0 : // non-copyability as way to enforce unique ownership of an
312 0 : // external resource in the typesystem. The fork breaks that
313 0 : // assumption, as now both parent and child process have an
314 0 : // owned instance of the object that represents the same
315 0 : // underlying resource.
316 0 : // While these seem like niche problems, (1) in particular is
317 0 : // highly relevant. For example, `malloc()` may grab a mutex internally,
318 0 : // and so, if we forked while another thread was mallocing' and our
319 0 : // pre_exec closure allocates as well, it will block on the malloc
320 0 : // mutex forever
321 0 : //
322 0 : // The proper solution is to only use C library functions that are marked
323 0 : // "async-signal-safe": https://man7.org/linux/man-pages/man7/signal-safety.7.html
324 0 : //
325 0 : // With this specific pre_exec() closure, the non-error path doesn't allocate.
326 0 : // The error path uses `anyhow`, and hence does allocate.
327 0 : // We take our chances there, hoping that any potential disaster is constrained
328 0 : // to the child process (e.g., malloc has no state ourside of the child process).
329 0 : // Last, `expect` prints to stderr, and stdio is not async-signal-safe.
330 0 : // Again, we take our chances, making the same assumptions as for malloc.
331 0 : unsafe {
332 0 : cmd.pre_exec(move || {
333 0 : let file = pid_file::claim_for_current_process(&path).expect("claim pid file");
334 0 : // Remove the FD_CLOEXEC flag on the pidfile descriptor so that the pidfile
335 0 : // remains locked after exec.
336 0 : nix::fcntl::fcntl(file.as_raw_fd(), FcntlArg::F_SETFD(FdFlag::empty()))
337 0 : .expect("remove FD_CLOEXEC");
338 0 : // Don't run drop(file), it would close the file before we actually exec.
339 0 : std::mem::forget(file);
340 0 : Ok(())
341 0 : });
342 0 : }
343 0 : cmd
344 0 : }
345 :
346 0 : async fn process_started<F, Fut>(
347 0 : pid: Pid,
348 0 : pid_file_to_check: &Utf8Path,
349 0 : status_check: &F,
350 0 : ) -> anyhow::Result<bool>
351 0 : where
352 0 : F: Fn() -> Fut,
353 0 : Fut: std::future::Future<Output = anyhow::Result<bool>>,
354 0 : {
355 0 : match status_check().await {
356 0 : Ok(true) => match pid_file::read(pid_file_to_check)? {
357 0 : PidFileRead::NotExist => Ok(false),
358 0 : PidFileRead::LockedByOtherProcess(pid_in_file) => Ok(pid_in_file == pid),
359 0 : PidFileRead::NotHeldByAnyProcess(_) => Ok(false),
360 : },
361 0 : Ok(false) => Ok(false),
362 0 : Err(e) => anyhow::bail!("process failed to start: {e}"),
363 : }
364 0 : }
365 :
366 0 : fn process_has_stopped(pid: Pid) -> anyhow::Result<bool> {
367 0 : match kill(pid, None) {
368 : // Process exists, keep waiting
369 0 : Ok(_) => Ok(false),
370 : // Process not found, we're done
371 0 : Err(Errno::ESRCH) => Ok(true),
372 0 : Err(err) => anyhow::bail!("Failed to send signal to process with pid {pid}: {err}"),
373 : }
374 0 : }
|