use clap::Args;
use std::path::PathBuf;
use std::time::Duration;
#[derive(Args, Debug)]
pub struct KillArgs {
pub targets: Vec<String>,
#[arg(long)]
pub all: bool,
#[arg(long)]
pub yes: bool,
#[arg(long, default_value = ".assay/inventory.yaml")]
pub inventory: PathBuf,
#[arg(long, default_value = "immediate")]
pub mode: String,
#[arg(long, default_value = "5s")]
pub grace: String,
#[arg(long)]
pub kill_children: bool,
#[arg(long)]
pub capture_state: bool,
#[arg(long)]
pub output: Option<PathBuf>,
#[arg(long)]
pub reason: Option<String>,
}
pub async fn run(args: KillArgs) -> anyhow::Result<i32> {
use assay_core::kill_switch::{parse_target_to_pid, KillMode, KillRequest};
if args.all && !args.yes {
anyhow::bail!("Refusing to --all without --yes (safety).");
}
let mut pids: Vec<u32> = vec![];
if args.all {
let inv = load_inventory(&args.inventory)?;
pids = inv.running_pids();
if pids.is_empty() {
println!("No running process-based servers found in inventory.");
return Ok(0);
}
println!("Found {} running servers to kill.", pids.len());
} else {
if args.targets.is_empty() {
anyhow::bail!("Provide at least one target, or use --all.");
}
let mut inventory_loaded = None;
for t in &args.targets {
if let Some(pid) = parse_target_to_pid(t) {
pids.push(pid);
continue;
}
if inventory_loaded.is_none() {
match load_inventory(&args.inventory) {
Ok(inv) => inventory_loaded = Some(inv),
Err(e) => {
eprintln!(
"Warning: could not load inventory to resolve target '{}': {}",
t, e
);
continue;
}
}
}
if let Some(inv) = &inventory_loaded {
if let Some(pid) = inv.resolve_to_pid(t) {
pids.push(pid);
} else {
eprintln!("✗ Could not resolve target '{t}' to a PID (not running process?)");
}
}
}
}
let mode = match args.mode.as_str() {
"immediate" => KillMode::Immediate,
"graceful" => KillMode::Graceful {
grace: parse_duration(&args.grace)?,
},
other => anyhow::bail!("unknown --mode: {other}"),
};
let mut failed = false;
for pid in pids {
let req = KillRequest {
pid,
mode: mode.clone(),
kill_children: args.kill_children,
capture_state: args.capture_state,
output_dir: args.output.clone(),
reason: args.reason.clone(),
};
match assay_core::kill_switch::kill_pid(req) {
Ok(rep) if rep.success => {
println!("✓ killed pid={}", rep.pid);
if !rep.children_killed.is_empty() {
println!(" children killed: {}", rep.children_killed.len());
}
if let Some(dir) = rep.incident_dir {
println!(" incident: {}", dir.display());
}
}
Ok(rep) => {
failed = true;
eprintln!(
"✗ failed to kill pid={} ({})",
rep.pid,
rep.error.unwrap_or_default()
);
}
Err(e) => {
failed = true;
eprintln!("✗ failed to kill pid={pid}: {e:#}");
}
}
}
Ok(if failed { 30 } else { 0 })
}
fn load_inventory(path: &PathBuf) -> anyhow::Result<assay_core::discovery::types::Inventory> {
use assay_common::{
doc::{Input, JsonInput, Refusal},
limits::{LimitKind, LimitReader},
unique_value::UniqueValue,
};
use std::io::Read;
let file = std::fs::File::open(path)
.map_err(|e| anyhow::anyhow!("Failed to read inventory at {:?}: {}", path, e))?;
let mut bytes = Vec::new();
LimitReader::new(
file,
super::discover::MAX_INVENTORY_BYTES,
LimitKind::SourceBytes,
)
.read_to_end(&mut bytes)?;
let result = if path.extension().and_then(|s| s.to_str()) == Some("json") {
let UniqueValue(source) = serde_json::from_slice(&bytes)?;
JsonInput::read_value(&source)
} else {
Input::parse_bytes(&bytes).and_then(Input::read)
};
result.map_err(|error| match error {
Refusal::UnknownKeys(paths) => anyhow::anyhow!("unknown inventory keys: {paths:?}"),
Refusal::NotAMapping { path, expected } => {
anyhow::anyhow!("expected a {expected} mapping at {path:?}")
}
Refusal::Syntax { message, .. } | Refusal::Shape { message, .. } => {
anyhow::anyhow!("{message}")
}
_ => anyhow::anyhow!("invalid inventory"),
})
}
fn parse_duration(s: &str) -> anyhow::Result<Duration> {
let s = s.trim();
if let Some(ms) = s.strip_suffix("ms") {
return Ok(Duration::from_millis(ms.parse()?));
}
if let Some(sec) = s.strip_suffix("s") {
return Ok(Duration::from_secs(sec.parse()?));
}
Ok(Duration::from_secs(s.parse()?))
}