use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::thread; use anyhow::{bail, Context, Result}; use crate::config::Config; use crate::ssh; pub const HUB_IMAGES: &[&str] = &[ "sope/prometheus:latest", "sope/loki:latest", "sope/tempo:latest", "sope/grafana:latest", "sope/caddy:latest", ]; pub const SAT_IMAGES: &[&str] = &["sope/alloy:latest", "sope/cadvisor:latest"]; pub const HUB_TARS: &[&str] = &[ "prometheus.tar.gz", "loki.tar.gz", "tempo.tar.gz", "grafana.tar.gz", "caddy.tar.gz", ]; pub const SAT_TARS: &[&str] = &["alloy.tar.gz", "cadvisor.tar.gz"]; #[derive(Debug, Clone, Copy)] pub enum ComposeAction { Start, Stop, Restart, } impl ComposeAction { pub fn as_str(self) -> &'static str { match self { Self::Start => "start", Self::Stop => "stop", Self::Restart => "restart", } } } fn repo_root() -> PathBuf { if let Ok(out) = Command::new("git") .args(["rev-parse", "--show-toplevel"]) .output() { if out.status.success() { return PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()); } } std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) } fn is_darwin() -> bool { cfg!(target_os = "macos") } /// CPU arch of the Linux images / remote hosts (not the operator OS). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TargetArch { Amd64, Arm64, } impl TargetArch { pub fn parse(s: &str) -> Result { match s.trim().to_ascii_lowercase().as_str() { "x86_64" | "amd64" | "x86_64-linux" => Ok(Self::Amd64), "aarch64" | "arm64" | "aarch64-linux" => Ok(Self::Arm64), other => bail!("unsupported arch {other:?} (use amd64 or arm64)"), } } pub fn docker_platform(self) -> &'static str { match self { Self::Amd64 => "linux/amd64", Self::Arm64 => "linux/arm64", } } pub fn linux_system(self) -> &'static str { match self { Self::Amd64 => "x86_64-linux", Self::Arm64 => "aarch64-linux", } } pub fn docker_arch(self) -> &'static str { match self { Self::Amd64 => "amd64", Self::Arm64 => "arm64", } } pub fn host_default() -> Self { if cfg!(target_arch = "aarch64") { Self::Arm64 } else { Self::Amd64 } } } /// Probe `uname -m` on the deploy target (hub, or named satellite). pub fn resolve_deploy_arch( cfg: &Config, target: crate::cli::DeployTarget, name: Option<&str>, ) -> Result { if let Ok(v) = std::env::var("SOPE_LINUX_SYSTEM") { if !v.is_empty() { return TargetArch::parse(&v); } } let (user, host) = match target { crate::cli::DeployTarget::Satellite => { let n = name.context("--name required to detect satellite arch")?; let sat = cfg.satellite(n)?; (sat.user.as_str(), sat.host.as_str()) } // all / hub: build for the hub (satellites on another arch need a separate deploy) _ => (cfg.hub.user.as_str(), cfg.hub.host.as_str()), }; let out = ssh::ssh_capture(user, host, "uname -m") .with_context(|| format!("detect arch on {user}@{host}"))?; let arch = TargetArch::parse(out.trim())?; println!( "→ remote {host} is {} — building/loading {} images", out.trim(), arch.docker_platform() ); Ok(arch) } pub fn assert_local_images_arch(arch: TargetArch) -> Result<()> { let probe = HUB_IMAGES[0]; let output = Command::new("docker") .args([ "image", "inspect", probe, "--format", "{{.Architecture}}", ]) .output() .context("docker image inspect")?; if !output.status.success() { bail!("image {probe} missing locally — run without --skip-build"); } let got = String::from_utf8_lossy(&output.stdout); let got = got.trim(); if got != arch.docker_arch() { bail!( "local {probe} is {got}, remote needs {} — rebuild (drop --skip-build) \ or set SOPE_LINUX_SYSTEM={}", arch.docker_arch(), arch.linux_system() ); } Ok(()) } fn run_streaming(mut cmd: Command, log: &mut dyn FnMut(&str)) -> Result<()> { cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); let mut child = cmd.spawn().context("failed to start command")?; let stdout = child.stdout.take().context("no stdout")?; let stderr = child.stderr.take().context("no stderr")?; let (tx, rx) = std::sync::mpsc::channel::(); let tx_out = tx.clone(); let tx_err = tx; let t_out = thread::spawn(move || { for line in BufReader::new(stdout).lines().map_while(Result::ok) { let _ = tx_out.send(line); } }); let t_err = thread::spawn(move || { for line in BufReader::new(stderr).lines().map_while(Result::ok) { let _ = tx_err.send(line); } }); for line in rx { log(&line); } let _ = t_out.join(); let _ = t_err.join(); let status = child.wait().context("waiting for process")?; if !status.success() { bail!("command failed (code {:?})", status.code()); } Ok(()) } fn images_flake_attr(arch: TargetArch) -> String { // Pin the flake output — pure eval ignores SOPE_LINUX_SYSTEM / getEnv. format!(".#packages.{}.images", arch.linux_system()) } fn image_tars_dir(root: &Path, arch: TargetArch) -> PathBuf { root.join(format!(".sope-image-tars-{}", arch.docker_arch())) } fn nix_build_images_native( root: &Path, arch: TargetArch, log: &mut dyn FnMut(&str), ) -> Result<()> { let attr = images_flake_attr(arch); log(&format!("→ nix build {attr}")); let mut cmd = Command::new("nix"); cmd.args(["build", &attr, "--out-link", "result-images"]) .current_dir(root); run_streaming(cmd, log).context("nix build — is Nix installed?")?; Ok(()) } // dockerTools targets Linux; on Darwin (and for cross-arch) build in a Nix container. fn nix_build_images_via_docker( root: &Path, arch: TargetArch, log: &mut dyn FnMut(&str), ) -> Result<()> { let platform = arch.docker_platform(); let linux_system = arch.linux_system(); let attr = images_flake_attr(arch); let tars = image_tars_dir(root, arch); let tars_name = tars .file_name() .and_then(|s| s.to_str()) .unwrap_or(".sope-image-tars"); // Separate Nix store per arch — a shared volume keeps aarch64 paths and // silently re-exports the wrong images under qemu/amd64. let nix_vol = format!("sope-nix-store-{}", arch.docker_arch()); log(&format!( "→ build images via Nix container ({platform}, flake {attr}, volume {nix_vol})" )); // Arch check: nixos/nix has no sed — grep only. let script = format!( "set -euo pipefail\n\ echo \"container uname=$(uname -m) → expect build for {linux_system}\"\n\ nix --extra-experimental-features 'nix-command flakes' build {attr} --out-link /tmp/sope-images\n\ mkdir -p /src/{tars_name}\n\ rm -f /src/{tars_name}/*\n\ cp -L /tmp/sope-images/* /src/{tars_name}/\n\ cfg=$(tar -tzf /src/{tars_name}/prometheus.tar.gz | grep -E '^[0-9a-f]+\\.json$' | head -1)\n\ echo \"checking $cfg for architecture={docker_arch}\"\n\ if ! tar -xOzf /src/{tars_name}/prometheus.tar.gz \"$cfg\" | grep -q '\"architecture\": \"{docker_arch}\"'; then\n\ echo \"error: prometheus.tar.gz is not {docker_arch}\" >&2\n\ tar -xOzf /src/{tars_name}/prometheus.tar.gz \"$cfg\" | grep architecture || true\n\ exit 1\n\ fi\n\ echo \"arch ok: {docker_arch}\"\n", linux_system = linux_system, attr = attr, tars_name = tars_name, docker_arch = arch.docker_arch(), ); // qemu/amd64 on Apple Silicon: Nix's seccomp BPF fails with // "unable to load seccomp BPF program: Invalid argument". let mut cmd = Command::new("docker"); cmd.args([ "run", "--rm", "--platform", platform, "--security-opt", "seccomp=unconfined", "-e", "NIX_CONFIG=filter-syscalls = false", "-v", &format!("{}:/src", root.display()), "-v", &format!("{nix_vol}:/nix"), "-w", "/src", "nixos/nix:2.24.10", "sh", "-c", &script, ]); run_streaming(cmd, log).context("docker run nixos/nix")?; let farm = root.join("result-images"); let _ = std::fs::remove_file(&farm); let _ = std::fs::remove_dir_all(&farm); std::os::unix::fs::symlink(&tars, &farm) .with_context(|| format!("symlink {} → {}", farm.display(), tars.display()))?; Ok(()) } fn docker_load_farm(farm: &Path, log: &mut dyn FnMut(&str)) -> Result<()> { let entries = std::fs::read_dir(farm) .with_context(|| format!("reading {}", farm.display()))?; for entry in entries { let entry = entry?; let path = entry.path(); let name = path .file_name() .and_then(|n| n.to_str()) .unwrap_or_default(); if !name.contains(".tar") { continue; } log(&format!("→ docker load < {}", path.display())); let mut cmd = Command::new("docker"); cmd.args(["load", "-i"]).arg(&path); run_streaming(cmd, log).with_context(|| format!("docker load {}", path.display()))?; } Ok(()) } pub fn build_images_for(arch: TargetArch) -> Result<()> { build_images_logged(arch, |line| println!("{line}")) } pub fn build_images_logged(arch: TargetArch, mut log: impl FnMut(&str)) -> Result<()> { let root = repo_root(); log(&format!( "→ building sope images for {} (from {})", arch.docker_platform(), root.display() )); // Cross-arch or Darwin: always use a Linux container matching the target. let cross = arch != TargetArch::host_default(); if is_darwin() || cross { nix_build_images_via_docker(&root, arch, &mut log)?; } else if let Err(err) = nix_build_images_native(&root, arch, &mut log) { log(&format!( "note: native build failed ({err:#}), trying via Docker" )); nix_build_images_via_docker(&root, arch, &mut log)?; } let farm = root.join("result-images"); docker_load_farm(&farm, &mut log)?; assert_local_images_arch(arch)?; Ok(()) } pub fn image_farm_public() -> Result { let root = repo_root(); for name in [ "result-images", ".sope-image-tars-amd64", ".sope-image-tars-arm64", ".sope-image-tars", ] { let p = root.join(name); if p.is_dir() { return Ok(p); } } bail!("no result-images — run `sope build` / deploy without --skip-build first") } pub fn compose_hub(cfg: &Config, action: ComposeAction) -> Result<()> { let verb = action.as_str(); println!("→ docker compose {verb} (hub)"); ssh::ssh( &cfg.hub.user, &cfg.hub.host, &format!("cd {} && docker compose {verb}", cfg.hub.path), )?; Ok(()) } pub fn compose_satellite(cfg: &Config, name: &str, action: ComposeAction) -> Result<()> { let sat = cfg.satellite(name)?; let verb = action.as_str(); println!("→ docker compose {verb} (satellite {name})"); ssh::ssh( &sat.user, &sat.host, &format!("cd {} && docker compose {verb}", sat.path), )?; Ok(()) } fn destroy_remote_script(path: &str, images: &[&str]) -> String { let path_q = ssh::shell_quote(path); let mut img_rm = String::new(); for img in images { img_rm.push_str(&format!( "docker image rm -f {} >/dev/null 2>&1 || true\n", ssh::shell_quote(img) )); } format!( r#"set -eu path={path_q} if [ -d "$path" ]; then if [ -f "$path/docker-compose.yml" ] || [ -f "$path/compose.yml" ] || [ -f "$path/compose.yaml" ]; then echo "→ docker compose down -v --remove-orphans ($path)" (cd "$path" && docker compose down -v --remove-orphans) || true fi echo "→ rm -rf $path" rm -rf -- "$path" else echo "→ no directory $path (already absent)" fi # leftover atomic-deploy dirs rm -rf -- "$path".prev "$path".next-* echo "→ removing sope images" {img_rm}echo "→ done" "# ) } pub fn destroy_hub(cfg: &Config) -> Result<()> { println!("→ destroy hub {}@{}", cfg.hub.user, cfg.hub.host); let script = destroy_remote_script(&cfg.hub.path, HUB_IMAGES); ssh::ssh(&cfg.hub.user, &cfg.hub.host, &script)?; println!("hub destroyed on {}", cfg.hub.host); Ok(()) } pub fn destroy_satellite(cfg: &Config, name: &str) -> Result<()> { let sat = cfg.satellite(name)?; println!("→ destroy satellite {name} ({}@{})", sat.user, sat.host); let script = destroy_remote_script(&sat.path, SAT_IMAGES); ssh::ssh(&sat.user, &sat.host, &script)?; println!("satellite {name} destroyed on {}", sat.host); Ok(()) } pub fn destroy_all(cfg: &Config) -> Result<()> { for sat in &cfg.satellites { destroy_satellite(cfg, &sat.name)?; } destroy_hub(cfg)?; Ok(()) } pub fn status_hub(cfg: &Config) -> Result<()> { println!("=== hub {} ===", cfg.hub.host); let services = crate::status::status_hub_data(cfg)?; println!("{}", crate::status::format_services_table(&services)); Ok(()) } pub fn status_satellite(cfg: &Config, name: &str) -> Result<()> { let sat = cfg.satellite(name)?; println!("=== satellite {} ({}) ===", sat.name, sat.host); let services = crate::status::status_satellite_data(cfg, name)?; println!("{}", crate::status::format_services_table(&services)); Ok(()) }