use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use anyhow::{bail, Context, Result}; use crate::progress::{self, UploadBar}; /// Write size to ssh stdin. macOS `scp` dies around ~256 KiB with /// `ssh_packet_write_poll: Result too large`; exec-channel streaming is fine /// (config `tar|ssh` already works). Append fallback stays under that scp cliff. const STREAM_WRITE: usize = 32 * 1024; const APPEND_CHUNK: usize = 128 * 1024; fn ssh_args(target: &str, remote_cmd: &str) -> Vec { vec![ "-o".into(), "BatchMode=yes".into(), "-o".into(), "StrictHostKeyChecking=accept-new".into(), "-o".into(), "IPQoS=none".into(), target.into(), remote_cmd.into(), ] } pub fn shell_quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) } pub fn ssh(user: &str, host: &str, remote_cmd: &str) -> Result<()> { let target = format!("{user}@{host}"); let status = Command::new("ssh") .args(ssh_args(&target, remote_cmd)) .stdin(Stdio::null()) .status() .context("failed to start ssh — is it installed?")?; if !status.success() { bail!("ssh {target} failed (code {:?})", status.code()); } Ok(()) } /// Like [`ssh`], but streams remote stdout/stderr to the local terminal (activate steps). pub fn ssh_live(user: &str, host: &str, remote_cmd: &str) -> Result<()> { let target = format!("{user}@{host}"); let status = Command::new("ssh") .args(ssh_args(&target, remote_cmd)) .stdin(Stdio::null()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .status() .context("failed to start ssh — is it installed?")?; if !status.success() { bail!("ssh {target} failed (code {:?})", status.code()); } Ok(()) } pub fn ssh_capture(user: &str, host: &str, remote_cmd: &str) -> Result { let target = format!("{user}@{host}"); let output = Command::new("ssh") .args(ssh_args(&target, remote_cmd)) .stdin(Stdio::null()) .output() .context("failed to start ssh")?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); bail!("ssh {target} failed: {stderr}"); } Ok(String::from_utf8_lossy(&output.stdout).into_owned()) } fn copy_to_ssh_stdin( user: &str, host: &str, remote_cmd: &str, local: &Path, write_size: usize, mut on_bytes: impl FnMut(u64), ) -> Result<()> { let target = format!("{user}@{host}"); let mut child = Command::new("ssh") .args(ssh_args(&target, remote_cmd)) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() .context("ssh upload")?; let mut stdin = child.stdin.take().context("no ssh stdin")?; let mut file = File::open(local).with_context(|| format!("open {}", local.display()))?; let mut buf = vec![0u8; write_size]; let mut sent = 0u64; loop { let n = file.read(&mut buf).context("read local file")?; if n == 0 { break; } stdin.write_all(&buf[..n]).context("write ssh stdin")?; sent += n as u64; on_bytes(sent); } drop(stdin); let output = child.wait_with_output().context("wait ssh upload")?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); bail!("ssh upload to {target} failed: {stderr}"); } Ok(()) } fn put_file_stream( user: &str, host: &str, local: &Path, remote: &str, on_bytes: impl FnMut(u64), ) -> Result<()> { let cmd = format!("cat > {}", shell_quote(remote)); copy_to_ssh_stdin(user, host, &cmd, local, STREAM_WRITE, on_bytes) } fn put_file_append_chunks( user: &str, host: &str, local: &Path, remote: &str, mut on_bytes: impl FnMut(u64), ) -> Result<()> { let remote_q = shell_quote(remote); ssh(user, host, &format!("rm -f {remote_q} && : > {remote_q}"))?; let mut file = File::open(local).with_context(|| format!("open {}", local.display()))?; let mut buf = vec![0u8; APPEND_CHUNK]; let mut part = 0u32; let mut absolute = 0u64; loop { let n = file.read(&mut buf).context("read chunk")?; if n == 0 { break; } let tmp = std::env::temp_dir().join(format!( "sope-up-{}-{part}", std::process::id() )); fs::write(&tmp, &buf[..n])?; let cmd = format!("cat >> {remote_q}"); let base = absolute; let res = copy_to_ssh_stdin(user, host, &cmd, &tmp, STREAM_WRITE, |s| { on_bytes(base + s); }); let _ = fs::remove_file(&tmp); res.with_context(|| format!("append chunk {part}"))?; absolute += n as u64; part += 1; } on_bytes(absolute); Ok(()) } pub fn put_file( user: &str, host: &str, local: &Path, remote: &str, mut on_progress: impl FnMut(u64, u64), ) -> Result<()> { let total = fs::metadata(local) .with_context(|| format!("stat {}", local.display()))? .len(); match put_file_stream(user, host, local, remote, |sent| on_progress(sent, total)) { Ok(()) => Ok(()), Err(e) => { eprintln!("warning: stream upload failed ({e:#}); retrying in 128KiB appends"); let _ = ssh(user, host, &format!("rm -f {}", shell_quote(remote))); put_file_append_chunks(user, host, local, remote, |sent| on_progress(sent, total)) } } } pub fn put_dir(user: &str, host: &str, local: &Path, remote_path: &str) -> Result<()> { let target = format!("{user}@{host}"); let remote_q = shell_quote(remote_path); ssh(user, host, &format!("mkdir -p {remote_q}"))?; // COPYFILE_DISABLE: skip macOS xattrs that Linux tar warns about. let mut tar = Command::new("tar") .env("COPYFILE_DISABLE", "1") .args(["-C"]) .arg(local) .args(["-cf", "-", "."]) .stdout(Stdio::piped()) .spawn() .context("tar local")?; let tar_stdout = tar.stdout.take().context("no tar stdout")?; let remote = format!("tar -C {remote_q} -xf -"); let status = Command::new("ssh") .args(ssh_args(&target, &remote)) .stdin(Stdio::from(tar_stdout)) .status() .context("ssh tar extract")?; let tar_status = tar.wait().context("waiting for tar")?; if !tar_status.success() { bail!("local tar failed"); } if !status.success() { bail!("remote extract to {target}:{remote_path} failed"); } Ok(()) } /// Stage configs + image tarballs, load images, swap into `live_path` only if compose succeeds. pub fn atomic_deploy( user: &str, host: &str, live_path: &str, local_cfg: &Path, image_tars: &[(PathBuf, &str)], image_refs: &[&str], ) -> Result<()> { let id = std::process::id(); let stage = format!("{live_path}.next-{id}"); let prev = format!("{live_path}.prev"); let stage_q = shell_quote(&stage); let live_q = shell_quote(live_path); let prev_q = shell_quote(&prev); let wipe_stage = || { let _ = ssh(user, host, &format!("rm -rf {stage_q}")); }; let result = (|| { progress::phase(&format!( "prepare stage {host}:{stage} (live path untouched until activate)" )); ssh( user, host, &format!("rm -rf {stage_q} {prev_q} && mkdir -p {stage_q}/images"), )?; progress::phase(&format!("upload configs → {host}:{stage}")); put_dir(user, host, local_cfg, &stage)?; eprintln!(" configs ok"); let n = image_tars.len(); let mut overall_total = 0u64; for (local, _) in image_tars { overall_total += fs::metadata(local).map(|m| m.len()).unwrap_or(0); } progress::phase(&format!( "upload {} image tar(s) ({} total) → {host}", n, progress::human_bytes(overall_total) )); let mut overall_base = 0u64; for (i, (local, name)) in image_tars.iter().enumerate() { if !local.is_file() { bail!( "missing image tar {} — run `sope build` first", local.display() ); } let size = fs::metadata(local)?.len(); let mut bar = UploadBar::new(name, i + 1, n, overall_base, overall_total); put_file(user, host, local, &format!("{stage}/images/{name}"), |sent, total| { bar.update(sent, total); })?; bar.finish(size); overall_base += size; } eprintln!( " all images uploaded ({})", progress::human_bytes(overall_base) ); let mut rm_images = String::new(); for img in image_refs { rm_images.push_str(&format!( " docker image rm -f {} >/dev/null 2>&1 || true\n", shell_quote(img) )); } let script = format!( r#"set -eu STAGE={stage_q} LIVE={live_q} PREV={prev_q} HAD_LIVE=0 [ -d "$LIVE" ] && HAD_LIVE=1 fail_before_swap() {{ rm -rf -- "$STAGE" if [ "$HAD_LIVE" = 0 ]; then {rm_images} fi exit 1 }} trap fail_before_swap ERR echo "→ docker load (from stage)" for f in "$STAGE"/images/*.tar.gz; do echo " loading $(basename "$f") …" docker load -i "$f" done rm -rf -- "$STAGE/images" trap - ERR echo "→ atomic switch stage → live" rm -rf -- "$PREV" if [ "$HAD_LIVE" = 1 ]; then mv -- "$LIVE" "$PREV" fi mv -- "$STAGE" "$LIVE" echo "→ docker compose up -d" if ! (cd "$LIVE" && docker compose up -d); then echo "→ compose failed — rolling back" (cd "$LIVE" && docker compose down --remove-orphans) >/dev/null 2>&1 || true rm -rf -- "$LIVE" if [ "$HAD_LIVE" = 1 ]; then mv -- "$PREV" "$LIVE" (cd "$LIVE" && docker compose up -d) || true else {rm_images} fi exit 1 fi rm -rf -- "$PREV" echo "→ active at $LIVE" "# ); progress::phase(&format!( "activate on {host}: docker load → swap → compose up ({live_path})" )); ssh_live(user, host, &script).context("remote activate")?; Ok(()) })(); if result.is_err() { wipe_stage(); } result }