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 : if !datadir.metadata().context("stat datadir")?.is_dir() {
73 0 : anyhow::bail!("`datadir` must be a directory when calling this function: {datadir:?}");
74 0 : }
75 0 : let log_path = datadir.join(format!("{process_name}.log"));
76 0 : let process_log_file = fs::OpenOptions::new()
77 0 : .create(true)
78 0 : .append(true)
79 0 : .open(&log_path)
80 0 : .with_context(|| {
81 0 : format!("Could not open {process_name} log file {log_path:?} for writing")
82 0 : })?;
83 0 : let same_file_for_stderr = process_log_file.try_clone().with_context(|| {
84 0 : format!("Could not reuse {process_name} log file {log_path:?} for writing stderr")
85 0 : })?;
86 :
87 0 : let mut command = Command::new(command);
88 0 : let background_command = command
89 0 : .stdout(process_log_file)
90 0 : .stderr(same_file_for_stderr)
91 0 : .args(args)
92 0 : // spawn all child processes in their datadir, useful for all kinds of things,
93 0 : // not least cleaning up child processes e.g. after an unclean exit from the test suite:
94 0 : // ```
95 0 : // lsof -d cwd -a +D Users/cs/src/neon/test_output
96 0 : // ```
97 0 : .current_dir(datadir);
98 0 :
99 0 : let filled_cmd = fill_env_vars_prefixed_neon(fill_remote_storage_secrets_vars(
100 0 : fill_rust_env_vars(background_command),
101 0 : ));
102 0 : filled_cmd.envs(envs);
103 :
104 0 : let pid_file_to_check = match &initial_pid_file {
105 0 : InitialPidFile::Create(path) => {
106 0 : pre_exec_create_pidfile(filled_cmd, path);
107 0 : path
108 : }
109 0 : InitialPidFile::Expect(path) => path,
110 : };
111 :
112 0 : let spawned_process = filled_cmd.spawn().with_context(|| {
113 0 : format!("Could not spawn {process_name}, see console output and log files for details.")
114 0 : })?;
115 0 : let pid = spawned_process.id();
116 0 : let pid = Pid::from_raw(
117 0 : i32::try_from(pid)
118 0 : .with_context(|| format!("Subprocess {process_name} has invalid pid {pid}"))?,
119 : );
120 : // set up a scopeguard to kill & wait for the child in case we panic or bail below
121 0 : let spawned_process = scopeguard::guard(spawned_process, |mut spawned_process| {
122 0 : println!("SIGKILL & wait the started process");
123 0 : (|| {
124 0 : // TODO: use another signal that can be caught by the child so it can clean up any children it spawned (e..g, walredo).
125 0 : spawned_process.kill().context("SIGKILL child")?;
126 0 : spawned_process.wait().context("wait() for child process")?;
127 0 : anyhow::Ok(())
128 0 : })()
129 0 : .with_context(|| format!("scopeguard kill&wait child {process_name:?}"))
130 0 : .unwrap();
131 0 : });
132 :
133 0 : for retries in 0..RETRIES {
134 0 : match process_started(pid, pid_file_to_check, &process_status_check).await {
135 : Ok(true) => {
136 0 : println!("\n{process_name} started and passed status check, pid: {pid}");
137 0 : // leak the child process, it'll outlive this neon_local invocation
138 0 : drop(scopeguard::ScopeGuard::into_inner(spawned_process));
139 0 : return Ok(());
140 : }
141 : Ok(false) => {
142 0 : if retries == NOTICE_AFTER_RETRIES {
143 0 : // The process is taking a long time to start up. Keep waiting, but
144 0 : // print a message
145 0 : print!("\n{process_name} has not started yet, continuing to wait");
146 0 : }
147 0 : if retries % DOT_EVERY_RETRIES == 0 {
148 0 : print!(".");
149 0 : io::stdout().flush().unwrap();
150 0 : }
151 0 : thread::sleep(Duration::from_millis(RETRY_INTERVAL_MILLIS));
152 : }
153 0 : Err(e) => {
154 0 : println!("error starting process {process_name:?}: {e:#}");
155 0 : return Err(e);
156 : }
157 : }
158 : }
159 0 : println!();
160 0 : anyhow::bail!(
161 0 : "{process_name} did not start+pass status checks within {RETRY_UNTIL_SECS} seconds"
162 0 : );
163 0 : }
164 :
165 : /// Stops the process, using the pid file given. Returns Ok also if the process is already not running.
166 0 : pub fn stop_process(
167 0 : immediate: bool,
168 0 : process_name: &str,
169 0 : pid_file: &Utf8Path,
170 0 : ) -> anyhow::Result<()> {
171 0 : let pid = match pid_file::read(pid_file)
172 0 : .with_context(|| format!("read pid_file {pid_file:?}"))?
173 : {
174 : PidFileRead::NotExist => {
175 0 : println!("{process_name} is already stopped: no pid file present at {pid_file:?}");
176 0 : return Ok(());
177 : }
178 : PidFileRead::NotHeldByAnyProcess(_) => {
179 : // Don't try to kill according to file contents beacuse the pid might have been re-used by another process.
180 : // Don't delete the file either, it can race with new pid file creation.
181 : // Read `pid_file` module comment for details.
182 0 : println!(
183 0 : "No process is holding the pidfile. The process must have already exited. Leave in place to avoid race conditions: {pid_file:?}"
184 0 : );
185 0 : return Ok(());
186 : }
187 0 : PidFileRead::LockedByOtherProcess(pid) => pid,
188 : };
189 : // XXX the pid could become invalid (and recycled) at any time before the kill() below.
190 :
191 : // send signal
192 0 : let sig = if immediate {
193 0 : print!("Stopping {process_name} with pid {pid} immediately..");
194 0 : Signal::SIGQUIT
195 : } else {
196 0 : print!("Stopping {process_name} with pid {pid} gracefully..");
197 0 : Signal::SIGTERM
198 : };
199 0 : io::stdout().flush().unwrap();
200 0 : match kill(pid, sig) {
201 0 : Ok(()) => (),
202 : Err(Errno::ESRCH) => {
203 : // Again, don't delete the pid file. The unlink can race with a new pid file being created.
204 0 : println!(
205 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."
206 0 : );
207 0 : return Ok(());
208 : }
209 0 : Err(e) => anyhow::bail!("Failed to send signal to {process_name} with pid {pid}: {e}"),
210 : }
211 :
212 : // Wait until process is gone
213 0 : wait_until_stopped(process_name, pid)?;
214 0 : Ok(())
215 0 : }
216 :
217 0 : pub fn wait_until_stopped(process_name: &str, pid: Pid) -> anyhow::Result<()> {
218 0 : for retries in 0..RETRIES {
219 0 : match process_has_stopped(pid) {
220 : Ok(true) => {
221 0 : println!("\n{process_name} stopped");
222 0 : return Ok(());
223 : }
224 : Ok(false) => {
225 0 : if retries == NOTICE_AFTER_RETRIES {
226 0 : // The process is taking a long time to start up. Keep waiting, but
227 0 : // print a message
228 0 : print!("\n{process_name} has not stopped yet, continuing to wait");
229 0 : }
230 0 : if retries % DOT_EVERY_RETRIES == 0 {
231 0 : print!(".");
232 0 : io::stdout().flush().unwrap();
233 0 : }
234 0 : thread::sleep(Duration::from_millis(RETRY_INTERVAL_MILLIS));
235 : }
236 0 : Err(e) => {
237 0 : println!("{process_name} with pid {pid} failed to stop: {e:#}");
238 0 : return Err(e);
239 : }
240 : }
241 : }
242 0 : println!();
243 0 : anyhow::bail!("{process_name} with pid {pid} did not stop in {RETRY_UNTIL_SECS} seconds");
244 0 : }
245 :
246 0 : fn fill_rust_env_vars(cmd: &mut Command) -> &mut Command {
247 0 : // If RUST_BACKTRACE is set, pass it through. But if it's not set, default
248 0 : // to RUST_BACKTRACE=1.
249 0 : let backtrace_setting = std::env::var_os("RUST_BACKTRACE");
250 0 : let backtrace_setting = backtrace_setting
251 0 : .as_deref()
252 0 : .unwrap_or_else(|| OsStr::new("1"));
253 0 :
254 0 : let mut filled_cmd = cmd.env_clear().env("RUST_BACKTRACE", backtrace_setting);
255 :
256 : // Pass through these environment variables to the command
257 0 : for var in ["LLVM_PROFILE_FILE", "FAILPOINTS", "RUST_LOG"] {
258 0 : if let Some(val) = std::env::var_os(var) {
259 0 : filled_cmd = filled_cmd.env(var, val);
260 0 : }
261 : }
262 :
263 0 : filled_cmd
264 0 : }
265 :
266 0 : fn fill_remote_storage_secrets_vars(mut cmd: &mut Command) -> &mut Command {
267 0 : for env_key in [
268 : "AWS_ACCESS_KEY_ID",
269 0 : "AWS_SECRET_ACCESS_KEY",
270 0 : "AWS_PROFILE",
271 0 : // HOME is needed in combination with `AWS_PROFILE` to pick up the SSO sessions.
272 0 : "HOME",
273 0 : "AZURE_STORAGE_ACCOUNT",
274 0 : "AZURE_STORAGE_ACCESS_KEY",
275 : ] {
276 0 : if let Ok(value) = std::env::var(env_key) {
277 0 : cmd = cmd.env(env_key, value);
278 0 : }
279 : }
280 0 : cmd
281 0 : }
282 :
283 0 : fn fill_env_vars_prefixed_neon(mut cmd: &mut Command) -> &mut Command {
284 0 : for (var, val) in std::env::vars() {
285 0 : if var.starts_with("NEON_PAGESERVER_") {
286 0 : cmd = cmd.env(var, val);
287 0 : }
288 : }
289 0 : cmd
290 0 : }
291 :
292 : /// Add a `pre_exec` to the cmd that, inbetween fork() and exec(),
293 : /// 1. Claims a pidfile with a fcntl lock on it and
294 : /// 2. Sets up the pidfile's file descriptor so that it (and the lock)
295 : /// will remain held until the cmd exits.
296 0 : fn pre_exec_create_pidfile<P>(cmd: &mut Command, path: P) -> &mut Command
297 0 : where
298 0 : P: Into<Utf8PathBuf>,
299 0 : {
300 0 : let path: Utf8PathBuf = path.into();
301 0 : // SAFETY:
302 0 : // pre_exec is marked unsafe because it runs between fork and exec.
303 0 : // Why is that dangerous in various ways?
304 0 : // Long answer: https://github.com/rust-lang/rust/issues/39575
305 0 : // Short answer: in a multi-threaded program, other threads may have
306 0 : // been inside of critical sections at the time of fork. In the
307 0 : // original process, that was allright, assuming they protected
308 0 : // the critical sections appropriately, e.g., through locks.
309 0 : // Fork adds another process to the mix that
310 0 : // 1. Has a single thread T
311 0 : // 2. In an exact copy of the address space at the time of fork.
312 0 : // A variety of problems scan occur now:
313 0 : // 1. T tries to grab a lock that was locked at the time of fork.
314 0 : // It will wait forever since in its address space, the lock
315 0 : // is in state 'taken' but the thread that would unlock it is
316 0 : // not there.
317 0 : // 2. A rust object that represented some external resource in the
318 0 : // parent now got implicitly copied by the fork, even though
319 0 : // the object's type is not `Copy`. The parent program may use
320 0 : // non-copyability as way to enforce unique ownership of an
321 0 : // external resource in the typesystem. The fork breaks that
322 0 : // assumption, as now both parent and child process have an
323 0 : // owned instance of the object that represents the same
324 0 : // underlying resource.
325 0 : // While these seem like niche problems, (1) in particular is
326 0 : // highly relevant. For example, `malloc()` may grab a mutex internally,
327 0 : // and so, if we forked while another thread was mallocing' and our
328 0 : // pre_exec closure allocates as well, it will block on the malloc
329 0 : // mutex forever
330 0 : //
331 0 : // The proper solution is to only use C library functions that are marked
332 0 : // "async-signal-safe": https://man7.org/linux/man-pages/man7/signal-safety.7.html
333 0 : //
334 0 : // With this specific pre_exec() closure, the non-error path doesn't allocate.
335 0 : // The error path uses `anyhow`, and hence does allocate.
336 0 : // We take our chances there, hoping that any potential disaster is constrained
337 0 : // to the child process (e.g., malloc has no state ourside of the child process).
338 0 : // Last, `expect` prints to stderr, and stdio is not async-signal-safe.
339 0 : // Again, we take our chances, making the same assumptions as for malloc.
340 0 : unsafe {
341 0 : cmd.pre_exec(move || {
342 0 : let file = pid_file::claim_for_current_process(&path).expect("claim pid file");
343 0 : // Remove the FD_CLOEXEC flag on the pidfile descriptor so that the pidfile
344 0 : // remains locked after exec.
345 0 : nix::fcntl::fcntl(file.as_raw_fd(), FcntlArg::F_SETFD(FdFlag::empty()))
346 0 : .expect("remove FD_CLOEXEC");
347 0 : // Don't run drop(file), it would close the file before we actually exec.
348 0 : std::mem::forget(file);
349 0 : Ok(())
350 0 : });
351 0 : }
352 0 : cmd
353 0 : }
354 :
355 0 : async fn process_started<F, Fut>(
356 0 : pid: Pid,
357 0 : pid_file_to_check: &Utf8Path,
358 0 : status_check: &F,
359 0 : ) -> anyhow::Result<bool>
360 0 : where
361 0 : F: Fn() -> Fut,
362 0 : Fut: std::future::Future<Output = anyhow::Result<bool>>,
363 0 : {
364 0 : match status_check().await {
365 0 : Ok(true) => match pid_file::read(pid_file_to_check)? {
366 0 : PidFileRead::NotExist => Ok(false),
367 0 : PidFileRead::LockedByOtherProcess(pid_in_file) => Ok(pid_in_file == pid),
368 0 : PidFileRead::NotHeldByAnyProcess(_) => Ok(false),
369 : },
370 0 : Ok(false) => Ok(false),
371 0 : Err(e) => anyhow::bail!("process failed to start: {e}"),
372 : }
373 0 : }
374 :
375 0 : fn process_has_stopped(pid: Pid) -> anyhow::Result<bool> {
376 0 : match kill(pid, None) {
377 : // Process exists, keep waiting
378 0 : Ok(_) => Ok(false),
379 : // Process not found, we're done
380 0 : Err(Errno::ESRCH) => Ok(true),
381 0 : Err(err) => anyhow::bail!("Failed to send signal to process with pid {pid}: {err}"),
382 : }
383 0 : }
|