diff --git a/crates/idunn-daemon/src/main.rs b/crates/idunn-daemon/src/main.rs index 8d590cf..12ffdfb 100644 --- a/crates/idunn-daemon/src/main.rs +++ b/crates/idunn-daemon/src/main.rs @@ -6,61 +6,127 @@ use odin_core::{ }; use std::env; use std::path::PathBuf; -use std::process::Command; +use std::process::{Child, Command, Stdio}; use std::thread; use std::time::Duration; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; #[derive(Clone, Debug)] -struct Options { - store_path: PathBuf, +struct DaemonTarget { daemon_id: String, verse_id: String, name: String, health_command: Option, deploy_command: Option, restart_command: Option, - operator_alarm_command: Option, enabled: bool, + interval_seconds: u64, +} + +#[derive(Clone, Debug)] +struct CommonOptions { + store_path: PathBuf, + operator_alarm_command: Option, execute: bool, - interval_seconds: Option, + command_timeout_seconds: u64, +} + +#[derive(Clone, Debug)] +enum Mode { + Single(DaemonTarget), + Swarm(SwarmOptions), +} + +#[derive(Clone, Debug)] +struct SwarmOptions { + profile: String, + repo_root: PathBuf, +} + +#[derive(Clone, Debug)] +struct Options { + common: CommonOptions, + mode: Mode, } fn main() -> Result<()> { let options = Options::parse(env::args().skip(1))?; - if let Some(parent) = options.store_path.parent() { + if let Some(parent) = options.common.store_path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("creating {}", parent.display()))?; } - if let Some(interval_seconds) = options.interval_seconds { - loop { - run_cycle(&options)?; - thread::sleep(Duration::from_secs(interval_seconds)); + match &options.mode { + Mode::Single(target) => run_target_cycle(target, &options.common), + Mode::Swarm(swarm) => run_swarm(swarm, &options.common), + } +} + +fn run_swarm(options: &SwarmOptions, common: &CommonOptions) -> Result<()> { + let targets = swarm_targets(options)?; + if targets.is_empty() { + return Err(anyhow!( + "Idunn swarm profile {} resolved to no targets", + options.profile + )); + } + + println!( + "Idunn swarm profile {} starting with {} targets.", + options.profile, + targets.len() + ); + println!("CultMesh store: {}", common.store_path.display()); + + let mut workers = Vec::with_capacity(targets.len()); + for target in targets { + let worker_common = common.clone(); + workers.push(thread::spawn(move || { + run_target_loop(target, worker_common) + })); + } + + for worker in workers { + match worker.join() { + Ok(Ok(())) => {} + Ok(Err(error)) => return Err(error), + Err(_) => return Err(anyhow!("Idunn swarm worker thread panicked")), } } - run_cycle(&options) + Ok(()) } -fn run_cycle(options: &Options) -> Result<()> { +fn run_target_loop(target: DaemonTarget, options: CommonOptions) -> Result<()> { + loop { + if let Err(error) = run_target_cycle(&target, &options) { + eprintln!( + "Idunn swarm target {} cycle failed: {}", + target.daemon_id, error + ); + } + thread::sleep(Duration::from_secs(target.interval_seconds)); + } +} + +fn run_target_cycle(target: &DaemonTarget, options: &CommonOptions) -> Result<()> { let now = timestamp()?; let desired = IdunnDesiredDaemonRecord { - daemon_id: options.daemon_id.clone(), - verse_id: options.verse_id.clone(), - name: options.name.clone(), - enabled: options.enabled, - health_command: options.health_command.clone(), - restart_command: options.restart_command.clone(), - deploy_command: options.deploy_command.clone(), + daemon_id: target.daemon_id.clone(), + verse_id: target.verse_id.clone(), + name: target.name.clone(), + enabled: target.enabled, + health_command: target.health_command.clone(), + restart_command: target.restart_command.clone(), + deploy_command: target.deploy_command.clone(), authority: "idunn.local-command".to_string(), max_silence_seconds: 60, observed_at: now.clone(), }; - let health = probe_health(&options, &now); + let health = probe_health(target, options.command_timeout_seconds, &now); let plan = plan_keepalive(&desired, &health, now.clone()); let mut node = CultMesh::create_node( @@ -79,7 +145,7 @@ fn run_cycle(options: &Options) -> Result<()> { if let Some(request) = &plan.deployment_request { node.put(&request.request_id, request)?; if options.execute { - let result = run_deployment(request, &now); + let result = run_deployment(request, &now, options.command_timeout_seconds); node.put(&result.result_id, &result)?; println!( "Idunn deployment {} for {}: {}", @@ -92,7 +158,7 @@ fn run_cycle(options: &Options) -> Result<()> { "Idunn raised operator alarm for {} through {}: {}", alarm.daemon_id, alarm.escalation_target, alarm.reason ); - run_operator_alarm_command(&options, &alarm); + run_operator_alarm_command(options, &alarm); } } else { println!( @@ -105,7 +171,7 @@ fn run_cycle(options: &Options) -> Result<()> { if let Some(request) = &plan.restart_request { node.put(&request.request_id, request)?; if options.execute { - let result = run_restart(request, &now); + let result = run_restart(request, &now, options.command_timeout_seconds); node.put(&result.result_id, &result)?; println!( "Idunn restart {} for {}: {}", @@ -118,7 +184,7 @@ fn run_cycle(options: &Options) -> Result<()> { "Idunn raised operator alarm for {} through {}: {}", alarm.daemon_id, alarm.escalation_target, alarm.reason ); - run_operator_alarm_command(&options, &alarm); + run_operator_alarm_command(options, &alarm); } } else { println!( @@ -141,10 +207,150 @@ fn run_cycle(options: &Options) -> Result<()> { "Idunn decision for {}: {} ({})", plan.decision.daemon_id, plan.decision.action, plan.decision.reason ); - println!("CultMesh store: {}", options.store_path.display()); Ok(()) } +fn swarm_targets(options: &SwarmOptions) -> Result> { + let repo_root = options.repo_root.display().to_string(); + let script = |name: &str| format!(r"{}\scripts\{}", repo_root, name); + + match options.profile.as_str() { + "starfire-local" => Ok(vec![ + DaemonTarget { + daemon_id: "odin".to_string(), + verse_id: "starfire.local".to_string(), + name: "Odin all-seer".to_string(), + health_command: Some(script("health-odin.cmd")), + deploy_command: None, + restart_command: Some(script("restart-odin.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "mimir-eve-dashboard".to_string(), + verse_id: "starfire.local".to_string(), + name: "Mimir Eve dashboard".to_string(), + health_command: Some(script("health-mimir-eve-dashboard.cmd")), + deploy_command: None, + restart_command: None, + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "stonks".to_string(), + verse_id: "starfire.local".to_string(), + name: "Stonks market pulse".to_string(), + health_command: Some(script("health-stonks.cmd")), + deploy_command: None, + restart_command: Some(script("restart-stonks.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "voidbot".to_string(), + verse_id: "starfire.local".to_string(), + name: "VoidBot local stack".to_string(), + health_command: Some(script("health-voidbot.cmd")), + deploy_command: None, + restart_command: Some(script("restart-voidbot.cmd")), + enabled: true, + interval_seconds: 300, + }, + DaemonTarget { + daemon_id: "muninn".to_string(), + verse_id: "raven.local".to_string(), + name: "Muninn telemetry Verse assembler".to_string(), + health_command: Some(script("health-muninn.cmd")), + deploy_command: None, + restart_command: Some(script("restart-muninn.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "idunn-swarm-deployment-coverage".to_string(), + verse_id: "starfire.local".to_string(), + name: "Idunn swarm deployment coverage".to_string(), + health_command: Some(script("health-idunn-swarm-deployment-coverage.cmd")), + deploy_command: None, + restart_command: None, + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "yggdrasil-heimdall".to_string(), + verse_id: "yggdrasil.local".to_string(), + name: "Yggdrasil Heimdall".to_string(), + health_command: Some(script("health-yggdrasil-heimdall.cmd")), + deploy_command: Some(script("deploy-yggdrasil-heimdall.cmd")), + restart_command: None, + enabled: true, + interval_seconds: 300, + }, + DaemonTarget { + daemon_id: "yggdrasil-repixelizer".to_string(), + verse_id: "yggdrasil.local".to_string(), + name: "Yggdrasil Repixelizer".to_string(), + health_command: Some(script("health-yggdrasil-repixelizer.cmd")), + deploy_command: Some(script("deploy-yggdrasil-repixelizer.cmd")), + restart_command: None, + enabled: true, + interval_seconds: 300, + }, + DaemonTarget { + daemon_id: "yggdrasil-streampixels".to_string(), + verse_id: "yggdrasil.local".to_string(), + name: "Yggdrasil StreamPixels".to_string(), + health_command: Some(script("health-yggdrasil-streampixels.cmd")), + deploy_command: Some(script("deploy-yggdrasil-streampixels.cmd")), + restart_command: None, + enabled: true, + interval_seconds: 300, + }, + DaemonTarget { + daemon_id: "nightwing-gjallar".to_string(), + verse_id: "nightwing.local".to_string(), + name: "Nightwing Gjallar framebuffer compositor".to_string(), + health_command: Some(script("health-nightwing-gjallar.cmd")), + deploy_command: Some(script("deploy-nightwing-gjallar.cmd")), + restart_command: Some(script("restart-nightwing-gjallar.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "nightwing-muninn".to_string(), + verse_id: "nightwing.local".to_string(), + name: "Nightwing Muninn telemetry and Move HID daemon".to_string(), + health_command: Some(script("health-nightwing-muninn.cmd")), + deploy_command: None, + restart_command: Some(script("restart-nightwing-muninn.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "nightwing-eve-dashboard".to_string(), + verse_id: "nightwing.local".to_string(), + name: "Nightwing Eve dashboard broker".to_string(), + health_command: Some(script("health-nightwing-eve-dashboard.cmd")), + deploy_command: None, + restart_command: Some(script("restart-nightwing-eve-dashboard.cmd")), + enabled: true, + interval_seconds: 30, + }, + DaemonTarget { + daemon_id: "nightwing-eve-browser-reference".to_string(), + verse_id: "nightwing.local".to_string(), + name: "Nightwing Eve browser reference".to_string(), + health_command: Some(script("health-nightwing-eve-browser-reference.cmd")), + deploy_command: None, + restart_command: Some(script("restart-nightwing-eve-browser-reference.cmd")), + enabled: true, + interval_seconds: 30, + }, + ]), + other => Err(anyhow!("unknown Idunn swarm profile: {other}")), + } +} + fn restart_failure_alarm( result: &IdunnRestartResultRecord, raised_at: &str, @@ -181,49 +387,59 @@ fn deployment_failure_alarm( impl Options { fn parse(args: impl Iterator) -> Result { - let mut options = Options { - store_path: PathBuf::from("scratch/idunn/idunn.keepalive.cc"), - daemon_id: String::new(), - verse_id: "local".to_string(), - name: String::new(), - health_command: None, - deploy_command: None, - restart_command: None, - operator_alarm_command: None, - enabled: true, - execute: false, - interval_seconds: None, - }; + let mut store_path = PathBuf::from("scratch/idunn/idunn.keepalive.cc"); + let mut operator_alarm_command = None; + let mut execute = false; + let mut command_timeout_seconds = 30; + let mut daemon_id = None; + let mut verse_id = "local".to_string(); + let mut name = None; + let mut health_command = None; + let mut deploy_command = None; + let mut restart_command = None; + let mut enabled = true; + let mut interval_seconds = None; + let mut swarm_profile = None; + let mut repo_root = env::current_dir().context("determining current directory")?; let mut args = args.peekable(); while let Some(arg) = args.next() { match arg.as_str() { - "--store" => options.store_path = PathBuf::from(take_value(&mut args, "--store")?), - "--daemon" => options.daemon_id = take_value(&mut args, "--daemon")?, - "--verse" => options.verse_id = take_value(&mut args, "--verse")?, - "--name" => options.name = take_value(&mut args, "--name")?, + "--store" => store_path = PathBuf::from(take_value(&mut args, "--store")?), + "--daemon" => daemon_id = Some(take_value(&mut args, "--daemon")?), + "--verse" => verse_id = take_value(&mut args, "--verse")?, + "--name" => name = Some(take_value(&mut args, "--name")?), "--health-command" => { - options.health_command = Some(take_value(&mut args, "--health-command")?) + health_command = Some(take_value(&mut args, "--health-command")?) } "--deploy-command" => { - options.deploy_command = Some(take_value(&mut args, "--deploy-command")?) + deploy_command = Some(take_value(&mut args, "--deploy-command")?) } "--restart-command" => { - options.restart_command = Some(take_value(&mut args, "--restart-command")?) + restart_command = Some(take_value(&mut args, "--restart-command")?) } "--operator-alarm-command" => { - options.operator_alarm_command = + operator_alarm_command = Some(take_value(&mut args, "--operator-alarm-command")?) } - "--disabled" => options.enabled = false, - "--execute" => options.execute = true, + "--disabled" => enabled = false, + "--execute" => execute = true, "--interval-seconds" => { - options.interval_seconds = Some( + interval_seconds = Some( take_value(&mut args, "--interval-seconds")? .parse() .context("--interval-seconds must be a positive integer")?, ) } + "--command-timeout-seconds" => { + command_timeout_seconds = take_value(&mut args, "--command-timeout-seconds")? + .parse() + .context("--command-timeout-seconds must be a positive integer")? + } + "--swarm-profile" => { + swarm_profile = Some(take_value(&mut args, "--swarm-profile")?) + } + "--repo-root" => repo_root = PathBuf::from(take_value(&mut args, "--repo-root")?), "--help" | "-h" => return Err(anyhow!(help_text())), other => { return Err(anyhow!( @@ -234,17 +450,52 @@ impl Options { } } - if options.daemon_id.trim().is_empty() { - return Err(anyhow!("--daemon is required\n\n{}", help_text())); - } - if options.name.trim().is_empty() { - options.name = options.daemon_id.clone(); - } - if options.interval_seconds == Some(0) { - return Err(anyhow!("--interval-seconds must be greater than zero")); + if command_timeout_seconds == 0 { + return Err(anyhow!( + "--command-timeout-seconds must be greater than zero" + )); } - Ok(options) + let common = CommonOptions { + store_path, + operator_alarm_command, + execute, + command_timeout_seconds, + }; + + let mode = match (swarm_profile, daemon_id) { + (Some(profile), None) => Mode::Swarm(SwarmOptions { profile, repo_root }), + (Some(_), Some(_)) => { + return Err(anyhow!( + "use either --swarm-profile or --daemon, not both\n\n{}", + help_text() + )); + } + (None, Some(daemon_id)) => { + let interval_seconds = interval_seconds.unwrap_or(30); + if interval_seconds == 0 { + return Err(anyhow!("--interval-seconds must be greater than zero")); + } + Mode::Single(DaemonTarget { + daemon_id: daemon_id.clone(), + verse_id, + name: name.unwrap_or(daemon_id), + health_command, + deploy_command, + restart_command, + enabled, + interval_seconds, + }) + } + (None, None) => { + return Err(anyhow!( + "either --daemon or --swarm-profile is required\n\n{}", + help_text() + )); + } + }; + + Ok(Self { common, mode }) } } @@ -253,30 +504,34 @@ fn take_value(args: &mut impl Iterator, name: &str) -> Result IdunnDaemonHealthRecord { - match &options.health_command { - Some(command) => match run_shell(command) { +fn probe_health( + target: &DaemonTarget, + command_timeout_seconds: u64, + observed_at: &str, +) -> IdunnDaemonHealthRecord { + match &target.health_command { + Some(command) => match run_shell(command, command_timeout_seconds) { Ok(output) if output.status.success() => IdunnDaemonHealthRecord { - daemon_id: options.daemon_id.clone(), + daemon_id: target.daemon_id.clone(), state: "active".to_string(), detail: "health command exited successfully".to_string(), observed_at: observed_at.to_string(), }, Ok(output) => IdunnDaemonHealthRecord { - daemon_id: options.daemon_id.clone(), + daemon_id: target.daemon_id.clone(), state: "failed".to_string(), detail: format!("health command exited with {}", output.status), observed_at: observed_at.to_string(), }, Err(error) => IdunnDaemonHealthRecord { - daemon_id: options.daemon_id.clone(), + daemon_id: target.daemon_id.clone(), state: "failed".to_string(), detail: format!("health command could not run: {error}"), observed_at: observed_at.to_string(), }, }, None => IdunnDaemonHealthRecord { - daemon_id: options.daemon_id.clone(), + daemon_id: target.daemon_id.clone(), state: "unknown".to_string(), detail: "no health command was provided".to_string(), observed_at: observed_at.to_string(), @@ -287,9 +542,10 @@ fn probe_health(options: &Options, observed_at: &str) -> IdunnDaemonHealthRecord fn run_restart( request: &odin_core::IdunnRestartRequestRecord, requested_at: &str, + command_timeout_seconds: u64, ) -> IdunnRestartResultRecord { let result_id = format!("result:{}", request.request_id); - match run_shell(&request.command) { + match run_shell(&request.command, command_timeout_seconds) { Ok(output) if output.status.success() => IdunnRestartResultRecord { result_id, request_id: request.request_id.clone(), @@ -320,9 +576,10 @@ fn run_restart( fn run_deployment( request: &odin_core::IdunnDeploymentRequestRecord, requested_at: &str, + command_timeout_seconds: u64, ) -> IdunnDeploymentResultRecord { let result_id = format!("result:{}", request.request_id); - match run_shell(&request.command) { + match run_shell(&request.command, command_timeout_seconds) { Ok(output) if output.status.success() => IdunnDeploymentResultRecord { result_id, request_id: request.request_id.clone(), @@ -350,16 +607,26 @@ fn run_deployment( } } -fn run_shell(command: &str) -> Result { - if cfg!(windows) { - Command::new("cmd").arg("/C").arg(command).output() +fn run_shell(command: &str, timeout_seconds: u64) -> Result { + let mut process = if cfg!(windows) { + let mut process = Command::new("cmd"); + process.arg("/C").arg(command); + process } else { - Command::new("sh").arg("-c").arg(command).output() - } - .with_context(|| format!("running command {command:?}")) + let mut process = Command::new("sh"); + process.arg("-c").arg(command); + process + }; + + let child = process + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .with_context(|| format!("running command {command:?}"))?; + wait_for_child_with_timeout(child, Duration::from_secs(timeout_seconds), command) } -fn run_operator_alarm_command(options: &Options, alarm: &IdunnOperatorAlarmRecord) { +fn run_operator_alarm_command(options: &CommonOptions, alarm: &IdunnOperatorAlarmRecord) { let Some(command) = options.operator_alarm_command.as_deref() else { return; }; @@ -384,21 +651,35 @@ fn run_operator_alarm_command(options: &Options, alarm: &IdunnOperatorAlarmRecor .env("IDUNN_ALARM_REASON", &alarm.reason) .env("IDUNN_ALARM_ESCALATION_TARGET", &alarm.escalation_target) .env("IDUNN_ALARM_RAISED_AT", &alarm.raised_at) - .output(); + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn(); match output { - Ok(output) if output.status.success() => { - println!( - "Idunn operator alarm command completed for {}.", - alarm.daemon_id - ); - } - Ok(output) => { - eprintln!( - "Idunn operator alarm command failed for {} with {}.", - alarm.daemon_id, output.status - ); - } + Ok(child) => match wait_for_child_with_timeout( + child, + Duration::from_secs(options.command_timeout_seconds), + command, + ) { + Ok(output) if output.status.success() => { + println!( + "Idunn operator alarm command completed for {}.", + alarm.daemon_id + ); + } + Ok(output) => { + eprintln!( + "Idunn operator alarm command failed for {} with {}.", + alarm.daemon_id, output.status + ); + } + Err(error) => { + eprintln!( + "Idunn operator alarm command could not run for {}: {}", + alarm.daemon_id, error + ); + } + }, Err(error) => { eprintln!( "Idunn operator alarm command could not run for {}: {}", @@ -408,6 +689,37 @@ fn run_operator_alarm_command(options: &Options, alarm: &IdunnOperatorAlarmRecor } } +fn wait_for_child_with_timeout( + mut child: Child, + timeout: Duration, + command: &str, +) -> Result { + let started_at = Instant::now(); + + loop { + if child + .try_wait() + .with_context(|| format!("waiting on command {command:?}"))? + .is_some() + { + return child + .wait_with_output() + .with_context(|| format!("collecting output for command {command:?}")); + } + + if started_at.elapsed() >= timeout { + let _ = child.kill(); + let _ = child.wait_with_output(); + return Err(anyhow!( + "command timed out after {} seconds: {command:?}", + timeout.as_secs() + )); + } + + thread::sleep(Duration::from_millis(100)); + } +} + fn timestamp() -> Result { let seconds = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -417,5 +729,5 @@ fn timestamp() -> Result { } fn help_text() -> &'static str { - "Usage: idunn --daemon [--name ] [--verse ] [--store ] [--health-command ] [--deploy-command ] [--restart-command ] [--operator-alarm-command ] [--execute] [--interval-seconds ]\n\nIdunn probes one daemon, writes typed CultMesh records, executes deployment or restart only when --execute is present, and may invoke an operator alarm bridge command only after an alarm is raised." + "Usage: idunn --daemon [--name ] [--verse ] [--store ] [--health-command ] [--deploy-command ] [--restart-command ] [--operator-alarm-command ] [--execute] [--interval-seconds ] [--command-timeout-seconds ] [--repo-root ] [--swarm-profile ]\n\nIdunn can run one manual daemon probe lane with --daemon, or one built-in swarm supervisor with --swarm-profile starfire-local." } diff --git a/crates/odin-core/src/idunn.rs b/crates/odin-core/src/idunn.rs index 629f1a6..70bfc41 100644 --- a/crates/odin-core/src/idunn.rs +++ b/crates/odin-core/src/idunn.rs @@ -45,7 +45,10 @@ pub fn plan_keepalive( &decision_id, desired, "deploy", - &format!("health is {}; deployment authority is available", health.state), + &format!( + "health is {}; deployment authority is available", + health.state + ), &now, ), deployment_request: Some(IdunnDeploymentRequestRecord { diff --git a/docs/idunn.md b/docs/idunn.md index 8b62afc..e137c6b 100644 --- a/docs/idunn.md +++ b/docs/idunn.md @@ -45,14 +45,13 @@ Idunn now shares Odin's Rust body: - `crates/odin-core/src/idunn.rs` owns the keepalive decision engine. - `crates/odin-core/src/documents.rs` publishes typed Idunn CultMesh records beside Odin and Gjallar records. -- `crates/idunn-daemon` is the local keepalive actuator crate. +- `crates/idunn-daemon` is the local keepalive actuator crate and now owns the + resident Starfire-local swarm scheduler. - `src/Idunn/README.md` is the user-facing introduction for developers, operators, and daemon authors. -- `scripts/start-idunn-local.ps1` starts resident local watchdogs, including - VoidBot through `health-voidbot.cmd` and `restart-voidbot.cmd`, Muninn - through `health-muninn.cmd` and `restart-muninn.cmd`, and Nightwing Gjallar - through `health-nightwing-gjallar.cmd`, - `deploy-nightwing-gjallar.cmd`, and `restart-nightwing-gjallar.cmd`. +- `scripts/start-idunn-local.ps1` is now a narrow bootstrap wrapper: it ensures + one `idunn.exe` process is alive, checks the shared keepalive store for + staleness, and lets Rust own the target catalog and per-target scheduling. - `scripts/deploy-yggdrasil-source-app.ps1` and `scripts/health-yggdrasil-source-app.ps1` are the generic Yggdrasil source artifact lane. They package committed local `HEAD` with `git archive`, run @@ -70,10 +69,10 @@ Idunn now shares Odin's Rust body: publish a typed `gamecult.operator_dm_request.v1` CultMesh command document instead of learning Discord delivery itself. - `npm run idunn:build` builds the Rust daemon. -- `npm run idunn:start -- ...` probes a daemon, records the decision, and can - execute the restart command when `--execute` is present. -- `--interval-seconds ` keeps the same probe and decision path running - as a resident keepalive loop. +- `npm run idunn:start -- ...` still supports the narrow one-daemon probe path + for manual use. +- `npm run idunn:start -- --swarm-profile starfire-local --repo-root E:\Projects\Odin --execute` + runs the singular local swarm supervisor. The current typed records are: @@ -150,26 +149,26 @@ idunn.operator_alarm.v1 not claim Bifrost deployment freshness until Bifrost owns that schema migration path. -## First Runtime Direction +## Runtime Direction -Idunn's Rust runtime grows in this order: +Idunn's current Rust runtime now has two postures: -1. Probe one named daemon with an explicit health command, once or on a - resident interval. -2. Normalize that into `idunn.desired_daemon.v1` and - `idunn.daemon_health.v1`. -3. Emit `idunn.keepalive_decision.v1`. -4. When deploy authority exists, emit `idunn.deployment_request.v1`. -5. When `--execute` is present, execute the deploy command and emit - `idunn.deployment_result.v1`. -6. When restart authority exists, emit `idunn.restart_request.v1`. -7. When `--execute` is present, execute the restart command and emit - `idunn.restart_result.v1`. -8. When authority is missing, emit `idunn.operator_alarm.v1` targeting - Bifrost operator notification. -9. Next: ingest Odin-owned service/provider advertisements directly, add named - adapters for Windows services, systemd, Docker, and provider-advertised - CultMesh commands, then publish an Eve/CultUI keepalive surface. +1. One-daemon manual mode for focused probes and explicit local testing. +2. One-process swarm mode for the Starfire-local continuity graph. + +The local swarm mode owns: + +1. the built-in Starfire-local target catalog; +2. one in-process schedule per target instead of one watchdog process per target; +3. shared typed keepalive records in one CultMesh store; +4. deploy/restart/alarm execution through the same Rust decision engine; +5. recovery of fast local targets like Odin without waiting behind slow remote + Yggdrasil checks. + +Next: ingest Odin-owned service/provider advertisements directly, promote the +target catalog out of hardcoded bootstrap data, add named adapters for Windows +services, systemd, Docker, and provider-advertised CultMesh commands, then +publish an Eve/CultUI keepalive surface. No ad hoc JSON manifest may become the live state owner. Debug projections are fine when they name the `.cc` record or CultMesh document behind them. diff --git a/docs/muninn.md b/docs/muninn.md index 0b13568..0a88272 100644 --- a/docs/muninn.md +++ b/docs/muninn.md @@ -116,7 +116,12 @@ recreates the `GameCult-Muninn` scheduled task and writes `-WindowStyle Hidden` and redirects logs under `C:\Meta\Odin\logs\muninn`. The `.cmd` file must not be the long-lived foreground process. -Nightwing runs Muninn as the user service `gamecult-muninn.service`. The binary -is installed at `/home/metacrat/.local/bin/muninn`, the store lives at +Nightwing Muninn is kept alive by the single Idunn supervisor through the +`nightwing-muninn` daemon target. Idunn learns that target through Odin's typed +daemon surface and invokes `scripts/health-nightwing-muninn.ps1` and +`scripts/restart-nightwing-muninn.ps1`; those scripts are health/restart +actuators only, not lifecycle owners. The binary is installed at +`/home/metacrat/.local/bin/muninn`, the store lives at `/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc`, and the -service command uses `--host nightwing --interval-seconds 15`. +restart actuator launches `serve --host nightwing --interval-seconds 15` with +PID and logs under `/home/metacrat/.local/state/gamecult/muninn`. diff --git a/scripts/health-nightwing-muninn.cmd b/scripts/health-nightwing-muninn.cmd new file mode 100644 index 0000000..cdd79c9 --- /dev/null +++ b/scripts/health-nightwing-muninn.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\health-nightwing-muninn.ps1 diff --git a/scripts/health-nightwing-muninn.ps1 b/scripts/health-nightwing-muninn.ps1 new file mode 100644 index 0000000..8e9d65d --- /dev/null +++ b/scripts/health-nightwing-muninn.ps1 @@ -0,0 +1,28 @@ +param( + [string] $SshTarget = "nightwing", + [string] $MuninnExe = "/home/metacrat/.local/bin/muninn", + [string] $StorePath = "/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc", + [string] $PidPath = "/home/metacrat/.local/state/gamecult/muninn/muninn.pid" +) + +$ErrorActionPreference = "Stop" + +$remoteScript = @" +set -eu +if [ ! -x '$MuninnExe' ]; then + echo 'Muninn executable not found at $MuninnExe' >&2 + exit 1 +fi +if [ -f '$PidPath' ] && kill -0 "`$(cat '$PidPath')" 2>/dev/null; then + : +elif pgrep -f '[m]uninn serve .*--host nightwing' >/dev/null 2>&1; then + : +else + echo 'Muninn serve process is not running on Nightwing' >&2 + exit 1 +fi +'$MuninnExe' --health --store '$StorePath' +"@ + +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget $remoteScript +exit $LASTEXITCODE diff --git a/scripts/restart-nightwing-muninn.cmd b/scripts/restart-nightwing-muninn.cmd new file mode 100644 index 0000000..1b6a169 --- /dev/null +++ b/scripts/restart-nightwing-muninn.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File E:\Projects\Odin\scripts\restart-nightwing-muninn.ps1 diff --git a/scripts/restart-nightwing-muninn.ps1 b/scripts/restart-nightwing-muninn.ps1 new file mode 100644 index 0000000..36bb2e2 --- /dev/null +++ b/scripts/restart-nightwing-muninn.ps1 @@ -0,0 +1,39 @@ +param( + [string] $SshTarget = "nightwing", + [string] $MuninnExe = "/home/metacrat/.local/bin/muninn", + [string] $StorePath = "/home/metacrat/.local/state/gamecult/muninn/muninn.telemetry.cc", + [string] $LogRoot = "/home/metacrat/.local/state/gamecult/muninn", + [int] $IntervalSeconds = 15 +) + +$ErrorActionPreference = "Stop" + +$remoteScript = @" +set -eu +mkdir -p '$LogRoot' +if [ ! -x '$MuninnExe' ]; then + echo 'Muninn executable not found at $MuninnExe' >&2 + exit 1 +fi +if [ -f '$LogRoot/muninn.pid' ] && kill -0 "`$(cat '$LogRoot/muninn.pid')" 2>/dev/null; then + kill "`$(cat '$LogRoot/muninn.pid')" 2>/dev/null || true + sleep 1 +fi +for pid in `$(pgrep -f '[m]uninn serve .*--host nightwing' 2>/dev/null || true); do + kill "`$pid" 2>/dev/null || true +done +nohup '$MuninnExe' serve \ + --store '$StorePath' \ + --log-root '$LogRoot' \ + --host nightwing \ + --interval-seconds '$IntervalSeconds' \ + > '$LogRoot/muninn-serve.out.log' \ + 2> '$LogRoot/muninn-serve.err.log' \ + < /dev/null & +echo `$! > '$LogRoot/muninn.pid' +sleep 1 +kill -0 "`$(cat '$LogRoot/muninn.pid')" 2>/dev/null +"@ + +ssh.exe -o BatchMode=yes -o ConnectTimeout=5 $SshTarget $remoteScript +exit $LASTEXITCODE diff --git a/scripts/start-idunn-local.ps1 b/scripts/start-idunn-local.ps1 index ce595bd..1665755 100644 --- a/scripts/start-idunn-local.ps1 +++ b/scripts/start-idunn-local.ps1 @@ -1,5 +1,5 @@ param( - [int] $IntervalSeconds = 30, + [int] $StaleAfterSeconds = 120, [string] $StateDir = "E:\Projects\Odin\scratch\idunn" ) @@ -8,10 +8,12 @@ $ErrorActionPreference = "Stop" $repoRoot = Split-Path -Parent $PSScriptRoot $idunnExe = Join-Path $repoRoot "target\debug\idunn.exe" $operatorAlarmCommand = Join-Path $repoRoot "scripts\notify-idunn-operator-alarm.cmd" -$logDir = Join-Path $StateDir "logs" -$pidDir = Join-Path $StateDir "pids" +$pidPath = Join-Path $StateDir "idunn.pid" +$storePath = Join-Path $StateDir "idunn.keepalive.cc" +$outLog = Join-Path $StateDir "idunn.out.log" +$errLog = Join-Path $StateDir "idunn.err.log" -New-Item -ItemType Directory -Force -Path $StateDir, $logDir, $pidDir | Out-Null +New-Item -ItemType Directory -Force -Path $StateDir | Out-Null if (-not (Test-Path -LiteralPath $idunnExe)) { Push-Location -LiteralPath $repoRoot @@ -25,168 +27,87 @@ if (-not (Test-Path -LiteralPath $idunnExe)) { } } -$watchdogs = @( - [pscustomobject]@{ - Id = "odin" - Name = "Odin all-seer" - Verse = "starfire.local" - Health = "$repoRoot\scripts\health-odin.cmd" - Restart = "$repoRoot\scripts\restart-odin.cmd" - }, - [pscustomobject]@{ - Id = "mimir-eve-dashboard" - Name = "Mimir Eve dashboard" - Verse = "starfire.local" - Health = "$repoRoot\scripts\health-mimir-eve-dashboard.cmd" - Restart = $null - }, - [pscustomobject]@{ - Id = "stonks" - Name = "Stonks market pulse" - Verse = "starfire.local" - Health = "$repoRoot\scripts\health-stonks.cmd" - Restart = "$repoRoot\scripts\restart-stonks.cmd" - }, - [pscustomobject]@{ - Id = "voidbot" - Name = "VoidBot local stack" - Verse = "starfire.local" - Health = "$repoRoot\scripts\health-voidbot.cmd" - Restart = "$repoRoot\scripts\restart-voidbot.cmd" - IntervalSeconds = 300 - }, - [pscustomobject]@{ - Id = "muninn" - Name = "Muninn telemetry Verse assembler" - Verse = "raven.local" - Health = "$repoRoot\scripts\health-muninn.cmd" - Restart = "$repoRoot\scripts\restart-muninn.cmd" - }, - [pscustomobject]@{ - Id = "idunn-swarm-deployment-coverage" - Name = "Idunn swarm deployment coverage" - Verse = "starfire.local" - Health = "$repoRoot\scripts\health-idunn-swarm-deployment-coverage.cmd" - Restart = $null - }, - [pscustomobject]@{ - Id = "yggdrasil-heimdall" - Name = "Yggdrasil Heimdall" - Verse = "yggdrasil.local" - Health = "$repoRoot\scripts\health-yggdrasil-heimdall.cmd" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-heimdall.cmd" - IntervalSeconds = 300 - }, - [pscustomobject]@{ - Id = "yggdrasil-repixelizer" - Name = "Yggdrasil Repixelizer" - Verse = "yggdrasil.local" - Health = "$repoRoot\scripts\health-yggdrasil-repixelizer.cmd" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-repixelizer.cmd" - IntervalSeconds = 300 - }, - [pscustomobject]@{ - Id = "yggdrasil-streampixels" - Name = "Yggdrasil StreamPixels" - Verse = "yggdrasil.local" - Health = "$repoRoot\scripts\health-yggdrasil-streampixels.cmd" - Deploy = "$repoRoot\scripts\deploy-yggdrasil-streampixels.cmd" - IntervalSeconds = 300 - }, - [pscustomobject]@{ - Id = "nightwing-gjallar" - Name = "Nightwing Gjallar framebuffer compositor" - Verse = "nightwing.local" - Health = "$repoRoot\scripts\health-nightwing-gjallar.cmd" - Deploy = "$repoRoot\scripts\deploy-nightwing-gjallar.cmd" - Restart = "$repoRoot\scripts\restart-nightwing-gjallar.cmd" - }, - [pscustomobject]@{ - Id = "nightwing-eve-dashboard" - Name = "Nightwing Eve dashboard broker" - Verse = "nightwing.local" - Health = "$repoRoot\scripts\health-nightwing-eve-dashboard.cmd" - Restart = "$repoRoot\scripts\restart-nightwing-eve-dashboard.cmd" - }, - [pscustomobject]@{ - Id = "nightwing-eve-browser-reference" - Name = "Nightwing Eve browser reference" - Verse = "nightwing.local" - Health = "$repoRoot\scripts\health-nightwing-eve-browser-reference.cmd" - Restart = "$repoRoot\scripts\restart-nightwing-eve-browser-reference.cmd" - } -) +function Test-IdunnSupervisorHealthy { + param( + [string] $PidPath, + [string] $StorePath, + [int] $StaleAfterSeconds + ) -function Test-LivePid { - param([string] $Path) - if (-not (Test-Path -LiteralPath $Path)) { + if (-not (Test-Path -LiteralPath $PidPath)) { return $false } - $pidText = (Get-Content -LiteralPath $Path -Raw).Trim() + + $pidText = (Get-Content -LiteralPath $PidPath -Raw).Trim() if ($pidText -notmatch "^\d+$") { - Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue return $false } + $process = Get-Process -Id ([int] $pidText) -ErrorAction SilentlyContinue if ($null -eq $process) { - Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue return $false } - return $true + + if (Test-Path -LiteralPath $StorePath) { + $storeAgeSeconds = ([DateTime]::UtcNow - (Get-Item -LiteralPath $StorePath).LastWriteTimeUtc).TotalSeconds + if ($storeAgeSeconds -le $StaleAfterSeconds) { + return $true + } + + Write-Host "Idunn swarm store is stale ($([math]::Round($storeAgeSeconds))s old). Restarting supervisor." + } else { + $processAgeSeconds = ([DateTime]::UtcNow - $process.StartTime.ToUniversalTime()).TotalSeconds + if ($processAgeSeconds -le $StaleAfterSeconds) { + return $true + } + + Write-Host "Idunn supervisor never wrote $StorePath within $StaleAfterSeconds seconds. Restarting supervisor." + } + + Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $PidPath -Force -ErrorAction SilentlyContinue + return $false } -function Start-Watchdog { - param($Watchdog) - - $pidPath = Join-Path $pidDir "$($Watchdog.Id).pid" - if (Test-LivePid -Path $pidPath) { - Write-Host "Idunn watchdog already running for $($Watchdog.Id)." - return - } - - $storePath = Join-Path $StateDir "$($Watchdog.Id).keepalive.cc" - - $startInfo = [System.Diagnostics.ProcessStartInfo]::new() - $startInfo.FileName = $idunnExe - $startInfo.WorkingDirectory = $repoRoot - $startInfo.UseShellExecute = $false - $startInfo.CreateNoWindow = $true - $startInfo.RedirectStandardOutput = $false - $startInfo.RedirectStandardError = $false - $arguments = @( - "--daemon", $Watchdog.Id, - "--name", $Watchdog.Name, - "--verse", $Watchdog.Verse, - "--store", $storePath, - "--health-command", $Watchdog.Health, - "--interval-seconds", "$(if ($Watchdog.PSObject.Properties['IntervalSeconds']) { $Watchdog.IntervalSeconds } else { $IntervalSeconds })" - ) - $shouldExecute = $false - if (-not [string]::IsNullOrWhiteSpace($Watchdog.Deploy)) { - $arguments += @("--deploy-command", $Watchdog.Deploy) - $shouldExecute = $true - } - if (-not [string]::IsNullOrWhiteSpace($Watchdog.Restart)) { - $arguments += @("--restart-command", $Watchdog.Restart) - $shouldExecute = $true - } - if ($shouldExecute) { - $arguments += @("--execute") - } - if (Test-Path -LiteralPath $operatorAlarmCommand) { - $arguments += @("--operator-alarm-command", $operatorAlarmCommand) - } - $startInfo.Arguments = Join-WindowsArguments -Arguments $arguments - - $process = [System.Diagnostics.Process]::new() - $process.StartInfo = $startInfo - [void] $process.Start() - $process.Id | Set-Content -Encoding ASCII -LiteralPath $pidPath - - Write-Host "Started Idunn watchdog $($Watchdog.Id) as PID $($process.Id)." - Write-Host " store: $storePath" +if (Test-IdunnSupervisorHealthy -PidPath $pidPath -StorePath $storePath -StaleAfterSeconds $StaleAfterSeconds) { + Write-Host "Idunn swarm supervisor already running." + return } +$arguments = @( + "--swarm-profile", "starfire-local", + "--repo-root", $repoRoot, + "--store", $storePath, + "--command-timeout-seconds", "30", + "--execute" +) + +if (Test-Path -LiteralPath $operatorAlarmCommand) { + $arguments += @("--operator-alarm-command", $operatorAlarmCommand) +} + +$process = Start-Process -FilePath $idunnExe ` + -ArgumentList $arguments ` + -WorkingDirectory $repoRoot ` + -WindowStyle Hidden ` + -PassThru ` + -RedirectStandardOutput $outLog ` + -RedirectStandardError $errLog +$process.Id | Set-Content -Encoding ASCII -LiteralPath $pidPath + +Start-Sleep -Seconds 2 +if ($process.HasExited) { + $detail = "" + if (Test-Path -LiteralPath $outLog) { $detail += Get-Content -Raw -LiteralPath $outLog } + if (Test-Path -LiteralPath $errLog) { $detail += Get-Content -Raw -LiteralPath $errLog } + throw "Idunn swarm supervisor exited immediately with code $($process.ExitCode).`n$detail" +} + +Write-Host "Started Idunn swarm supervisor as PID $($process.Id)." +Write-Host " store: $storePath" + function ConvertTo-WindowsArgument { param([string] $Value) if ($Value -notmatch '[\s"]') { @@ -199,7 +120,3 @@ function Join-WindowsArguments { param([object[]] $Arguments) return (($Arguments | ForEach-Object { ConvertTo-WindowsArgument -Value ([string] $_) }) -join " ") } - -foreach ($watchdog in $watchdogs) { - Start-Watchdog -Watchdog $watchdog -} diff --git a/src/Idunn/README.md b/src/Idunn/README.md index 58a8f7e..15840f8 100644 --- a/src/Idunn/README.md +++ b/src/Idunn/README.md @@ -50,11 +50,12 @@ watchdog. ## Current State -Idunn is a Rust daemon inside Odin's Cargo workspace. It can probe one daemon, -write desired state, health, keepalive decision, deployment request, -deployment result, restart request, restart result, and operator alarm as typed -CultMesh records, and execute deploy/restart commands when the operator -explicitly gives it authority. +Idunn is a Rust daemon inside Odin's Cargo workspace. The live local runtime is +one long-lived `idunn.exe` process that owns the whole Starfire-local swarm: +Odin, local adjunct daemons, the Yggdrasil deploy lanes, and the Nightwing +display services. Each target keeps its own interval, health command, and +deploy/restart authority, but the scheduler and continuity witness now belong +to one Rust process instead of a PowerShell-herded pile of one-daemon workers. ```text scratch/idunn/idunn.keepalive.cc @@ -69,16 +70,17 @@ npm run idunn:build npm run idunn:start -- --daemon demo --health-command "exit 0" ``` -Install the local Starfire boot watchdogs: +Install the local Starfire boot watchdog: ```powershell .\scripts\install-idunn-startup.ps1 ``` -That task starts Idunn loops for Odin, Stonks, the enforced Yggdrasil source -artifact targets, and the Nightwing display services at user logon. The current -Mimir dashboard is observed but not restarted until its restart authority is -named. +That task starts one `idunn.exe` swarm supervisor at user logon. The Rust +runtime owns the target catalog for Odin, Stonks, Muninn, the enforced +Yggdrasil source artifact lanes, and the Nightwing display services. The +current Mimir dashboard is observed but not restarted until its restart +authority is named. It also starts `idunn-swarm-deployment-coverage`, which watches the deployment target catalog in `scripts/idunn-deployment-targets.ps1`. A repo/service is not @@ -103,6 +105,12 @@ To keep watching on a resident interval: npm run idunn:start -- --daemon demo --health-command "exit 0" --interval-seconds 30 ``` +To run the built-in Starfire-local swarm profile directly: + +```powershell +npm run idunn:start -- --swarm-profile starfire-local --repo-root E:\Projects\Odin --execute +``` + Optional store override: ```powershell @@ -147,9 +155,10 @@ Pages remains external-owned. - `idunn.restart_result.v1` - `idunn.operator_alarm.v1` -The next cuts are direct Odin service/provider ingestion, named adapters for -systemd, Windows services, Docker, and provider-advertised CultMesh commands, -and a Bifrost-owned operator notification request record for alarms. +The next cuts are promoting the built-in target catalog into Odin-ingested +service/provider records, adding named adapters for systemd, Windows services, +Docker, and provider-advertised CultMesh commands, and replacing the local +operator alarm bridge with a fully Bifrost-owned notification request record. ## Boundaries