-
Notifications
You must be signed in to change notification settings - Fork 3
refactor: pid1-exe
#22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
polarathene
wants to merge
15
commits into
fpco:master
Choose a base branch
from
polarathene:refactor/pid1-exe
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
d10d4c5
docs: Fix typos in CLI arg descriptions
polarathene 7c98936
chore: Format `Pid1App` fields with blank lines
polarathene e69fbad
chore: Adjust `Pid1App` for consistency
polarathene 88b1d2e
chore(CLI): Display version and description
polarathene 3fb570f
feat(CLI): Make `--` optional
polarathene 0c3a281
refactor(CLI): Simplify parsing `--env` values
polarathene 8826642
chore: Minor revisions to `Pid1App`
polarathene 10f4860
chore: Don't support compiling for `windows`
polarathene aca116e
chore: Minor revisions for `Pid1App::run()`
polarathene 8742517
docs: README - Update `--help` output
polarathene 1c18457
chore: Improve DX
polarathene 64fe9b8
chore: Indent to 4 spaces
polarathene 9a96890
tests: Remove unecessary TTY assignment
polarathene db229d7
docs: Revise development guide
polarathene f143cb3
docs: Revise development guide
polarathene File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,104 +1,108 @@ | ||
| use clap::Parser; | ||
| #[cfg(target_family = "unix")] | ||
| use pid1::Pid1Settings; | ||
| #[cfg(target_family = "unix")] | ||
| use signal_hook::{ | ||
| consts::{SIGCHLD, SIGINT, SIGTERM}, | ||
| iterator::Signals, | ||
| }; | ||
| #[cfg(target_family = "unix")] | ||
| use std::os::unix::process::CommandExt; | ||
| #[cfg(target_family = "unix")] | ||
| use std::time::Duration; | ||
| use std::{error::Error, ffi::OsString, path::PathBuf}; | ||
| use std::{str::FromStr, ffi::OsString, path::PathBuf}; | ||
|
|
||
| #[derive(Parser, Debug, PartialEq)] | ||
| #[derive(clap::Parser, Debug, PartialEq)] | ||
| #[command(version, about, long_about = None)] | ||
| pub(crate) struct Pid1App { | ||
| /// Specify working direcory | ||
| /// Specify working directory | ||
| #[arg(short, long, value_name = "DIR")] | ||
| pub(crate) workdir: Option<PathBuf>, | ||
| /// Timeout (in seconds) to wait for child proess to exit | ||
| #[arg(short, long, value_name = "TIMEOUT", default_value_t = 2)] | ||
|
|
||
| /// Grace period for stopping before escalating to SIGKILL | ||
| #[arg(short, long, value_name = "SECONDS", default_value_t = 2)] | ||
| pub(crate) timeout: u8, | ||
|
|
||
| /// Turn on verbose output | ||
| #[arg(short, long, default_value_t = false)] | ||
| #[arg(short, long)] | ||
| pub(crate) verbose: bool, | ||
|
|
||
| /// Override environment variables. Can specify multiple times. | ||
| #[arg(short, long, value_parser=parse_key_val::<OsString, OsString>)] | ||
| pub(crate) env: Vec<(OsString, OsString)>, | ||
| #[arg(short, long, value_name = "KEY=VALUE")] | ||
| pub(crate) env: Vec<KeyValue>, | ||
|
|
||
| /// Run command with user ID | ||
| #[arg(short, long, value_name = "USER_ID")] | ||
| user_id: Option<u32>, | ||
| #[arg(short, long, value_name = "USER ID")] | ||
| pub(crate) user_id: Option<u32>, | ||
|
|
||
| /// Run command with group ID | ||
| #[arg(short, long, value_name = "GROUP_ID")] | ||
| group_id: Option<u32>, | ||
| #[arg(short, long, value_name = "GROUP ID")] | ||
| pub(crate) group_id: Option<u32>, | ||
|
|
||
| /// Process to run | ||
| #[arg(required = true)] | ||
| #[arg(trailing_var_arg = true)] | ||
| pub(crate) command: String, | ||
| /// Arguments to the process | ||
| #[arg(required = false)] | ||
|
|
||
| /// Arguments to that process | ||
| pub(crate) args: Vec<String>, | ||
| } | ||
|
|
||
| impl Pid1App { | ||
| #[cfg(target_family = "unix")] | ||
| /// Parses CLI arguments from the environment. | ||
| pub(crate) fn from_cli() -> Self { | ||
| use clap::Parser; | ||
| Self::parse() | ||
| } | ||
|
|
||
| pub(crate) fn run(self) -> ! { | ||
| let mut child = std::process::Command::new(&self.command); | ||
| let child = child.args(&self.args[..]); | ||
| let mut cmd = std::process::Command::new(&self.command); | ||
| cmd.args(&self.args); | ||
|
|
||
| if let Some(workdir) = &self.workdir { | ||
| child.current_dir(workdir); | ||
| cmd.current_dir(workdir); | ||
| } | ||
| if let Some(user_id) = &self.user_id { | ||
| child.uid(*user_id); | ||
| cmd.uid(*user_id); | ||
| } | ||
| if let Some(group_id) = &self.group_id { | ||
| child.gid(*group_id); | ||
| cmd.gid(*group_id); | ||
| } | ||
| for (key, value) in &self.env { | ||
| child.env(key, value); | ||
| for KeyValue(key, value) in &self.env { | ||
| cmd.env(key, value); | ||
| } | ||
|
|
||
| let pid = std::process::id(); | ||
| if pid != 1 { | ||
| let status = child.exec(); | ||
| let status = cmd.exec(); | ||
| eprintln!("execvp failed with: {status:?}"); | ||
|
|
||
| std::process::exit(1); | ||
| } else { | ||
| // Install signal handlers before launching child process | ||
| let signals = Signals::new([SIGTERM, SIGINT, SIGCHLD]).unwrap(); | ||
| let child = child.spawn(); | ||
| let child = match child { | ||
| Ok(child) => child, | ||
| Err(err) => { | ||
| eprintln!("pid1: {} spawn failed. Got error: {err}", self.command); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
|
|
||
| Pid1Settings::new() | ||
| .enable_log(self.verbose) | ||
| .timeout(Duration::from_secs(self.timeout.into())) | ||
| .pid1_handling(signals, child) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(target_family = "windows")] | ||
| pub(crate) fn run(self) -> ! { | ||
| eprintln!("pid1: Not supported on Windows"); | ||
| std::process::exit(1); | ||
| // CRITICAL: Install signal handlers BEFORE spawning the child. | ||
| // This prevents a race condition where a fast-failing child sends SIGCHLD | ||
| // before we are ready to catch and reap it, creating zombie processes. | ||
| let signals = Signals::new([SIGTERM, SIGINT, SIGCHLD]).unwrap(); | ||
|
|
||
| let child = cmd.spawn().unwrap_or_else(|err| { | ||
| eprintln!("pid1: {} spawn failed. Got error: {err}", self.command); | ||
| std::process::exit(1); | ||
| }); | ||
|
|
||
| Pid1Settings::new() | ||
| .enable_log(self.verbose) | ||
| .timeout(Duration::from_secs(self.timeout.into())) | ||
| .pid1_handling(signals, child) | ||
| } | ||
| } | ||
|
|
||
| /// Parse a single key-value pair | ||
| fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>> | ||
| where | ||
| T: std::str::FromStr, | ||
| T::Err: Error + Send + Sync + 'static, | ||
| U: std::str::FromStr, | ||
| U::Err: Error + Send + Sync + 'static, | ||
| { | ||
| let pos = s | ||
| .find('=') | ||
| .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?; | ||
| Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) | ||
| /// A CLI argument parsed from a `KEY=VALUE` pair. | ||
| #[derive(Debug, Clone, PartialEq)] | ||
| pub(crate) struct KeyValue(OsString, OsString); | ||
|
|
||
| impl FromStr for KeyValue { | ||
| type Err = String; | ||
|
|
||
| /// Parses a CLI flag value into a [`KeyValue`] type. | ||
| fn from_str(s: &str) -> Result<Self, Self::Err> { | ||
| let (key, value) = s.split_once('=') | ||
| .ok_or_else(|| format!("invalid `KEY=VALUE` pair: no `=` found in `{s}`"))?; | ||
|
|
||
| Ok(KeyValue(key.into(), value.into())) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,10 @@ | ||
| #[cfg(unix)] | ||
| mod cli; | ||
|
|
||
| use clap::Parser; | ||
|
|
||
| use crate::cli::Pid1App; | ||
|
|
||
| fn main() { | ||
| let cli = Pid1App::parse(); | ||
| cli.run() | ||
| #[cfg(unix)] | ||
| cli::Pid1App::from_cli().run(); | ||
|
|
||
| #[cfg(not(unix))] | ||
| compile_error!("`pid1` is only compatible with Unix-like operating systems."); | ||
|
polarathene marked this conversation as resolved.
Outdated
|
||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any reason why we are removing
required = true?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It can be added back if you prefer it for clarity.
I removed it as it is implicitly
trueas a default (for a positional arg). Similarly a positional arg of Vec is implicitlyrequired = false.