dance-ops 0.1.0

Deploy NixOS hosts safely from a local inventory
//! Local Nix and remote NixOS command execution.

use std::{num::NonZeroU32, time::Duration};

use indicatif::ProgressBar;

use crate::{
    error::Error,
    inventory::Host,
    process::{Invocation, ProcessContext},
    ssh,
    store_path::StorePath,
};

/// Limits routine SSH operations.
pub(super) const SSH_TIMEOUT: Duration = Duration::from_mins(1);
/// Bounds rebuild actions performed while the rollback watchdog is armed.
const REBUILD_TIMEOUT: Duration = Duration::from_mins(2);

/// Creates an SSH invocation targeting one inventory host.
pub(super) fn ssh<'a>(
    host: &Host,
    label: impl Into<String>,
    processes: &'a ProcessContext<'a>,
    progress: &'a ProgressBar,
) -> Invocation<'a> {
    Invocation::new(processes, label, "ssh", progress)
        .arguments(ssh::ARGUMENTS)
        .argument(host.ssh_url())
}

/// Reads the system currently activated on a target.
pub(super) async fn deployed_store_path(
    host: &Host,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<StorePath, Error> {
    let output = ssh(
        host,
        format!("review-{}-remote", host.id()),
        processes,
        progress,
    )
    .argument("readlink -f /run/current-system")
    .timeout(SSH_TIMEOUT)
    .output()
    .await?;
    let value = output.trim();
    value.parse().map_err(Error::StorePath)
}

/// Evaluates a host's desired system without building it.
pub(super) async fn expected_store_path(
    host: &Host,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<StorePath, Error> {
    let output = Invocation::new(
        processes,
        format!("review-{}-local", host.id()),
        "nix",
        progress,
    )
    .arguments(["eval", "--raw"])
    .argument(host.nixos_output())
    .output()
    .await?;
    let value = output.trim();
    value.parse().map_err(Error::StorePath)
}

/// Builds and transfers a host configuration without activating it.
pub(super) async fn dry_activate(
    host: &Host,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<(), Error> {
    rebuild(host, "dry-activate", processes, progress)
        .status()
        .await
}

/// Builds and temporarily activates a host configuration.
pub(super) async fn test(
    host: &Host,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<(), Error> {
    rebuild(host, "test", processes, progress)
        .timeout(REBUILD_TIMEOUT)
        .status()
        .await
}

/// Builds and persistently activates a host configuration.
pub(super) async fn switch(
    host: &Host,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<(), Error> {
    rebuild(host, "switch", processes, progress)
        .timeout(REBUILD_TIMEOUT)
        .status()
        .await
}

/// Creates a complete `nixos-rebuild` deployment action.
fn rebuild<'a>(
    host: &Host,
    action: &str,
    processes: &'a ProcessContext<'a>,
    progress: &'a ProgressBar,
) -> Invocation<'a> {
    Invocation::new(
        processes,
        format!("deploy-{}-{action}", host.id()),
        "nixos-rebuild",
        progress,
    )
    .argument(action)
    .arguments(["--use-substitutes", "--flake"])
    .argument(host.flake())
    .argument("--target-host")
    .argument(host.ssh_url())
    .environment("NIX_SSHOPTS", ssh::nix_options())
}

/// Prunes old generations and collects unreachable target store paths.
pub(super) async fn collect_garbage(
    host: &Host,
    keep_generations: NonZeroU32,
    processes: &ProcessContext<'_>,
    progress: &ProgressBar,
) -> Result<(), Error> {
    ssh(
        host,
        format!("deploy-{}-prune-generations", host.id()),
        processes,
        progress,
    )
    .arguments([
        "nix-env",
        "--profile",
        "/nix/var/nix/profiles/system",
        "--delete-generations",
    ])
    .argument(format!("+{keep_generations}"))
    .status()
    .await?;

    ssh(
        host,
        format!("deploy-{}-refresh-bootloader", host.id()),
        processes,
        progress,
    )
    .arguments(["/run/current-system/bin/switch-to-configuration", "boot"])
    .status()
    .await?;

    ssh(
        host,
        format!("deploy-{}-collect-garbage", host.id()),
        processes,
        progress,
    )
    .arguments(["nix-store", "--gc"])
    .status()
    .await
}