This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

superconfig / tools / deploy / flake-module.nix
11 kB 245 lines
1{ self, inputs, ... }: 2{ 3 perSystem = 4 { 5 pkgs, 6 system, 7 ... 8 }: 9 { 10 # deploy [--flake PATH] <machine> [[user@]host] (host defaults to <machine>.r) 11 # 12 # Generates vars, copies the flake source to /var/lib/deploy/incoming 13 # on the target, builds it there in the systemd unit deploy-build 14 # (progress via nom), shows the source diff against the running system 15 # (/var/lib/deploy/src) and the closure diff, asks, then uploads 16 # secrets and switches in the unit deploy-switch. Both units survive 17 # the ssh connection dying; rerunning deploy attaches to a running one. 18 packages.deploy = 19 (pkgs.writeShellApplication { 20 name = "deploy"; 21 runtimeInputs = [ 22 self.packages.${system}.pass 23 inputs.clan-core.packages.${system}.clan-cli 24 pkgs.gnutar 25 pkgs.jq 26 pkgs.less 27 pkgs.nix-output-monitor 28 ]; 29 text = '' 30 usage() { 31 echo "usage: deploy [--flake PATH] <machine> [[user@]host] (host defaults to <machine>.r)" >&2 32 exit 1 33 } 34 35 flake=. 36 while [ $# -gt 0 ]; do 37 case $1 in 38 --flake) 39 [ $# -ge 2 ] || usage 40 flake=$2 41 shift 2 42 ;; 43 -*) usage ;; 44 *) break ;; 45 esac 46 done 47 [ $# -eq 1 ] || [ $# -eq 2 ] || usage 48 machine=$1 49 target=''${2:-$machine.r} 50 [[ $target == *@* ]] || target=root@$target 51 52 state=/var/lib/deploy 53 nix="/run/current-system/sw/bin/nix --extra-experimental-features 'nix-command flakes'" 54 55 tmp=$(mktemp -d) 56 chmod 700 "$tmp" 57 # One ssh connection for the whole run, so the key signs only once. 58 ssh_opts=(-o ControlMaster=auto -o "ControlPath=$tmp/ssh" -o ControlPersist=yes) 59 cleanup() { 60 ssh "''${ssh_opts[@]}" -O exit "$target" 2>/dev/null || true 61 rm -rf "$tmp" 62 } 63 trap cleanup EXIT 64 65 remote() { 66 # shellcheck disable=SC2029 # the command line is meant for the target 67 ssh "''${ssh_opts[@]}" "$target" "$@" 68 } 69 step() { 70 printf '\n\033[1m== %s\033[0m\n' "$*" >&2 71 } 72 page() { 73 if [ -t 1 ]; then ''${PAGER:-less -RFX}; else cat; fi 74 } 75 76 # True while the unit's ExecStartPre or ExecStart is running. 77 # Finished units stay around (RemainAfterExit) until the next start, 78 # so their result can still be read after reconnecting. 79 in_progress() { 80 case $(remote systemctl show -p ActiveState -p SubState "$1") in 81 *ActiveState=activating* | *SubState=running*) return 0 ;; 82 esac 83 return 1 84 } 85 86 # start <unit> <systemd-run args...>: the arguments are quoted, so 87 # they reach systemd-run on the target unchanged. Units start with 88 # an empty environment; go through the daemon like a login shell 89 # (the store is read-only inside containers). 90 start() { 91 local unit=$1 92 shift 93 remote "systemctl stop $unit 2>/dev/null; systemctl reset-failed $unit 2>/dev/null;" \ 94 "systemd-run --quiet --unit=$unit -p RemainAfterExit=yes" \ 95 "-p StandardOutput=truncate:$state/$unit.log" \ 96 "--setenv=NIX_REMOTE=daemon --setenv=PATH=/run/wrappers/bin:/run/current-system/sw/bin" \ 97 "$(printf ' %q' "$@")" 98 } 99 100 # follow <unit>: stream its log until it finishes, fail if it did. 101 # tail can lag far behind the log when the reader (nom) is slow, so 102 # it must not be killed on a timer: --pid makes it read the log to 103 # the end once the waiter (unit finished) is gone, then exit, so 104 # no line is cut off. 105 follow() { 106 ssh "''${ssh_opts[@]}" "$target" bash -s -- "$1" "$state" <<'EOF' 107 unit=$1 log=$2/$1.log 108 while case $(systemctl show -p ActiveState -p SubState "$unit") in 109 *ActiveState=activating* | *SubState=running*) true ;; 110 *) false ;; 111 esac; do 112 sleep 1 113 done & 114 tail -n +1 -F --pid=$! "$log" 2>/dev/null 115 [ "$(systemctl show -p Result --value "$unit")" = success ] && exit 0 116 echo "deploy: $unit failed (exit status $(systemctl show -p ExecMainStatus --value "$unit")), log: $log" >&2 117 exit 1 118 EOF 119 } 120 121 # source_diff: per-file +/- summary, then the full diff, of the 122 # running system's source against the incoming one. 123 source_diff() { 124 ssh "''${ssh_opts[@]}" "$target" bash -s -- "$state" <<'EOF' 125 old=$1/src new=$1/incoming 126 if [ ! -d "$old" ]; then 127 echo "no source recorded for the running system" 128 exit 0 129 fi 130 # diff exits 1 when the trees differ, 2 on trouble. 131 d() { diff -ruN "$@" "$old" "$new" || [ $? -eq 1 ]; } 132 d | awk -v pre="$new/" ' 133 /^diff -ruN / { 134 f = substr($0, index($0, " " pre) + 1 + length(pre)) 135 files[++n] = f; hdr = 2; next 136 } 137 hdr > 0 { hdr--; next } 138 /^\+/ { add[f]++ } 139 /^-/ { del[f]++ } 140 END { 141 if (n == 0) { print "no source changes"; exit } 142 for (i = 1; i <= n; i++) { 143 f = files[i] 144 printf " %-60s \033[32m+%d\033[0m \033[31m-%d\033[0m\n", f, add[f], del[f] 145 } 146 printf "%d files changed\n\n", n 147 }' 148 d --color=always 149 EOF 150 } 151 152 step "connecting to $target" 153 remote true || { echo "deploy: cannot reach $target" >&2; exit 1; } 154 # shellcheck disable=SC2016 # expanded on the target 155 remote 'test -e /etc/NIXOS && command -v systemd-run >/dev/null' || 156 { echo "deploy: $target is not a NixOS system with systemd" >&2; exit 1; } 157 if in_progress deploy-switch; then 158 step "a switch is still running on $target, attaching" 159 follow deploy-switch 160 exit 161 fi 162 163 # Decrypt the bulk key once (one Secure Enclave unlock); every 164 # later pass call from clan then uses it without prompting. 165 PASS_BULK_KEY_FILE="" pass show bulk-operations/age-key >"$tmp/bulk-key" 166 if [ ! -s "$tmp/bulk-key" ]; then 167 echo "deploy: could not extract the bulk key" >&2 168 exit 1 169 fi 170 export PASS_BULK_KEY_FILE="$tmp/bulk-key" 171 172 if in_progress deploy-build; then 173 step "a build is still running on $target, attaching" 174 else 175 step "generating vars for $machine" 176 pass git pull --rebase 177 clan vars generate --flake "$flake" "$machine" 178 pass git push 179 180 step "copying source to $target:$state/incoming" 181 # The flake source exactly as nix sees it: tracked files only. 182 src=$(nix flake metadata --json "$flake" | jq -r .path) 183 tar -C "$src" --owner=0 --group=0 --numeric-owner -czf - . | 184 remote "rm -rf $state/incoming.new && mkdir -p $state/incoming.new &&" \ 185 "tar -C $state/incoming.new -xzf - &&" \ 186 "rm -rf $state/incoming && mv $state/incoming.new $state/incoming" 187 188 step "source changes" 189 source_diff | page 190 191 step "building $machine on $target" 192 # nvd comes from the machine's own nixpkgs, so it is built for 193 # the target and usually substituted; out-links are result 194 # (system) and result-1 (nvd), in installable order. 195 start deploy-build \ 196 /run/current-system/sw/bin/nix --extra-experimental-features "nix-command flakes" \ 197 --log-format internal-json -v build --out-link "$state/result" \ 198 "$state/incoming#nixosConfigurations.$machine.config.system.build.toplevel" \ 199 "$state/incoming#nixosConfigurations.$machine.pkgs.nvd" 200 fi 201 follow deploy-build | nom --json 202 system=$(remote readlink -f "$state/result") 203 204 step "closure changes" 205 if [ "$(remote readlink -f /run/current-system)" = "$system" ]; then 206 echo "$system is already running" 207 else 208 remote "$state/result-1/bin/nvd diff /run/current-system $system" 209 fi 210 211 read -r -p "switch $target to $system? [y/N] " answer </dev/tty 212 if [[ $answer != [yY]* ]]; then 213 echo "aborted, $target is unchanged" >&2 214 exit 1 215 fi 216 217 step "uploading secrets" 218 secret_location=$(remote "$nix eval --raw $state/incoming#nixosConfigurations.$machine.config.clan.core.vars.password-store.secretLocation") 219 clan vars upload --flake "$flake" --directory "$tmp/vars" "$machine" 220 if [ -s "$tmp/vars/.pass_info" ] && 221 [ "$(remote cat "$secret_location/.pass_info" 2>/dev/null)" = "$(cat "$tmp/vars/.pass_info")" ]; then 222 echo "secrets in $secret_location unchanged" 223 else 224 # Same layout and permissions as `clan vars upload`; swapped in 225 # with a rename so the directory is never empty. 226 find "$tmp/vars" -type d -exec chmod 700 {} + 227 find "$tmp/vars" -type f -exec chmod 400 {} + 228 # shellcheck disable=SC2016 # expanded on the target 229 tar -C "$tmp/vars" --owner=0 --group=0 --numeric-owner -czf - . | 230 remote "d=$secret_location;" \ 231 'rm -rf "$d.new" "$d.old" && install -d -m 700 "$d.new" && tar -C "$d.new" -xzf - &&' \ 232 '{ [ ! -e "$d" ] || mv "$d" "$d.old"; } && mv "$d.new" "$d" && rm -rf "$d.old"' 233 fi 234 235 step "switching $target" 236 start deploy-switch \ 237 -p "ExecStartPre=/run/current-system/sw/bin/nix-env -p /nix/var/nix/profiles/system --set $system" \ 238 -p "ExecStartPre=/bin/sh -c 'rm -rf $state/src && cp -a $state/incoming $state/src'" \ 239 "$system/bin/switch-to-configuration" switch 240 follow deploy-switch 241 ''; 242 }).overrideAttrs 243 { passthru.usage = builtins.readFile ./usage.kdl; }; 244 }; 245}