This repository has no description
11 kB
250 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. systemctl fails for a moment while a switch
105 # reexecutes systemd ("Failed to connect to system scope bus");
106 # that is retried, not taken for the unit having finished.
107 follow() {
108 ssh "''${ssh_opts[@]}" "$target" bash -s -- "$1" "$state" <<'EOF'
109 unit=$1 log=$2/$1.log
110 query() {
111 until systemctl show "$@" "$unit" 2>/dev/null; do sleep 1; done
112 }
113 while case $(query -p ActiveState -p SubState) in
114 *ActiveState=activating* | *SubState=running*) true ;;
115 *) false ;;
116 esac; do
117 sleep 1
118 done &
119 tail -n +1 -F --pid=$! "$log" 2>/dev/null
120 [ "$(query -p Result --value)" = success ] && exit 0
121 echo "deploy: $unit failed (exit status $(query -p ExecMainStatus --value)), log: $log" >&2
122 exit 1
123 EOF
124 }
125
126 # source_diff: per-file +/- summary, then the full diff, of the
127 # running system's source against the incoming one.
128 source_diff() {
129 ssh "''${ssh_opts[@]}" "$target" bash -s -- "$state" <<'EOF'
130 old=$1/src new=$1/incoming
131 if [ ! -d "$old" ]; then
132 echo "no source recorded for the running system"
133 exit 0
134 fi
135 # diff exits 1 when the trees differ, 2 on trouble.
136 d() { diff -ruN "$@" "$old" "$new" || [ $? -eq 1 ]; }
137 d | awk -v pre="$new/" '
138 /^diff -ruN / {
139 f = substr($0, index($0, " " pre) + 1 + length(pre))
140 files[++n] = f; hdr = 2; next
141 }
142 hdr > 0 { hdr--; next }
143 /^\+/ { add[f]++ }
144 /^-/ { del[f]++ }
145 END {
146 if (n == 0) { print "no source changes"; exit }
147 for (i = 1; i <= n; i++) {
148 f = files[i]
149 printf " %-60s \033[32m+%d\033[0m \033[31m-%d\033[0m\n", f, add[f], del[f]
150 }
151 printf "%d files changed\n\n", n
152 }'
153 d --color=always
154 EOF
155 }
156
157 step "connecting to $target"
158 remote true || { echo "deploy: cannot reach $target" >&2; exit 1; }
159 # shellcheck disable=SC2016 # expanded on the target
160 remote 'test -e /etc/NIXOS && command -v systemd-run >/dev/null' ||
161 { echo "deploy: $target is not a NixOS system with systemd" >&2; exit 1; }
162 if in_progress deploy-switch; then
163 step "a switch is still running on $target, attaching"
164 follow deploy-switch
165 exit
166 fi
167
168 # Decrypt the bulk key once (one Secure Enclave unlock); every
169 # later pass call from clan then uses it without prompting.
170 PASS_BULK_KEY_FILE="" pass show bulk-operations/age-key >"$tmp/bulk-key"
171 if [ ! -s "$tmp/bulk-key" ]; then
172 echo "deploy: could not extract the bulk key" >&2
173 exit 1
174 fi
175 export PASS_BULK_KEY_FILE="$tmp/bulk-key"
176
177 if in_progress deploy-build; then
178 step "a build is still running on $target, attaching"
179 else
180 step "generating vars for $machine"
181 pass git pull --rebase
182 clan vars generate --flake "$flake" "$machine"
183 pass git push
184
185 step "copying source to $target:$state/incoming"
186 # The flake source exactly as nix sees it: tracked files only.
187 src=$(nix flake metadata --json "$flake" | jq -r .path)
188 tar -C "$src" --owner=0 --group=0 --numeric-owner -czf - . |
189 remote "rm -rf $state/incoming.new && mkdir -p $state/incoming.new &&" \
190 "tar -C $state/incoming.new -xzf - &&" \
191 "rm -rf $state/incoming && mv $state/incoming.new $state/incoming"
192
193 step "source changes"
194 source_diff | page
195
196 step "building $machine on $target"
197 # nvd comes from the machine's own nixpkgs, so it is built for
198 # the target and usually substituted; out-links are result
199 # (system) and result-1 (nvd), in installable order.
200 start deploy-build \
201 /run/current-system/sw/bin/nix --extra-experimental-features "nix-command flakes" \
202 --log-format internal-json -v build --out-link "$state/result" \
203 "$state/incoming#nixosConfigurations.$machine.config.system.build.toplevel" \
204 "$state/incoming#nixosConfigurations.$machine.pkgs.nvd"
205 fi
206 follow deploy-build | nom --json
207 system=$(remote readlink -f "$state/result")
208
209 step "closure changes"
210 if [ "$(remote readlink -f /run/current-system)" = "$system" ]; then
211 echo "$system is already running"
212 else
213 remote "$state/result-1/bin/nvd diff /run/current-system $system"
214 fi
215
216 read -r -p "switch $target to $system? [y/N] " answer </dev/tty
217 if [[ $answer != [yY]* ]]; then
218 echo "aborted, $target is unchanged" >&2
219 exit 1
220 fi
221
222 step "uploading secrets"
223 secret_location=$(remote "$nix eval --raw $state/incoming#nixosConfigurations.$machine.config.clan.core.vars.password-store.secretLocation")
224 clan vars upload --flake "$flake" --directory "$tmp/vars" "$machine"
225 if [ -s "$tmp/vars/.pass_info" ] &&
226 [ "$(remote cat "$secret_location/.pass_info" 2>/dev/null)" = "$(cat "$tmp/vars/.pass_info")" ]; then
227 echo "secrets in $secret_location unchanged"
228 else
229 # Same layout and permissions as `clan vars upload`; swapped in
230 # with a rename so the directory is never empty.
231 find "$tmp/vars" -type d -exec chmod 700 {} +
232 find "$tmp/vars" -type f -exec chmod 400 {} +
233 # shellcheck disable=SC2016 # expanded on the target
234 tar -C "$tmp/vars" --owner=0 --group=0 --numeric-owner -czf - . |
235 remote "d=$secret_location;" \
236 'rm -rf "$d.new" "$d.old" && install -d -m 700 "$d.new" && tar -C "$d.new" -xzf - &&' \
237 '{ [ ! -e "$d" ] || mv "$d" "$d.old"; } && mv "$d.new" "$d" && rm -rf "$d.old"'
238 fi
239
240 step "switching $target"
241 start deploy-switch \
242 -p "ExecStartPre=/run/current-system/sw/bin/nix-env -p /nix/var/nix/profiles/system --set $system" \
243 -p "ExecStartPre=/bin/sh -c 'rm -rf $state/src && cp -a $state/incoming $state/src'" \
244 "$system/bin/switch-to-configuration" switch
245 follow deploy-switch
246 '';
247 }).overrideAttrs
248 { passthru.usage = builtins.readFile ./usage.kdl; };
249 };
250}