chyabrung-cli 0.1.0

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! `chy deploy`: one-command VPS deploys over SSH.
//!
//! Configure in `chyabrung.toml`:
//!
//! ```toml
//! [deploy]
//! host = "203.0.113.10"     # required
//! user = "root"             # default root
//! domain = "example.com"    # enables Nginx + Let's Encrypt
//! email = "you@example.com" # for Let's Encrypt
//! port = 8000               # app port behind Nginx
//! path = "/opt/myapp"       # install dir
//! build = "local"           # "local" (cargo build here) or "remote" (build on the server)
//! target = "x86_64-unknown-linux-gnu"   # optional cross-compile target for local builds
//! env_file = ".env.production"
//! ```

use crate::util::{ok, step, CliResult};
use std::io::Write;
use std::process::{Command, Stdio};

/// Deploy settings.
#[derive(Debug, Clone, PartialEq)]
pub struct DeployConfig {
    /// SSH host.
    pub host: String,
    /// SSH user.
    pub user: String,
    /// Public domain (optional).
    pub domain: Option<String>,
    /// Email for certbot.
    pub email: Option<String>,
    /// App port.
    pub port: u16,
    /// Remote install path.
    pub path: String,
    /// App/binary/service name.
    pub app: String,
    /// `local` or `remote`.
    pub build: String,
    /// Cross target for local builds.
    pub target: Option<String>,
    /// Env file to upload.
    pub env_file: String,
}

impl DeployConfig {
    /// Read from a `chyabrung.toml` table.
    pub fn from_table(t: &toml::Table, app: &str) -> CliResult<Self> {
        let d = t.get("deploy").and_then(|d| d.as_table()).ok_or("add a [deploy] section to chyabrung.toml (see `chy deploy --help`)")?;
        let s = |k: &str| d.get(k).and_then(|v| v.as_str()).map(str::to_owned);
        Ok(Self {
            host: s("host").ok_or("[deploy] host is required")?,
            user: s("user").unwrap_or_else(|| "root".into()),
            domain: s("domain"),
            email: s("email"),
            port: d.get("port").and_then(|v| v.as_integer()).and_then(|p| u16::try_from(p).ok()).unwrap_or(8000),
            path: s("path").unwrap_or_else(|| format!("/opt/{app}")),
            app: app.to_string(),
            build: s("build").unwrap_or_else(|| "local".into()),
            target: s("target"),
            env_file: s("env_file").unwrap_or_else(|| ".env.production".into()),
        })
    }

    fn remote(&self) -> String {
        format!("{}@{}", self.user, self.host)
    }
}

/// The systemd unit.
pub fn systemd_unit(c: &DeployConfig) -> String {
    format!(
        "[Unit]\nDescription={app} (Chyabrung)\nAfter=network.target\n\n[Service]\nType=simple\nWorkingDirectory={path}\nExecStart={path}/{app}\nEnvironmentFile=-{path}/.env\nEnvironment=APP_ENV=production\nEnvironment=APP_HOST=127.0.0.1\nEnvironment=APP_PORT={port}\nRestart=always\nRestartSec=2\nKillSignal=SIGTERM\nTimeoutStopSec=35\nNoNewPrivileges=true\nPrivateTmp=true\nLimitNOFILE=65535\n\n[Install]\nWantedBy=multi-user.target\n",
        app = c.app,
        path = c.path,
        port = c.port
    )
}

/// The Nginx site.
pub fn nginx_site(c: &DeployConfig) -> String {
    let server_name = c.domain.clone().unwrap_or_else(|| "_".into());
    format!(
        "upstream {app}_upstream {{\n    server 127.0.0.1:{port};\n    keepalive 64;\n}}\n\nserver {{\n    listen 80;\n    listen [::]:80;\n    server_name {server_name};\n    client_max_body_size 20m;\n\n    location /assets/ {{\n        alias {path}/public/;\n        expires 30d;\n        access_log off;\n    }}\n\n    location /pkg/ {{\n        alias {path}/dist/pkg/;\n        expires 30d;\n    }}\n\n    location / {{\n        proxy_pass http://{app}_upstream;\n        proxy_http_version 1.1;\n        proxy_set_header Host $host;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_set_header X-Forwarded-Host $host;\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection $connection_upgrade;\n        proxy_buffering off;\n        proxy_read_timeout 3600s;\n    }}\n}}\n\nmap $http_upgrade $connection_upgrade {{\n    default upgrade;\n    ''      close;\n}}\n",
        app = c.app,
        port = c.port,
        path = c.path,
    )
}

/// Remote commands run after upload.
pub fn remote_script(c: &DeployConfig) -> String {
    let mut s = format!(
        "set -e\nmkdir -p {path}\ncd {path}\n",
        path = c.path
    );
    if c.build == "remote" {
        s.push_str(&format!(
            "tar xzf /tmp/{app}-src.tgz -C {path}\ncommand -v cargo >/dev/null || (curl -sSf https://sh.rustup.rs | sh -s -- -y)\n. \"$HOME/.cargo/env\"\ncargo build --release\ncp target/release/{app} {path}/{app}\n",
            app = c.app,
            path = c.path
        ));
    }
    s.push_str(&format!(
        "chmod +x {path}/{app}\nmv /tmp/{app}.service /etc/systemd/system/{app}.service\nsystemctl daemon-reload\nsystemctl enable {app} >/dev/null 2>&1\nsystemctl restart {app}\n",
        path = c.path,
        app = c.app
    ));
    if c.domain.is_some() {
        s.push_str(&format!(
            "command -v nginx >/dev/null || (apt-get update -y && apt-get install -y nginx)\nmv /tmp/{app}.nginx /etc/nginx/sites-available/{app}\nln -sf /etc/nginx/sites-available/{app} /etc/nginx/sites-enabled/{app}\nnginx -t\nsystemctl reload nginx\n",
            app = c.app
        ));
        if let (Some(domain), Some(email)) = (&c.domain, &c.email) {
            s.push_str(&format!(
                "if [ ! -d /etc/letsencrypt/live/{domain} ]; then\n  command -v certbot >/dev/null || apt-get install -y certbot python3-certbot-nginx\n  certbot --nginx -d {domain} --non-interactive --agree-tos -m {email} --redirect\nfi\n"
            ));
        }
    }
    s.push_str(&format!("systemctl --no-pager status {} | head -n 5\n", c.app));
    s
}

fn ssh(c: &DeployConfig) -> Command {
    let mut cmd = Command::new("ssh");
    cmd.args(["-o", "BatchMode=yes", &c.remote()]);
    cmd
}

fn scp(c: &DeployConfig, local: &str, remote_path: &str) -> CliResult {
    crate::util::run(Command::new("scp").args(["-r", "-q", local, &format!("{}:{remote_path}", c.remote())]))
}

fn upload_text(c: &DeployConfig, content: &str, remote_path: &str) -> CliResult {
    let mut child = ssh(c)
        .arg(format!("cat > {remote_path}"))
        .stdin(Stdio::piped())
        .spawn()
        .map_err(|e| format!("ssh failed: {e}"))?;
    if let Some(stdin) = child.stdin.as_mut() {
        stdin.write_all(content.as_bytes()).map_err(|e| e.to_string())?;
    }
    let st = child.wait().map_err(|e| e.to_string())?;
    if st.success() {
        Ok(())
    } else {
        Err(format!("uploading {remote_path} failed"))
    }
}

/// `chy deploy [--dry-run]`
pub fn run(dry_run: bool) -> CliResult {
    let app = crate::util::package_name()?;
    let c = DeployConfig::from_table(&crate::util::config(), &app)?;
    let script = remote_script(&c);
    if dry_run {
        println!("# deploy plan for {app} → {}\n", c.remote());
        println!("## /etc/systemd/system/{app}.service\n{}", systemd_unit(&c));
        if c.domain.is_some() {
            println!("## /etc/nginx/sites-available/{app}\n{}", nginx_site(&c));
        }
        println!("## remote script\n{script}");
        return Ok(());
    }
    for tool in ["ssh", "scp"] {
        if !crate::util::which(tool) {
            return Err(format!("`{tool}` not found on PATH (install OpenSSH)"));
        }
    }
    step(&format!("deploying {app} to {}", c.remote()));
    crate::util::run(ssh(&c).arg(format!("mkdir -p {}", c.path)))?;

    if c.build == "remote" {
        step("packaging sources");
        crate::util::run(Command::new("tar").args([
            "czf",
            &format!("{}/{app}-src.tgz", std::env::temp_dir().display()),
            "--exclude=target",
            "--exclude=.git",
            ".",
        ]))?;
        scp(&c, &format!("{}/{app}-src.tgz", std::env::temp_dir().display()), &format!("/tmp/{app}-src.tgz"))?;
    } else {
        step("building release binary");
        let mut cmd = Command::new("cargo");
        cmd.args(["build", "--release"]);
        if let Some(t) = &c.target {
            cmd.args(["--target", t]);
        }
        crate::util::run(&mut cmd)?;
        let bin = match &c.target {
            Some(t) => format!("target/{t}/release/{app}"),
            None => format!("target/release/{app}"),
        };
        if cfg!(windows) && c.target.is_none() {
            return Err("local builds on Windows produce a Windows binary; set [deploy] build = \"remote\" or target = \"x86_64-unknown-linux-gnu\" (with a cross linker)".into());
        }
        step("uploading binary and assets");
        scp(&c, &bin, &format!("{}/{app}", c.path))?;
    }
    for dir in ["public", "dist", "migrations", "chyabrung.toml"] {
        if std::path::Path::new(dir).exists() {
            scp(&c, dir, &c.path)?;
        }
    }
    if std::path::Path::new(&c.env_file).exists() {
        scp(&c, &c.env_file, &format!("{}/.env", c.path))?;
    } else {
        eprintln!("  note: {} not found; the server keeps its existing .env", c.env_file);
    }
    upload_text(&c, &systemd_unit(&c), &format!("/tmp/{app}.service"))?;
    if c.domain.is_some() {
        upload_text(&c, &nginx_site(&c), &format!("/tmp/{app}.nginx"))?;
    }
    step("configuring systemd, Nginx and TLS");
    let mut child = ssh(&c).arg("bash -s").stdin(Stdio::piped()).spawn().map_err(|e| e.to_string())?;
    if let Some(stdin) = child.stdin.as_mut() {
        stdin.write_all(script.as_bytes()).map_err(|e| e.to_string())?;
    }
    if !child.wait().map_err(|e| e.to_string())?.success() {
        return Err("remote setup failed (see output above)".into());
    }
    match &c.domain {
        Some(d) => ok(&format!("deployed → https://{d}")),
        None => ok(&format!("deployed → http://{}:{}", c.host, c.port)),
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg() -> DeployConfig {
        let t: toml::Table = r#"
            [deploy]
            host = "1.2.3.4"
            domain = "example.com"
            email = "a@example.com"
            port = 9000
        "#
        .parse()
        .unwrap();
        DeployConfig::from_table(&t, "blog").unwrap()
    }

    #[test]
    fn config_defaults() {
        let c = cfg();
        assert_eq!((c.user.as_str(), c.path.as_str(), c.port), ("root", "/opt/blog", 9000));
        assert!(DeployConfig::from_table(&toml::Table::new(), "x").is_err());
    }

    #[test]
    fn generated_files() {
        let c = cfg();
        let unit = systemd_unit(&c);
        assert!(unit.contains("ExecStart=/opt/blog/blog"));
        assert!(unit.contains("APP_PORT=9000"));
        let nginx = nginx_site(&c);
        assert!(nginx.contains("server_name example.com;"));
        assert!(nginx.contains("server 127.0.0.1:9000;"));
        assert!(nginx.contains("Upgrade $http_upgrade"));
        let script = remote_script(&c);
        assert!(script.contains("certbot --nginx -d example.com"));
        assert!(script.contains("systemctl restart blog"));
    }
}