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