Something went wrong. Try again.
Something went wrong. Try again.
ark deploy.nu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287#!/usr/bin/env nu
use std "path add"use std/log
path add /nix/var/nix/profiles/default/bin
cd $env.NH_FLAKE
def webhook [title: string, content: string, exit_code?: number, ping?: bool = false] { let type = if $exit_code == null { "⌛" } else if $exit_code == 0 { "✔️" } else { "❌" } let msg = { content: (if $ping { "hey <@853064602904166430>!" } else { "" }), embeds: [{ description: $content, title: $"($type) /($title)/", footer: { text: $"(date now) \((sys host | get hostname)\)", } }] }
if $exit_code == 0 or $exit_code == null { log info $content } else { log error $content } # http post --content-type application/json $"https://discord.com/api/webhooks/($env.WEBHOOK_ID)/($env.WEBHOOK_TOKEN)" $msg}
def upload-paste []: any -> string { # let paste_url = http post -H ["user-agent" "gaze.systems terra deploy"] --content-type multipart/form-data "https://0x0.st" {file: ($in | to text | into binary), secret: true} # return $paste_url return ""}
def time-block [block]: nothing -> record { let start = date now let result = do $block let end = date now return {result: $result, elapsed: ($end - $start)}}
let hosts = { valefar: { type: "nixos", user: "regent", addr: "valefar", }, dzwonek: { type: "nixos", user: "root", addr: "94.237.26.47", }, volsinii: { type: "nixos", user: "root", addr: "199.71.188.53", }, trimounts: { type: "nixos", user: "root", addr: "159.195.58.28", port: 2200, }, focalor: { type: "nixos", user: "regent", addr: "100.64.0.13", }, pupos: { type: "nixos", user: "dawn", addr: "pupos", },}
def deploy [hostname: string, boot: bool, target_build: bool]: nothing -> bool { log info $"start deploy host ($hostname)" let hooktitle = $"/($hostname)/deploy" let hostcfg = $hosts | get $hostname let port = ($hostcfg | get -o port | default 22) let ssh_opts = ["-p" ($port | into string)] let target = $"($hostcfg.user)@($hostcfg.addr)" let remote_source = $"/tmp/ark-deploy-($hostname)"
webhook $hooktitle $"=== deploy for ($hostname): started ===\n\n(sys disks | to text)\n\n(sys mem | to text)"
# one line per finished step: the terminal already showed whatever it printed def report [action: string, r: record] { if $r.failed { let tail = if ($r.output | is-empty) { "(no output)" } else { $r.output | str substring (-4000..) } webhook $"($hooktitle)/($action)" $"=== ($action) ($hostname) FAILED with exit code ($r.exit_code) after ($r.elapsed) ===\n\n($tail)" $r.exit_code true } else { webhook $"($hooktitle)/($action)" $"=== ($action) ($hostname) is done ===\n\ntook ($r.elapsed)" 0 } }
# quick steps: hold both streams so they can be quoted back when something breaks def run_step [action: string, block]: nothing -> record { webhook $"($hooktitle)/($action)" $"=== ($action) ($hostname) started ===" let start = date now let r = (do $block) | complete let res = { failed: ($r.exit_code != 0) exit_code: $r.exit_code output: ($r.stdout + "\n" + $r.stderr) elapsed: ((date now) - $start) } report $action $res $res }
# slow steps: shown as they happen and logged for the failure report. `complete` and `tee` # both hold everything until the command exits, and a failing external stops the script # before any webhook fires, so bash owns the pipe and nushell only reads the status back. def run_long [action: string, cmd: string, --quiet]: nothing -> record { if not $quiet { webhook $"($hooktitle)/($action)" $"=== ($action) ($hostname) started ===" } let start = date now let logfile = (^mktemp) # the whole command goes in a subshell: a bare "a; b" would bind the pipe to "b" only, # and then everything before it lands on the terminal unlogged let piped = "( " + $cmd + " ) 2>&1 | tee -a " + $logfile let exit_code = (try { ^bash -o pipefail -c $piped 0 } catch { $env.LAST_EXIT_CODE }) let res = { failed: ($exit_code != 0) exit_code: $exit_code output: (if ($logfile | path exists) { open --raw $logfile | str trim } else { "" }) elapsed: ((date now) - $start) } ^rm -f $logfile if not $quiet { report $action $res } $res }
# switch-to-configuration exits 11 with "Could not acquire lock" while another activation # (a stale deploy, an autoupgrade, another admin) owns the lock def lock_busy [r: record]: nothing -> bool { $r.failed and (($r.exit_code == 11) or ($r.output | str contains "Could not acquire lock")) }
def remote_system []: nothing -> string { let out = (do -i { ^ssh ...($ssh_opts | append [$target]) "readlink /run/current-system" }) if ($out | is-empty) { "" } else { $out | into string | str trim } }
let result_dir = (^mktemp -d | path join "result") let sync_cmd = { rsync -a --delete -e $"ssh ($ssh_opts | str join ' ')" --exclude .git --exclude .direnv --exclude "result*" $"($env.NH_FLAKE)/" $"($target):($remote_source)/" } let build_cmd = if $target_build { $"ssh ($ssh_opts | str join ' ') ($target) \"cd ($remote_source) && nix build --accept-flake-config --no-link --print-out-paths '.#nixosConfigurations.($hostname).config.system.build.toplevel'\"" } else { match $hostcfg.type { "nixos" => $"nh os build --no-nom -H ($hostname) -o ($result_dir) -- -L --show-trace" "home" => $"nh home build --no-nom -c ($hostname) -o ($result_dir) -- -L --show-trace" } } if $target_build { if (run_step "sync" $sync_cmd).failed { return false } } let built = (run_long (if $target_build { "build on target" } else { "build" }) $build_cmd) if $built.failed { return false } let result_link = if $target_build { # the out path is printed, but so are other /nix/store lines: keep the toplevel $built.output | lines | where {|l| ($l starts-with "/nix/store/") and ($l | str contains $"-nixos-system-($hostname)-") } | last } else { ^readlink $result_dir } if ($result_link | is-empty) { log error "could not find the built toplevel in the build output" return false }
if $target_build == false { let copy_cmd = $"NIX_SSHOPTS='($ssh_opts | str join ' ')' nix copy --no-check-sigs -s --to ssh://($target) ($result_link)" if (run_long "copy to" $copy_cmd).failed { return false } }
let action = if $boot { "boot" } else { "switch" } let remote_activate = match $hostcfg.type { "nixos" => $"sudo nix-env -p /nix/var/nix/profiles/system --set '($result_link)' && sudo '($result_link)/bin/switch-to-configuration' ($action) --fail-on-warning" "home" => $"($result_link)/activate" } let activate_cmd = $"ssh ($ssh_opts | str join ' ') ($target) \"($remote_activate)\"" webhook $"($hooktitle)/activate" $"=== activate ($hostname) started ===" mut activated = (run_long "activate" $activate_cmd --quiet) mut waits = 0 while (lock_busy $activated) and $waits < 40 { if (remote_system) == $result_link { log info "another activation already switched to this generation, nothing left to do" $activated = ($activated | merge { failed: false, exit_code: 0, output: "" }) break } $waits = $waits + 1 log warning $"another switch holds /run/nixos/switch-to-configuration.lock, waiting 15s, retry ($waits)" sleep 15sec $activated = (run_long "activate" $activate_cmd --quiet) } report "activate" $activated if $activated.failed { return false }
if $boot { log info "rebooting target..." if (run_step "reboot" { ssh ...($ssh_opts | append [$target]) "sudo reboot" }).failed { return false } }
if $target_build { if (run_step "cleanup" { ssh ...($ssh_opts | append [$target]) $"rm -rf '($remote_source)'" }).failed { return false } }
webhook $hooktitle $"=== deploy for ($hostname): finished ===" 0 true return true}
def known-hosts []: nothing -> list<string> { $hosts | columns}
# "a,b" / "a b" / "@all" -> host list, validated before anything is toucheddef parse-targets [targets: list<string>]: nothing -> list<string> { let known = (known-hosts) let wanted = ( $targets | each {|t| $t | split row "," } | flatten | each {|t| $t | str trim } | where {|t| $t != "" } ) if ($wanted | is-empty) { error make --unspanned { msg: $"nothing to deploy\nusage: deploy <host[,host...]|@all> [--boot] [--target-build]\nhosts: ($known | str join ', ')" } } if ($wanted | any {|t| $t == "@all" }) { return $known } let unknown = ($wanted | where {|t| not ($known | any {|k| $k == $t })}) if not ($unknown | is-empty) { error make --unspanned { msg: $"unknown hosts: ($unknown | str join ', '), known: ($known | str join ', ')" } } $wanted}
def main [ ...targets: string # host[,host...] or @all --boot (-b) # boot into the new generation instead of switching --target-build # build on the host instead of here] { let names = (parse-targets $targets) webhook "/deploy" $"=== deploying ($names | str join ', ') ==="
let results = ( $names | each {|host| { host: $host, ok: (deploy $host $boot $target_build) } } ) let failed = ($results | where {|r| not $r.ok }) let ok = ($failed | is-empty) let summary = if $ok { $"=== ($names | str join ', ') deployed ===" } else { let down = ($failed | get host | str join ', ') $"=== FAILED: ($down) ===\nsucceeded: (($results | where {|r| $r.ok } | get host) | str join ', ')" } webhook "/deploy" $summary (if $ok { 0 } else { 1 })
if not $ok { print $"deploy failed: ($failed | get host | str join ', ')" exit 1 }}