use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use crate::config::Config; use crate::deploy; use crate::render; use crate::ssh; const STATE_VERSION: u32 = 1; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Change { Create, UpdateConfigs { changed: Vec }, UpdateImages { changed_files: Vec }, Noop, } #[derive(Debug, Clone)] pub struct UnitPlan { pub label: String, pub user: String, pub host: String, pub path: String, pub change: Change, pub local_dir: PathBuf, pub images: &'static [&'static str], pub tars: &'static [&'static str], /// Desired hashes after render (written to state on success). desired_files: BTreeMap, desired_images: BTreeMap, } impl UnitPlan { pub fn needs_images(&self) -> bool { matches!(self.change, Change::Create | Change::UpdateImages { .. }) } } #[derive(Debug, Clone, Serialize, Deserialize, Default)] struct StateFile { version: u32, #[serde(default)] units: BTreeMap, } #[derive(Debug, Clone, Serialize, Deserialize)] struct UnitState { user: String, host: String, path: String, files: BTreeMap, images: BTreeMap, #[serde(default)] applied_at: u64, } /// `sope.toml` → `sope.state.json` (next to the config). pub fn state_path(config: &Path) -> PathBuf { config.with_extension("state.json") } fn load_state(path: &Path) -> Result { if !path.exists() { return Ok(StateFile { version: STATE_VERSION, units: BTreeMap::new(), }); } let raw = fs::read_to_string(path) .with_context(|| format!("read state {}", path.display()))?; let mut st: StateFile = serde_json::from_str(&raw).context("invalid sope.state.json")?; if st.version == 0 { st.version = STATE_VERSION; } Ok(st) } fn save_state(path: &Path, st: &StateFile) -> Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let body = serde_json::to_string_pretty(st).context("serialize state")?; let tmp = path.with_extension("state.json.tmp"); fs::write(&tmp, format!("{body}\n")).with_context(|| format!("write {}", tmp.display()))?; fs::rename(&tmp, path).with_context(|| format!("rename → {}", path.display()))?; Ok(()) } fn now_unix() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } fn work_dir() -> PathBuf { std::env::temp_dir().join(format!("sope-plan-{}", std::process::id())) } fn hash_bytes(data: &[u8]) -> String { let mut h: u64 = 0xcbf29ce484222325; for b in data { h ^= u64::from(*b); h = h.wrapping_mul(0x100000001b3); } format!("{h:016x}") } fn hash_file(path: &Path) -> Result { let data = fs::read(path).with_context(|| format!("read {}", path.display()))?; Ok(hash_bytes(&data)) } fn walk_files(dir: &Path) -> Result> { let mut out = BTreeMap::new(); walk_files_inner(dir, dir, &mut out)?; Ok(out) } fn walk_files_inner(root: &Path, dir: &Path, out: &mut BTreeMap) -> Result<()> { for ent in fs::read_dir(dir).with_context(|| format!("read_dir {}", dir.display()))? { let ent = ent?; let path = ent.path(); if path.is_dir() { walk_files_inner(root, &path, out)?; } else if path.is_file() { let rel = path .strip_prefix(root) .unwrap() .to_string_lossy() .replace('\\', "/"); out.insert(rel, hash_file(&path)?); } } Ok(()) } fn remote_exists(user: &str, host: &str, path: &str) -> Result { let q = ssh::shell_quote(path); let out = ssh::ssh_capture( user, host, &format!("if [ -f {q}/docker-compose.yml ]; then echo yes; else echo no; fi"), )?; Ok(out.trim() == "yes") } fn remote_content_fnv(user: &str, host: &str, remote_file: &str) -> Result> { let q = ssh::shell_quote(remote_file); let script = format!( r#"if [ ! -f {q} ]; then echo MISSING; exit 0; fi if command -v python3 >/dev/null 2>&1; then python3 -c 'import pathlib,sys;d=pathlib.Path(sys.argv[1]).read_bytes();h=0xcbf29ce484222325 for b in d: h^=b; h=(h*0x100000001b3)&0xffffffffffffffff print(f"{{h:016x}}")' {q} else echo UNKNOWN fi"# ); let out = ssh::ssh_capture(user, host, &script)?; let t = out.trim(); if t == "MISSING" || t == "UNKNOWN" { return Ok(None); } Ok(Some(t.to_string())) } fn local_image_id(image: &str) -> Result> { let output = Command::new("docker") .args(["image", "inspect", image, "--format", "{{.Id}}"]) .output() .context("docker image inspect")?; if !output.status.success() { return Ok(None); } let id = String::from_utf8_lossy(&output.stdout).trim().to_string(); if id.is_empty() { return Ok(None); } Ok(Some(id)) } fn remote_image_id(user: &str, host: &str, image: &str) -> Result> { let img_q = ssh::shell_quote(image); let out = ssh::ssh_capture( user, host, &format!("docker image inspect {img_q} --format '{{{{.Id}}}}' 2>/dev/null || true"), )?; let id = out.trim(); if id.is_empty() { return Ok(None); } Ok(Some(id.to_string())) } fn collect_local_images(images: &[&str]) -> Result> { let mut m = BTreeMap::new(); for img in images { if let Some(id) = local_image_id(img)? { m.insert((*img).to_string(), id); } } Ok(m) } fn collect_remote_images( user: &str, host: &str, images: &[&str], ) -> Result> { let mut m = BTreeMap::new(); for img in images { if let Some(id) = remote_image_id(user, host, img)? { m.insert((*img).to_string(), id); } } Ok(m) } fn collect_remote_files( user: &str, host: &str, remote_path: &str, keys: &BTreeMap, ) -> Result> { let mut m = BTreeMap::new(); for rel in keys.keys() { let remote_file = format!("{remote_path}/{rel}"); if let Some(h) = remote_content_fnv(user, host, &remote_file)? { m.insert(rel.clone(), h); } } Ok(m) } fn diff_maps( desired: &BTreeMap, recorded: &BTreeMap, ) -> Vec { let mut changed = Vec::new(); for (k, v) in desired { match recorded.get(k) { Some(h) if h == v => {} _ => changed.push(k.clone()), } } for k in recorded.keys() { if !desired.contains_key(k) { changed.push(k.clone()); } } changed.sort(); changed.dedup(); changed } fn images_changed( desired: &BTreeMap, recorded: &BTreeMap, ) -> bool { if desired.len() != recorded.len() { return true; } for (k, v) in desired { match recorded.get(k) { Some(id) if id == v => {} _ => return true, } } false } fn decide_change( desired_files: &BTreeMap, desired_images: &BTreeMap, recorded: Option<&UnitState>, user: &str, host: &str, path: &str, ) -> Result { match recorded { None => { // No state: probe remote (bootstrap / import). if !remote_exists(user, host, path)? { return Ok(Change::Create); } let remote_files = collect_remote_files(user, host, path, desired_files)?; let img_list: Vec<&str> = desired_images.keys().map(|s| s.as_str()).collect(); let remote_images = collect_remote_images(user, host, &img_list)?; let file_diff = diff_maps(desired_files, &remote_files); if images_changed(desired_images, &remote_images) { Ok(Change::UpdateImages { changed_files: file_diff, }) } else if !file_diff.is_empty() { Ok(Change::UpdateConfigs { changed: file_diff, }) } else { Ok(Change::Noop) } } Some(st) => { if st.host != host || st.path != path || st.user != user { // Resource moved — full redeploy to new address. return Ok(Change::Create); } let file_diff = diff_maps(desired_files, &st.files); if images_changed(desired_images, &st.images) { Ok(Change::UpdateImages { changed_files: file_diff, }) } else if !file_diff.is_empty() { Ok(Change::UpdateConfigs { changed: file_diff, }) } else { Ok(Change::Noop) } } } } fn refresh_unit_into_state( st: &mut StateFile, label: &str, user: &str, host: &str, path: &str, desired_files: &BTreeMap, images: &[&str], ) -> Result<()> { if !remote_exists(user, host, path)? { st.units.remove(label); return Ok(()); } let files = collect_remote_files(user, host, path, desired_files)?; let imgs = collect_remote_images(user, host, images)?; st.units.insert( label.to_string(), UnitState { user: user.into(), host: host.into(), path: path.into(), files, images: imgs, applied_at: now_unix(), }, ); Ok(()) } fn plan_unit( state: &StateFile, label: String, user: &str, host: &str, path: &str, local_dir: PathBuf, images: &'static [&'static str], tars: &'static [&'static str], ) -> Result { let desired_files = walk_files(&local_dir)?; let desired_images = collect_local_images(images)?; let change = decide_change( &desired_files, &desired_images, state.units.get(&label), user, host, path, )?; Ok(UnitPlan { label, user: user.into(), host: host.into(), path: path.into(), change, local_dir, images, tars, desired_files, desired_images, }) } fn render_hub_dir(cfg: &Config) -> Result { let dir = work_dir().join("hub"); let _ = fs::remove_dir_all(&dir); render::render_hub(cfg, &dir)?; Ok(dir) } fn render_sat_dir(cfg: &Config, name: &str) -> Result { let dir = work_dir().join("sat").join(name); let _ = fs::remove_dir_all(&dir); render::render_satellite(cfg, name, &dir)?; Ok(dir) } pub struct PlanOpts { pub config_path: PathBuf, pub refresh: bool, } pub fn plan_hub(cfg: &Config, opts: &PlanOpts) -> Result { let sp = state_path(&opts.config_path); let mut st = load_state(&sp)?; let dir = render_hub_dir(cfg)?; let files = walk_files(&dir)?; if opts.refresh { println!("→ refresh state from remote (hub)"); refresh_unit_into_state( &mut st, "hub", &cfg.hub.user, &cfg.hub.host, &cfg.hub.path, &files, deploy::HUB_IMAGES, )?; save_state(&sp, &st)?; } plan_unit( &st, "hub".into(), &cfg.hub.user, &cfg.hub.host, &cfg.hub.path, dir, deploy::HUB_IMAGES, deploy::HUB_TARS, ) } pub fn plan_satellite(cfg: &Config, name: &str, opts: &PlanOpts) -> Result { let sat = cfg.satellite(name)?; let label = format!("satellite:{name}"); let sp = state_path(&opts.config_path); let mut st = load_state(&sp)?; let dir = render_sat_dir(cfg, name)?; let files = walk_files(&dir)?; if opts.refresh { println!("→ refresh state from remote ({label})"); refresh_unit_into_state( &mut st, &label, &sat.user, &sat.host, &sat.path, &files, deploy::SAT_IMAGES, )?; save_state(&sp, &st)?; } plan_unit( &st, label, &sat.user, &sat.host, &sat.path, dir, deploy::SAT_IMAGES, deploy::SAT_TARS, ) } pub fn plan_all(cfg: &Config, opts: &PlanOpts) -> Result> { let sp = state_path(&opts.config_path); let mut st = load_state(&sp)?; if opts.refresh { println!("→ refresh state from remotes"); let hub_dir = render_hub_dir(cfg)?; let hub_files = walk_files(&hub_dir)?; refresh_unit_into_state( &mut st, "hub", &cfg.hub.user, &cfg.hub.host, &cfg.hub.path, &hub_files, deploy::HUB_IMAGES, )?; for sat in &cfg.satellites { let dir = render_sat_dir(cfg, &sat.name)?; let files = walk_files(&dir)?; refresh_unit_into_state( &mut st, &format!("satellite:{}", sat.name), &sat.user, &sat.host, &sat.path, &files, deploy::SAT_IMAGES, )?; } save_state(&sp, &st)?; println!("→ wrote {}", sp.display()); } let mut plans = vec![plan_unit( &st, "hub".into(), &cfg.hub.user, &cfg.hub.host, &cfg.hub.path, render_hub_dir(cfg)?, deploy::HUB_IMAGES, deploy::HUB_TARS, )?]; for sat in &cfg.satellites { plans.push(plan_unit( &st, format!("satellite:{}", sat.name), &sat.user, &sat.host, &sat.path, render_sat_dir(cfg, &sat.name)?, deploy::SAT_IMAGES, deploy::SAT_TARS, )?); } Ok(plans) } pub fn print_plans(plans: &[UnitPlan]) { for p in plans { println!("{} {}@{}:{}", p.label, p.user, p.host, p.path); match &p.change { Change::Noop => println!(" ✓ up to date"), Change::Create => println!(" + create (configs + images + compose up)"), Change::UpdateConfigs { changed } => { println!(" ~ sync configs ({} file(s)) + compose up", changed.len()); for f in changed { println!(" {f}"); } } Change::UpdateImages { changed_files } => { println!(" ↻ refresh images — full atomic deploy"); for f in changed_files { println!(" ~ {f}"); } } } } } fn record_unit(config_path: &Path, plan: &UnitPlan) -> Result<()> { let sp = state_path(config_path); let mut st = load_state(&sp)?; st.version = STATE_VERSION; st.units.insert( plan.label.clone(), UnitState { user: plan.user.clone(), host: plan.host.clone(), path: plan.path.clone(), files: plan.desired_files.clone(), images: plan.desired_images.clone(), applied_at: now_unix(), }, ); // Drop satellites removed from sope.toml when planning "all" — handled by prune. save_state(&sp, &st)?; Ok(()) } pub fn prune_state(config_path: &Path, cfg: &Config) -> Result<()> { let sp = state_path(config_path); let mut st = load_state(&sp)?; let mut keep = std::collections::HashSet::new(); keep.insert("hub".to_string()); for sat in &cfg.satellites { keep.insert(format!("satellite:{}", sat.name)); } st.units.retain(|k, _| keep.contains(k)); save_state(&sp, &st)?; Ok(()) } pub fn forget_unit(config_path: &Path, label: &str) -> Result<()> { let sp = state_path(config_path); let mut st = load_state(&sp)?; st.units.remove(label); save_state(&sp, &st)?; Ok(()) } pub fn apply_unit(plan: &UnitPlan, full: bool, config_path: &Path) -> Result<()> { let change = if full { match &plan.change { Change::Create => Change::Create, _ => Change::UpdateImages { changed_files: vec![], }, } } else { plan.change.clone() }; match change { Change::Noop => { println!("→ {} already up to date — skip", plan.label); // Still refresh state timestamps/desired if missing (bootstrap noop). if !state_path(config_path).exists() || load_state(&state_path(config_path))? .units .get(&plan.label) .is_none() { record_unit(config_path, plan)?; } Ok(()) } Change::UpdateConfigs { changed } => { println!( "→ {} config sync ({} file(s)) → {}@{}:{}", plan.label, changed.len(), plan.user, plan.host, plan.path ); for f in &changed { println!(" ~ {f}"); } ssh::put_dir(&plan.user, &plan.host, &plan.local_dir, &plan.path)?; let path_q = ssh::shell_quote(&plan.path); ssh::ssh_live( &plan.user, &plan.host, &format!("cd {path_q} && docker compose up -d --remove-orphans"), )?; record_unit(config_path, plan)?; println!("→ {} configs applied (state updated)", plan.label); Ok(()) } Change::Create | Change::UpdateImages { .. } => { println!( "→ {} full atomic deploy → {}@{}:{}", plan.label, plan.user, plan.host, plan.path ); let farm = deploy::image_farm_public()?; let tars: Vec<(PathBuf, &str)> = plan.tars.iter().map(|n| (farm.join(n), *n)).collect(); ssh::atomic_deploy( &plan.user, &plan.host, &plan.path, &plan.local_dir, &tars, plan.images, )?; // Re-read local image IDs after possible rebuild/load. let mut plan = plan.clone(); plan.desired_images = collect_local_images(plan.images)?; record_unit(config_path, &plan)?; println!("→ {} deployed (state updated)", plan.label); Ok(()) } } } pub fn apply_plans(plans: &[UnitPlan], full: bool, config_path: &Path) -> Result<()> { for p in plans { apply_unit(p, full, config_path)?; } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn fnv_stable() { assert_eq!(hash_bytes(b"hello"), hash_bytes(b"hello")); assert_ne!(hash_bytes(b"hello"), hash_bytes(b"world")); } #[test] fn state_path_next_to_toml() { assert_eq!( state_path(Path::new("sope.toml")), PathBuf::from("sope.state.json") ); assert_eq!( state_path(Path::new("/tmp/x/sope.toml")), PathBuf::from("/tmp/x/sope.state.json") ); } #[test] fn state_roundtrip() { let dir = std::env::temp_dir().join(format!("sope-state-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); let path = dir.join("sope.state.json"); let mut st = StateFile { version: STATE_VERSION, units: BTreeMap::new(), }; st.units.insert( "hub".into(), UnitState { user: "root".into(), host: "h".into(), path: "/opt/sope/hub".into(), files: BTreeMap::from([("docker-compose.yml".into(), "abc".into())]), images: BTreeMap::from([("sope/grafana:latest".into(), "sha256:1".into())]), applied_at: 1, }, ); save_state(&path, &st).unwrap(); let loaded = load_state(&path).unwrap(); assert_eq!(loaded.units["hub"].files["docker-compose.yml"], "abc"); let _ = fs::remove_dir_all(&dir); } #[test] fn diff_maps_detects() { let a = BTreeMap::from([("a".into(), "1".into())]); let b = BTreeMap::from([("a".into(), "2".into())]); assert_eq!(diff_maps(&a, &b), vec!["a"]); assert!(diff_maps(&a, &a).is_empty()); } }