use std::{
env,
ffi::OsStr,
future::ready,
io::{self, Write},
path::{Path, PathBuf},
process::{self, Child, Command, ExitStatus},
time::Duration,
};
use serde::Serialize;
use time::{OffsetDateTime, SignedDuration};
use troll_core::{
Clock, Lease, LeaseGroup, LeaseGroupRequest, LeaseRequest, OperationError, Policy, Refused,
Store, SystemClock, UpdateError, component_env_name,
};
use crate::{
cli::WithCommand,
error::CliError,
output::{SCHEMA, stderr_json, timestamp},
platform::{self, StopSignal},
};
use super::{Context, inspect::allocation_snapshot, registry::holder};
const MAX_PROJECT_CHARS: usize = 64;
const MAX_PURPOSE_CHARS: usize = 120;
const UNKNOWN_NAME: &str = "unknown";
const SPAWN_FAILURE: i32 = 127;
const SIGNAL_EXIT_OFFSET: i32 = 128;
#[cfg(unix)]
const CHILD_POLL_INTERVAL: Duration = Duration::from_secs(1);
#[cfg(not(unix))]
const CHILD_POLL_INTERVAL: Duration = Duration::from_millis(50);
pub(super) fn run(
context: &Context,
project: Option<String>,
purpose: Option<String>,
command: &WithCommand,
json: bool,
) -> Result<i32, CliError> {
let (program, args) = command
.arguments
.split_first()
.expect("clap requires a command");
let project = match project {
Some(project) => project,
None => {
let cwd = env::current_dir()
.map_err(|error| CliError::WithSetup("read the working directory", error))?;
default_project(&cwd, env::var_os("GIT_CEILING_DIRECTORIES").as_deref())
}
};
let purpose = purpose.unwrap_or_else(|| default_purpose(Path::new(program)));
let probe = platform::probe()?;
context.ensure_registry_home()?;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|error| CliError::WithSetup("start the child supervisor", error))?;
runtime.block_on(async {
let mut signals = Signals::install()
.map_err(|error| CliError::WithSetup("install child supervision handlers", error))?;
let request = LeaseRequest {
project,
purpose,
holder: holder(),
holder_pid: Some(process::id()),
duration: command.duration,
bind: None,
};
let policy = context.config.policy_for_pool(command.pool.as_deref())?;
let allocation = match &command.group {
Some(components) => troll_core::lease_group(
&context.store,
&policy,
&|| allocation_snapshot(&probe),
&SystemClock,
LeaseGroupRequest {
lease: request,
components: components.clone(),
},
)
.map(Allocation::Group),
None => troll_core::lease(&context.store, &policy, &probe, &SystemClock, request)
.map(Allocation::Single),
};
let cancelled = signals.pending_stop().await;
let allocation = match allocation {
Ok(allocation) => allocation,
Err(error) => {
let Some(received) = cancelled else {
return Err(error.into());
};
let signal = received.name();
let exit_code = SIGNAL_EXIT_OFFSET + received.number();
let error = CliError::from(error).to_string();
report(
json,
Event::StartupCancelled {
signal,
exit_code,
error: &error,
},
format_args!(
"Startup cancelled by {signal}. Lease allocation reported: {error}"
),
);
return Ok(exit_code);
}
};
let heartbeat_duration = command
.duration
.unwrap_or(policy.lease_default)
.min(policy.lease_max);
let heartbeat = command
.heartbeat
.then(|| Heartbeat::new(&context.store, &policy, &allocation, heartbeat_duration));
let group = allocation.group_report();
let mut child_command = Command::new(program);
child_command.args(args);
allocation.set_env(&mut child_command);
let cancelled = match cancelled {
Some(received) => Some(received),
None => signals.pending_stop().await,
};
let (status, mut exit_code, error) = if let Some(received) = cancelled {
(
None,
SIGNAL_EXIT_OFFSET + received.number(),
Some(format!("Startup cancelled by {}.", received.name())),
)
} else {
match child_command.spawn() {
Ok(mut child) => {
allocation.report_started(json, group.as_ref());
match wait_for_child(
&mut child,
async || signals.next().await,
json,
group.as_ref(),
heartbeat,
)
.await
{
Ok(status) => {
let status = ChildStatus::from(status);
(Some(status), status.shell_code(), None)
}
Err(error) => (
None,
1,
Some(format!("could not wait for {program:?}: {error}")),
),
}
}
Err(error) => (
None,
SPAWN_FAILURE,
Some(format!("could not start {program:?}: {error}")),
),
}
};
let release = match allocation.release(&context.store) {
Ok(true) => Release::Released,
Ok(false) => Release::AlreadyAbsent,
Err(error) => {
if exit_code == 0 {
exit_code = 1;
}
Release::Failed {
message: error.to_string(),
lease: allocation.single(),
leases: allocation.group_leases(),
}
}
};
report_finished(
json,
&allocation,
group.as_ref(),
status,
exit_code,
error.as_deref(),
release,
);
Ok(exit_code)
})
}
fn default_project(cwd: &Path, ceiling_directories: Option<&OsStr>) -> String {
let root = git_project_root(cwd, ceiling_directories).unwrap_or(cwd);
let Some(name) = root.file_name() else {
return UNKNOWN_NAME.into();
};
name.to_string_lossy()
.chars()
.take(MAX_PROJECT_CHARS)
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') {
ch.to_ascii_lowercase()
} else {
'-'
}
})
.collect()
}
fn git_project_root<'a>(cwd: &'a Path, ceiling_directories: Option<&OsStr>) -> Option<&'a Path> {
if troll_probe::is_git_top_level(cwd) {
return Some(cwd);
}
let ceilings = git_ceilings(ceiling_directories);
cwd.ancestors()
.skip(1)
.take_while(|path| {
!ceilings
.iter()
.any(|ceiling| ceiling.as_os_str() == path.as_os_str())
})
.find(|path| troll_probe::is_git_top_level(path))
}
fn git_ceilings(value: Option<&OsStr>) -> Vec<PathBuf> {
let mut resolve = true;
value
.into_iter()
.flat_map(env::split_paths)
.filter_map(|path| {
if path.as_os_str().is_empty() {
resolve = false;
return None;
}
if !path.is_absolute() {
return None;
}
if resolve {
path.canonicalize().ok()
} else {
Some(path)
}
})
.collect()
}
fn default_purpose(program: &Path) -> String {
program
.file_name()
.filter(|name| !name.is_empty())
.map_or_else(
|| UNKNOWN_NAME.into(),
|name| {
name.to_string_lossy()
.chars()
.take(MAX_PURPOSE_CHARS)
.map(|ch| if ch.is_control() { ' ' } else { ch })
.collect()
},
)
}
enum Allocation {
Single(Lease),
Group(LeaseGroup),
}
impl Allocation {
fn single(&self) -> Option<&Lease> {
match self {
Self::Single(lease) => Some(lease),
Self::Group(_) => None,
}
}
fn group_leases(&self) -> Option<&[Lease]> {
match self {
Self::Single(_) => None,
Self::Group(group) => Some(&group.leases),
}
}
fn group_report(&self) -> Option<GroupReport<'_>> {
let Self::Group(group) = self else {
return None;
};
Some(GroupReport {
group: &group.group,
components: group
.leases
.iter()
.map(|lease| ComponentPort {
component: lease
.component
.as_deref()
.expect("group leases have components"),
port: lease.port,
})
.collect(),
})
}
fn set_env(&self, command: &mut Command) {
match self {
Self::Single(lease) => {
let port = lease.port.to_string();
command.env("PORT", &port).env("TROLL_PORT", &port);
}
Self::Group(group) => {
command
.env_remove("PORT")
.env_remove("TROLL_PORT")
.env("TROLL_GROUP", &group.group);
for lease in &group.leases {
let component = lease
.component
.as_deref()
.expect("group leases have components");
command.env(component_env_name(component), lease.port.to_string());
}
}
}
}
fn report_started(&self, json: bool, group: Option<&GroupReport<'_>>) {
let event = Event::Started {
lease: self.single(),
group,
};
match self {
Self::Single(lease) => report(
json,
event,
format_args!("Leased port {} for {}.", lease.port, lease.project),
),
Self::Group(group) => report(
json,
event,
format_args!(
"Leased group {} with {} ports.",
group.group,
group.leases.len()
),
),
}
}
fn leased_at(&self) -> OffsetDateTime {
match self {
Self::Single(lease) => lease.leased_at,
Self::Group(group) => {
group
.leases
.first()
.expect("a group has at least one lease")
.leased_at
}
}
}
fn renew(
&self,
store: &Store,
policy: &Policy,
duration: SignedDuration,
) -> Result<(), UpdateError<OperationError>> {
match self {
Self::Single(lease) => troll_core::renew(
store,
policy,
&SystemClock,
lease.port,
Some(&lease.holder),
Some(duration),
Some(lease.leased_at),
)
.map(|_| ()),
Self::Group(group) => {
let holder = &group
.leases
.first()
.expect("a group has at least one lease")
.holder;
troll_core::renew_group(
store,
policy,
&SystemClock,
&group.group,
holder,
Some(duration),
)
.map(|_| ())
}
}
}
fn release(&self, store: &Store) -> Result<bool, CliError> {
match self {
Self::Single(lease) => release_lease(store, lease),
Self::Group(group) => {
let expected: Vec<_> = group
.leases
.iter()
.map(|lease| (lease.port, lease.leased_at))
.collect();
let holder = &group
.leases
.first()
.expect("a group has at least one lease")
.holder;
match troll_core::release_group(store, &group.group, holder, Some(&expected)) {
Ok(released) => Ok(!released.is_empty()),
Err(UpdateError::Operation(OperationError::Refused(
Refused::GroupNotFound { .. },
))) => Ok(false),
Err(error) => Err(error.into()),
}
}
}
}
}
fn release_lease(store: &Store, lease: &Lease) -> Result<bool, CliError> {
Ok(store.update::<_, troll_core::OperationError>(|registry| {
let Some(index) = registry.lease.iter().position(|entry| {
entry.port == lease.port
&& entry.bind == lease.bind
&& entry.holder == lease.holder
&& entry.holder_pid == lease.holder_pid
&& entry.leased_at == lease.leased_at
}) else {
return Ok(false);
};
registry.lease.remove(index);
Ok(true)
})?)
}
struct Heartbeat<'a> {
store: &'a Store,
policy: &'a Policy,
allocation: &'a Allocation,
duration: SignedDuration,
interval: Duration,
max_deadline: Option<OffsetDateTime>,
next_tick: tokio::time::Instant,
stopped: bool,
}
impl<'a> Heartbeat<'a> {
fn new(
store: &'a Store,
policy: &'a Policy,
allocation: &'a Allocation,
duration: SignedDuration,
) -> Self {
let half_seconds = (duration.whole_seconds() / 2).max(1) as u64;
let interval = Duration::from_secs(half_seconds);
let max_deadline = allocation.leased_at().checked_add(policy.lease_max);
Self {
store,
policy,
allocation,
duration,
interval,
max_deadline,
next_tick: tokio::time::Instant::now() + interval,
stopped: false,
}
}
fn tick(&mut self) {
let Some(max_deadline) = self.max_deadline else {
self.stopped = true;
return;
};
let remaining = max_deadline - SystemClock.now();
if !remaining.is_positive() {
self.stopped = true;
return;
}
let renew_for = self.duration.min(remaining);
match self.allocation.renew(self.store, self.policy, renew_for) {
Ok(()) => {
if renew_for >= remaining {
self.stopped = true;
} else {
self.next_tick = tokio::time::Instant::now() + self.interval;
}
}
Err(UpdateError::Operation(OperationError::Refused(
Refused::NotFound { .. } | Refused::GroupNotFound { .. } | Refused::Changed { .. },
))) => {
self.stopped = true;
}
Err(_) => {
self.next_tick = tokio::time::Instant::now() + self.interval;
}
}
}
}
async fn sleep_until_heartbeat(heartbeat: Option<&Heartbeat<'_>>) {
match heartbeat {
Some(hb) if !hb.stopped => tokio::time::sleep_until(hb.next_tick).await,
_ => std::future::pending().await,
}
}
async fn wait_for_child(
child: &mut Child,
mut next_signal: impl AsyncFnMut() -> Option<StopSignal>,
json: bool,
group: Option<&GroupReport<'_>>,
mut heartbeat: Option<Heartbeat<'_>>,
) -> io::Result<ExitStatus> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(status);
}
enum Wake {
Signal(Option<StopSignal>),
Heartbeat,
Poll,
}
let wake = tokio::select! {
signal = next_signal() => Wake::Signal(signal),
() = sleep_until_heartbeat(heartbeat.as_ref()) => Wake::Heartbeat,
() = tokio::time::sleep(CHILD_POLL_INTERVAL) => Wake::Poll,
};
match wake {
Wake::Heartbeat => {
if let Some(hb) = heartbeat.as_mut() {
hb.tick();
}
}
Wake::Signal(Some(received)) => {
if let Err(error) = platform::forward_stop_signal_to_own_child(child, received)
&& error.kind() != io::ErrorKind::Unsupported
{
let signal = received.name();
let message = error.to_string();
report(
json,
Event::SignalForwardFailed {
group,
signal,
message: &message,
},
format_args!("Could not forward {signal} to the child: {message}"),
);
}
}
Wake::Signal(None) | Wake::Poll => {}
}
}
}
struct Signals {
#[cfg(unix)]
child: tokio::signal::unix::Signal,
#[cfg(windows)]
ctrl_break: tokio::signal::windows::CtrlBreak,
stop: StopSignals,
}
impl Signals {
fn install() -> io::Result<Self> {
Ok(Self {
#[cfg(unix)]
child: tokio::signal::unix::signal(tokio::signal::unix::SignalKind::child())?,
#[cfg(windows)]
ctrl_break: tokio::signal::windows::ctrl_break()?,
stop: StopSignals::install()?,
})
}
async fn pending_stop(&mut self) -> Option<StopSignal> {
tokio::task::yield_now().await;
tokio::select! {
biased;
signal = self.stop.next() => Some(signal),
() = ready(()) => None,
}
}
async fn next(&mut self) -> Option<StopSignal> {
#[cfg(unix)]
let wake = self.child.recv();
#[cfg(windows)]
let wake = self.ctrl_break.recv();
#[cfg(not(any(unix, windows)))]
let wake = std::future::pending::<()>();
tokio::select! {
_ = wake => None,
signal = self.stop.next() => Some(signal),
}
}
}
#[cfg(unix)]
struct StopSignals {
interrupt: tokio::signal::unix::Signal,
terminate: tokio::signal::unix::Signal,
hangup: tokio::signal::unix::Signal,
}
#[cfg(unix)]
impl StopSignals {
fn install() -> io::Result<Self> {
use tokio::signal::unix::{SignalKind, signal};
Ok(Self {
interrupt: signal(SignalKind::interrupt())?,
terminate: signal(SignalKind::terminate())?,
hangup: signal(SignalKind::hangup())?,
})
}
async fn next(&mut self) -> StopSignal {
tokio::select! {
Some(()) = self.interrupt.recv() => StopSignal::Interrupt,
Some(()) = self.terminate.recv() => StopSignal::Terminate,
Some(()) = self.hangup.recv() => StopSignal::Hangup,
}
}
}
#[cfg(not(unix))]
struct StopSignals {
#[cfg(windows)]
interrupt: tokio::signal::windows::CtrlC,
}
#[cfg(not(unix))]
impl StopSignals {
fn install() -> io::Result<Self> {
Ok(Self {
#[cfg(windows)]
interrupt: tokio::signal::windows::ctrl_c()?,
})
}
async fn next(&mut self) -> StopSignal {
#[cfg(windows)]
{
self.interrupt.recv().await;
StopSignal::Interrupt
}
#[cfg(not(windows))]
std::future::pending().await
}
}
#[derive(Clone, Copy, Serialize)]
struct ChildStatus {
exit_code: Option<i32>,
signal: Option<i32>,
}
impl From<ExitStatus> for ChildStatus {
fn from(status: ExitStatus) -> Self {
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
Self {
exit_code: status.code(),
#[cfg(unix)]
signal: status.signal(),
#[cfg(not(unix))]
signal: None,
}
}
}
impl ChildStatus {
fn shell_code(self) -> i32 {
self.exit_code
.or_else(|| self.signal.map(|signal| SIGNAL_EXIT_OFFSET + signal))
.unwrap_or(1)
}
}
#[derive(Serialize)]
#[serde(tag = "result", rename_all = "snake_case")]
enum Release<'a> {
Released,
AlreadyAbsent,
Failed {
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
lease: Option<&'a Lease>,
#[serde(skip_serializing_if = "Option::is_none")]
leases: Option<&'a [Lease]>,
},
}
#[derive(Serialize)]
struct ComponentPort<'a> {
component: &'a str,
port: u16,
}
#[derive(Serialize)]
struct GroupReport<'a> {
group: &'a str,
components: Vec<ComponentPort<'a>>,
}
#[derive(Serialize)]
struct Diagnostic<'a> {
schema: u32,
#[serde(flatten)]
event: Event<'a>,
}
#[derive(Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
enum Event<'a> {
Started {
#[serde(skip_serializing_if = "Option::is_none")]
lease: Option<&'a Lease>,
#[serde(flatten)]
group: Option<&'a GroupReport<'a>>,
},
Finished {
#[serde(skip_serializing_if = "Option::is_none")]
port: Option<u16>,
#[serde(flatten)]
group: Option<&'a GroupReport<'a>>,
status: Option<ChildStatus>,
exit_code: i32,
release: Release<'a>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<&'a str>,
},
StartupCancelled {
signal: &'a str,
exit_code: i32,
error: &'a str,
},
SignalForwardFailed {
#[serde(flatten)]
group: Option<&'a GroupReport<'a>>,
signal: &'a str,
message: &'a str,
},
}
fn report(json: bool, event: Event<'_>, human: std::fmt::Arguments<'_>) {
if json {
stderr_json(&Diagnostic {
schema: SCHEMA,
event,
});
} else {
let _ = writeln!(io::stderr().lock(), "{human}");
}
}
fn report_finished(
json: bool,
allocation: &Allocation,
group: Option<&GroupReport<'_>>,
status: Option<ChildStatus>,
exit_code: i32,
error: Option<&str>,
release: Release<'_>,
) {
if json {
stderr_json(&Diagnostic {
schema: SCHEMA,
event: Event::Finished {
port: allocation.single().map(|lease| lease.port),
group,
status,
exit_code,
release,
error,
},
});
return;
}
let mut out = io::stderr().lock();
if let Some(error) = error {
let _ = writeln!(out, "{error}");
}
match (allocation, release) {
(Allocation::Single(lease), Release::Released) => {
let _ = writeln!(out, "Released port {}.", lease.port);
}
(Allocation::Single(lease), Release::AlreadyAbsent) => {
let _ = writeln!(out, "Lease on port {} was already absent.", lease.port);
}
(Allocation::Group(group), Release::Released) => {
let _ = writeln!(out, "Released leases for group {}.", group.group);
}
(Allocation::Group(group), Release::AlreadyAbsent) => {
let _ = writeln!(out, "Leases for group {} were already absent.", group.group);
}
(allocation, Release::Failed { message, .. }) => match allocation {
Allocation::Single(lease) => write_release_failure(&mut out, lease, &message),
Allocation::Group(group) => {
let _ = writeln!(out, "Could not release group {}.", group.group);
for lease in &group.leases {
write_release_failure(&mut out, lease, &message);
}
}
},
}
}
fn write_release_failure(out: &mut impl Write, lease: &Lease, message: &str) {
let port = lease.port;
let holder_pid = lease
.holder_pid
.map_or_else(|| "unknown".into(), |pid| pid.to_string());
let leased_at = timestamp(lease.leased_at).unwrap_or_else(|_| lease.leased_at.to_string());
let _ = writeln!(
out,
"Could not release port {port} (bind {}, holder {:?}, holder PID {holder_pid}, leased at {leased_at}): {message}",
lease.bind, lease.holder,
);
let _ = writeln!(
out,
"Release it with `troll release {port} --leased-at {leased_at}` or let it expire."
);
}
#[cfg(all(test, unix))]
mod tests {
use std::{fs, os::unix::fs::symlink, process::Stdio};
use crate::test_support::TempDir;
use super::*;
#[test]
fn parses_group_options_and_serializes_the_group_diagnostic() {
use clap::Parser;
use serde_json::json;
let cli = crate::cli::Cli::try_parse_from([
"troll",
"with",
"--group",
"front-end,db",
"--json",
"--",
"p",
"--group",
"child-value",
])
.unwrap();
let Some(crate::cli::Command::With { command, .. }) = cli.command else {
panic!("expected the with subcommand");
};
assert!(cli.json);
assert_eq!(command.group.as_deref().unwrap(), ["front-end", "db"]);
assert_eq!(command.arguments, ["p", "--group", "child-value"]);
let group = GroupReport {
group: "g-0123456789ab",
components: vec![
ComponentPort {
component: "front-end",
port: 20000,
},
ComponentPort {
component: "db",
port: 20001,
},
],
};
let diagnostic = Diagnostic {
schema: SCHEMA,
event: Event::Started {
lease: None,
group: Some(&group),
},
};
assert_eq!(
serde_json::to_value(diagnostic).unwrap(),
json!({
"schema": 1,
"event": "started",
"group": "g-0123456789ab",
"components": [
{"component": "front-end", "port": 20000},
{"component": "db", "port": 20001},
],
})
);
}
#[test]
fn child_poll_reaps_an_exit_without_sigchld() {
let mut child = Command::new("/bin/sh")
.args(["-c", "read -r line; exit 37"])
.stdin(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take();
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let status = runtime.block_on(async {
tokio::time::timeout(
CHILD_POLL_INTERVAL * 3,
wait_for_child(
&mut child,
async || {
if let Some(mut stdin) = stdin.take() {
stdin.write_all(b"exit\n").unwrap();
}
std::future::pending().await
},
false,
None,
None,
),
)
.await
});
drop(stdin);
let reaped = child.wait().unwrap();
assert_eq!(status.expect("child polling timed out").unwrap(), reaped);
assert_eq!(reaped.code(), Some(37));
}
fn mark_git_top_level(path: &Path) {
fs::create_dir(path.join(".git")).unwrap();
fs::write(path.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
}
#[test]
fn git_ceiling_resolves_symlinks_before_the_empty_entry() {
let fixture = TempDir::new();
let base = fixture.path().canonicalize().unwrap();
let root = base.join("project");
let cwd = root.join("src");
fs::create_dir_all(&cwd).unwrap();
mark_git_top_level(&root);
let link = base.join("shortcut");
symlink(&root, &link).unwrap();
let resolving = env::join_paths([&link]).unwrap();
let resolves_before_sentinel = env::join_paths([&link, Path::new("")]).unwrap();
let literal = env::join_paths([Path::new(""), &link]).unwrap();
let relative = OsStr::new("project");
assert_eq!(default_project(&cwd, Some(&resolving)), "src");
assert_eq!(
default_project(&cwd, Some(&resolves_before_sentinel)),
"src"
);
assert_eq!(default_project(&cwd, Some(&literal)), "project");
let dotted = format!(":{}/./project", base.display());
assert_eq!(default_project(&cwd, Some(OsStr::new(&dotted))), "project");
assert_eq!(default_project(&cwd, Some(relative)), "project");
}
#[test]
fn git_ceiling_at_start_does_not_stop_ancestor_discovery() {
let fixture = TempDir::new();
let root = fixture.path().join("project");
let cwd = root.join("src");
fs::create_dir_all(&cwd).unwrap();
mark_git_top_level(&root);
let ceiling = cwd.as_os_str();
assert_eq!(git_project_root(&cwd, None), Some(root.as_path()));
assert_eq!(git_project_root(&cwd, Some(ceiling)), Some(root.as_path()));
mark_git_top_level(&cwd);
assert_eq!(git_project_root(&cwd, Some(ceiling)), Some(cwd.as_path()));
}
}