mind-body: the shared --instance/--endpoint parser lives in cli.rs
mind-wake's private parse() and endpoint resolution become one pub fn, cli::instance_and_endpoint, so the next organ binary reads the same arguments the same way. Refusals and messages are unchanged and echo no value; the instance's slug grammar is now checked there as well as at control_path. tests/public_surface.txt is updated in the commit that adds self_run (the snapshot test is red until then; everything builds). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
70d0cef421
commit
b4795b8030
3 changed files with 80 additions and 28 deletions
|
|
@ -5,13 +5,12 @@
|
|||
//! mind cannot be reached or the arguments are wrong. Without `--endpoint` the
|
||||
//! daemon is `HUGINN_ENDPOINT`.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use eureka_pipeline::Slug;
|
||||
use anyhow::Result;
|
||||
use eureka_state::HuginnClient;
|
||||
use mind_body::cli::instance_and_endpoint;
|
||||
use mind_body::control::{CONTROL_ROOT, FileSource, control_path};
|
||||
use mind_body::launch::{Ports, SystemClock, SystemdLauncher};
|
||||
use mind_body::queue::HuginnMind;
|
||||
|
|
@ -22,25 +21,6 @@ const TIMEOUT: Duration = Duration::from_secs(15);
|
|||
|
||||
const USAGE: &str = "usage: mind-wake --instance <slug> [--endpoint rudp://<ip>:<port>]";
|
||||
|
||||
/// The instance and the endpoint as given. A flag given twice or an unknown
|
||||
/// argument is refused without printing it.
|
||||
fn parse(args: &[String]) -> Result<(Slug, Option<String>)> {
|
||||
let (mut instance, mut endpoint) = (None, None);
|
||||
let mut rest = args.iter();
|
||||
while let Some(flag) = rest.next() {
|
||||
let slot = match flag.as_str() {
|
||||
"--instance" => &mut instance,
|
||||
"--endpoint" => &mut endpoint,
|
||||
_ => bail!("{USAGE}"),
|
||||
};
|
||||
let value = rest.next().ok_or_else(|| anyhow!("{USAGE}"))?;
|
||||
if slot.replace(value.clone()).is_some() {
|
||||
bail!("{USAGE}");
|
||||
}
|
||||
}
|
||||
Ok((Slug(instance.ok_or_else(|| anyhow!("{USAGE}"))?), endpoint))
|
||||
}
|
||||
|
||||
/// The host a run records: the kernel's name for this machine.
|
||||
fn host() -> String {
|
||||
std::fs::read_to_string("/proc/sys/kernel/hostname").map(|name| name.trim().to_string()).ok().filter(|name| !name.is_empty()).unwrap_or_else(|| "unknown".into())
|
||||
|
|
@ -51,13 +31,8 @@ fn host() -> String {
|
|||
#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and the daemon's address, and hands them to the library")]
|
||||
fn run() -> Result<String> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let (instance, endpoint) = parse(&args)?;
|
||||
let (instance, address) = instance_and_endpoint(&args, std::env::var("HUGINN_ENDPOINT").ok(), USAGE)?;
|
||||
let source = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?);
|
||||
let endpoint = endpoint.or_else(|| std::env::var("HUGINN_ENDPOINT").ok()).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?;
|
||||
let address = endpoint
|
||||
.strip_prefix("rudp://")
|
||||
.and_then(|address| address.parse::<SocketAddr>().ok())
|
||||
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
|
||||
let mind = HuginnMind::new(HuginnClient::new(address, instance, TIMEOUT));
|
||||
let launcher = SystemdLauncher::new();
|
||||
let host = host();
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@
|
|||
//! fails if either step failed. No other command stops anything.
|
||||
|
||||
use std::io::Write;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::str::FromStr;
|
||||
|
||||
|
|
@ -32,6 +33,36 @@ use crate::launch::unit;
|
|||
const USAGE: &str =
|
||||
"usage: mind-control [--root <dir>] --instance <slug> show | check | brake hold | brake release | dial set --heat H --base-cooldown-s S --base-run-usd U";
|
||||
|
||||
/// The arguments every organ binary shares: `--instance <slug>` and an optional
|
||||
/// `--endpoint rudp://<ip>:<port>`, which `env_endpoint` (the binary's reading of
|
||||
/// `HUGINN_ENDPOINT`) replaces when absent. A flag given twice, an unknown
|
||||
/// argument, a name that is not a slug or an endpoint that is not
|
||||
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
|
||||
/// value is echoed.
|
||||
pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, usage: &str) -> Result<(Slug, SocketAddr)> {
|
||||
let (mut instance, mut endpoint) = (None, None);
|
||||
let mut rest = args.iter();
|
||||
while let Some(flag) = rest.next() {
|
||||
let slot = match flag.as_str() {
|
||||
"--instance" => &mut instance,
|
||||
"--endpoint" => &mut endpoint,
|
||||
_ => bail!("{usage}"),
|
||||
};
|
||||
let value = rest.next().ok_or_else(|| anyhow!("{usage}"))?;
|
||||
if slot.replace(value.clone()).is_some() {
|
||||
bail!("{usage}");
|
||||
}
|
||||
}
|
||||
let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?);
|
||||
instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?;
|
||||
let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?;
|
||||
let address = endpoint
|
||||
.strip_prefix("rudp://")
|
||||
.and_then(|address| address.parse::<SocketAddr>().ok())
|
||||
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
|
||||
Ok((instance, address))
|
||||
}
|
||||
|
||||
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty
|
||||
/// variable counts as unset.
|
||||
pub fn operator_name(sudo_user: Option<String>, user: Option<String>) -> String {
|
||||
|
|
|
|||
|
|
@ -375,3 +375,49 @@ fn the_binary_hold_fails_with_status_2_when_systemctl_does() {
|
|||
assert!(stderr.contains("units were not stopped") && stderr.contains("exit status 5"), "{stderr}");
|
||||
assert!(!String::from_utf8_lossy(&output.stdout).contains("stopped"));
|
||||
}
|
||||
|
||||
// ---- the arguments every organ binary shares ----
|
||||
|
||||
mod shared_arguments {
|
||||
use mind_body::cli::instance_and_endpoint;
|
||||
|
||||
const USAGE: &str = "usage: test-organ --instance <slug>";
|
||||
|
||||
fn parse(args: &[&str], env: Option<&str>) -> anyhow::Result<(eureka_pipeline::Slug, std::net::SocketAddr)> {
|
||||
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
|
||||
instance_and_endpoint(&args, env.map(str::to_string), USAGE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_names_the_endpoint_and_wins_over_the_environment_which_is_the_fallback() {
|
||||
let (instance, address) = parse(&["--instance", "yggdrasil", "--endpoint", "rudp://10.77.0.1:17872"], Some("rudp://127.0.0.1:1")).unwrap();
|
||||
assert_eq!((instance.0.as_str(), address.to_string().as_str()), ("yggdrasil", "10.77.0.1:17872"));
|
||||
let (_, address) = parse(&["--endpoint", "rudp://10.77.0.1:17872", "--instance", "yggdrasil"], None).unwrap();
|
||||
assert_eq!(address.to_string(), "10.77.0.1:17872", "flag order does not matter");
|
||||
let (_, address) = parse(&["--instance", "yggdrasil"], Some("rudp://127.0.0.1:9")).unwrap();
|
||||
assert_eq!(address.to_string(), "127.0.0.1:9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_refusal_is_fixed_text_that_echoes_no_value() {
|
||||
let canary = "canary-value-91e7";
|
||||
let cases: Vec<(Vec<&str>, Option<&str>, &str)> = vec![
|
||||
(vec![], Some("rudp://127.0.0.1:9"), USAGE),
|
||||
(vec!["--instance"], None, USAGE),
|
||||
(vec!["--instance", "a", "--instance", canary], Some("rudp://127.0.0.1:9"), USAGE),
|
||||
(vec!["--instance", "a", "--endpoint", "rudp://127.0.0.1:9", "--endpoint", canary], None, USAGE),
|
||||
(vec!["--instance", "a", canary], Some("rudp://127.0.0.1:9"), USAGE),
|
||||
(vec!["--endpoint", "rudp://127.0.0.1:9"], None, USAGE),
|
||||
(vec!["--instance", "Canary/../x"], Some("rudp://127.0.0.1:9"), "the instance is not a slug"),
|
||||
(vec!["--instance", "a"], None, "no daemon endpoint: --endpoint or HUGINN_ENDPOINT"),
|
||||
(vec!["--instance", "a", "--endpoint", canary], None, "the endpoint is not rudp://<ip>:<port>"),
|
||||
(vec!["--instance", "a", "--endpoint", "http://127.0.0.1:9"], None, "the endpoint is not rudp://<ip>:<port>"),
|
||||
(vec!["--instance", "a", "--endpoint", "rudp://not-an-address"], None, "the endpoint is not rudp://<ip>:<port>"),
|
||||
(vec!["--instance", "a"], Some(canary), "the endpoint is not rudp://<ip>:<port>"),
|
||||
];
|
||||
for (args, env, message) in cases {
|
||||
let error = parse(&args, env).unwrap_err();
|
||||
assert_eq!(format!("{error:#}"), message, "{args:?} {env:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue