1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
# NAME
# krops.nix - deployment entry point
#
# SYNOPSIS
# $(nix-build krops.nix --no-out-link --argstr name HOSTNAME -A ACTION)
#
# ACTIONS
# deploy build the system on the target and switch to it
# diff build the system on the target and show what switching to it
# would change
#
# ARGUMENTS
# name the host to deploy
# target where to deploy it, instead of spec.nix's target
# switch what switch-to-configuration does: switch (the default), boot,
# or test (no new generation)
#
# REMOTE BUILDS
# A host whose spec.nix lists builders (ssh destinations, e.g.
# [ "root@zu.r" ]) gets evaluated on the deploying host, from sources
# populated into $HOST_CACHEDIR/src/HOSTNAME (default: ~/tmp/cache/hrm;
# git sources as symlinks to this host's checkouts of the same name at
# the same revision, else shallow clones),
# and built on the first builder that answers. The builder keeps a GC
# root in /var/hrm/HOSTNAME/system and copies the system to the target
# (or, with copyVia = "deployer", the deploying host copies it from the
# builder).
# The target gets only its secrets, and activates. A record of each such
# build goes to $PORTABLE_CACHEDIR/builds.jsonl (default:
# ~/shared-tmp/cache/hrm), the evaluated derivation's GC root to
# $HOST_CACHEDIR/roots/HOSTNAME.drv.
#
{ lib ? import ~/sync/src/krops/lib
, pkgs ? import ~/sync/src/krops/pkgs {}
, name
, target ? null
, switch ? "switch"
}@args:
assert builtins.elem switch [ "switch" "boot" "test" ];
rec {
spec = {
nixpkgs = "nixos-26.05";
target = "root@${name}.r/var/src";
builders = [];
copyVia = "builder";
targetStore = "ssh-ng";
} // import ./systems/${name}/spec.nix;
target = if args.target or null != null then args.target else spec.target;
sources = {
hrm.file = {
path = toString ~/sync/src/hrm;
};
nixos-config.symlink = {
target = "hrm/systems/${name}/config.nix";
};
nixpkgs.git = {
ref = (lib.importJSON ./nixpkgs.json).${spec.nixpkgs}.rev;
url = "https://github.com/NixOS/nixpkgs";
};
secrets.passage = {
age = "${pkgs.rage}/bin/rage";
dir = toString ~/sync/secrets/${name};
identities_file = toString ~/.passage/identities;
};
stockholm.file = {
path = toString ~/sync/src/stockholm;
};
};
source = lib.evalSource [ sources ];
# What a host with builders gets on the target, which it needs at run
# time; everything else in sources is for evaluation.
targetSources = { inherit (sources) secrets; };
deploy = hrm.legacy.deploy;
diff = hrm.legacy.diff;
hrm.legacy.deploy = mkAction "legacy" "deploy";
hrm.legacy.diff = mkAction "legacy" "diff";
hrm.flake.deploy = mkAction "flake" "deploy";
hrm.flake.diff = mkAction "flake" "diff";
mkAction = build-method: deploy-action:
if spec.builders == [] then
mkTargetBuildAction build-method deploy-action
else
assert build-method == "legacy";
pkgs.writers.writeDash "${name}-deploy-remote-${deploy-action}"
(remoteBuildScript deploy-action);
mkTargetBuildAction = build-method: deploy-action: let
target' = lib.mkTarget target;
name' = "${name}-deploy-${build-method}-${deploy-action}";
in
pkgs.writers.writeDash name' /* sh */ ''
set -efu
${pkgs.populate { source = source; target = target'; }}
${pkgs.krops.runShell target' { allocateTTY = true; } /* sh */ ''
set -efu
system=$(
export NIX_PATH=${lib.escapeShellArg target'.path}
${builtins.getAttr build-method {
legacy = /* sh */ ''
nix-build \
-j 1 \
--show-trace \
--attr nixosConfigurations.${name}.config.system.build.toplevel \
'<hrm/legacy.nix>'
'';
flake = /* sh */ ''
nix build \
--print-build-logs \
--show-trace \
--print-out-paths \
"$NIX_PATH"/hrm#nixosConfigurations.${name}.config.system.build.toplevel
'';
}}
)
${builtins.getAttr deploy-action {
deploy = let
setAndSwitch = /* sh */ ''
old_gen=$(readlink -f /nix/var/nix/profiles/system)
new_gen=$(readlink -f "$system")
if [ "x$old_gen" != "x$new_gen" ]; then
nix-env -p /nix/var/nix/profiles/system --set "$system"
"$system"/bin/switch-to-configuration ${switch}
else
echo 'Configuration is already up to date' >&2
fi
'';
in builtins.getAttr switch {
switch = setAndSwitch;
boot = setAndSwitch;
test = /* sh */ ''
"$system"/bin/switch-to-configuration test
'';
};
diff = /* sh */ ''
nix --extra-experimental-features nix-command \
store diff-closures /run/current-system "$system"
if command -v nix-diff >/dev/null; then
nix-diff --environment --skip-already-compared /run/current-system "$system"
else
NIX_PATH=${lib.escapeShellArg target'.path} \
nix-shell -p nix-diff --run \
"nix-diff --environment --skip-already-compared /run/current-system $system"
fi
"$system"/bin/switch-to-configuration dry-activate
'';
}}
''}
'';
# The deploy or diff script for a host with builders. Its own attribute,
# so its text can be checked without building it.
remoteBuildScript = deploy-action: let
target' = lib.mkTarget target;
q = lib.escapeShellArg;
nix = "nix --extra-experimental-features nix-command";
jq = "${pkgs.jq}/bin/jq";
targetDest =
lib.optionalString (target'.user != null) "${target'.user}@" + target'.host;
targetSSHOpts =
lib.optionalString (target'.port != null) "-p ${target'.port}";
targetURL = "${spec.targetStore}://${targetDest}";
targetSource = lib.evalSource [ targetSources ];
# Sources for evaluating here, in a directory of this host, populated as
# onto a target: everything but targetSources. Git sources link to this
# host's checkout of the same name at the same revision, if it has one,
# else get cloned, shallow until populate shares Git objects.
hostCache = let
dir = builtins.getEnv "HOST_CACHEDIR";
in if dir != "" then dir else toString ~/tmp/cache/hrm;
evalTarget = lib.mkTarget "${hostCache}/src/${name}";
# The revision of a checkout: its Git HEAD, or nixpkgs' .git-revision.
revisionOf = path: let
git = "${path}/.git";
revisionFile = "${path}/.git-revision";
in
if lib.pathIsGitRepo git then lib.commitIdFromGitRepo git
else if builtins.pathExists revisionFile then lib.fileContents revisionFile
else null;
# This host's <NAME>, if it's at revision REV.
hereAt = name: rev: let
found = builtins.tryEval (builtins.findFile builtins.nixPath name);
in
if found.success && revisionOf (toString found.value) == rev
then toString found.value
else null;
evalSource = lib.evalSource [
(lib.mapAttrs (name: source:
if source ? git then
let here = hereAt name source.git.ref; in
if here != null
then { symlink.target = here; }
else { git = source.git // { shallow = true; }; }
else source
) (removeAttrs sources (lib.attrNames targetSources)))
];
# Runs SCRIPT on the target, with the system's store path on standard
# input (read -r system).
onTarget = script: /* sh */ ''
printf '%s\n' "$system" |
${pkgs.krops.runShell target' {} /* sh */ ''
set -efu
read -r system
${script}
''}
'';
in /* sh */ ''
set -efu
name=${q name}
portable_cache=''${PORTABLE_CACHEDIR:-$HOME/shared-tmp/cache/hrm}
host_cache=''${HOST_CACHEDIR:-$HOME/tmp/cache/hrm}
mkdir -p "$portable_cache" "$host_cache"/roots
#
# Sources for evaluating here, but nothing of targetSources: evaluation
# must not resolve <secrets> here, where it would yield this host's
# paths.
#
eval_dir=${q evalTarget.path}
mkdir -p "$eval_dir"
${pkgs.populate { source = evalSource; target = evalTarget; }}
export NIX_PATH="$eval_dir"
#
# Evaluate here, keeping the derivation for diff.
#
echo "$name: evaluating..." >&2
drv=$(nix-instantiate \
--show-trace \
--add-root "$host_cache"/roots/"$name".drv \
--attr nixosConfigurations."$name".config.system.build.toplevel \
'<hrm/legacy.nix>')
#
# Choose the first builder that answers, and note its state.
#
builder=
for candidate in ${lib.concatMapStringsSep " " q spec.builders}; do
if builder_state=$(ssh -o BatchMode=yes -o ConnectTimeout=5 "$candidate" \
'printf "%s %s %s %s\n" "$(cut -d" " -f1 /proc/loadavg)" "$(nproc)" \
"$(awk "/^MemAvailable:/{print \$2*1024}" /proc/meminfo)" \
"$(df -B1 --output=avail /nix | tail -n 1)"')
then
builder=$candidate
break
fi
echo "$name: builder $candidate doesn't answer" >&2
done
if test -z "$builder"; then
echo "$name: error: no builder answers: "${q (toString spec.builders)} >&2
exit 1
fi
set -- $builder_state
builder_load=$1 builder_cpus=$2 builder_mem=$3 builder_disk=$4
#
# Build on the builder, into its store, and keep it there.
#
echo "$name: building on $builder..." >&2
build_start=$(date +%s)
${nix} copy --no-check-sigs --derivation --to ssh-ng://"$builder" "$drv"
system=$(nix-store --store ssh-ng://"$builder" --realise "$drv")
build_end=$(date +%s)
ssh "$builder" "mkdir -p /var/hrm/$name &&
nix-store --realise $system --add-root /var/hrm/$name/system >/dev/null"
#
# Copy the system to the target.
#
copy_start=$(date +%s)
${if spec.copyVia == "deployer" then /* sh */ ''
echo "$name: copying from $builder via this host..." >&2
NIX_SSHOPTS=${q targetSSHOpts} \
${nix} copy --no-check-sigs \
--from ssh-ng://"$builder" --to ${q targetURL} "$system"
'' else /* sh */ ''
if ! check=$(ssh "$builder" ssh -o BatchMode=yes -o ConnectTimeout=10 \
${targetSSHOpts} ${q targetDest} true 2>&1)
then
echo "$name: error: $builder can't log in to "${q targetDest}":" >&2
printf '%s\n' "$check" >&2
case $check in
*'Host key verification failed'*)
echo "$name: $builder doesn't know the target's host key; add it" \
"to $builder's known hosts (e.g. programs.ssh.knownHosts)." >&2
;;
*'Permission denied'*)
echo "$name: the target doesn't accept $builder's key; add it to" \
"the target's authorized keys:" >&2
ssh "$builder" 'cat ~/.ssh/id_*.pub' >&2 || :
;;
*)
echo "$name: check the network between $builder and the target." >&2
;;
esac
exit 1
fi
echo "$name: copying from $builder..." >&2
ssh "$builder" "NIX_SSHOPTS='${targetSSHOpts}' ${nix} copy --no-check-sigs \
--to ${targetURL} $system"
''}
copy_end=$(date +%s)
#
# Note what happened, for choosing builders later.
#
closure_size=$(${nix} path-info --store ssh-ng://"$builder" -S "$system" | cut -f2)
${jq} -nc \
--arg host "$name" --arg action ${q deploy-action} \
--arg deployer "$(cat /etc/hostname)" --arg builder "$builder" \
--arg system "$system" --arg via ${q spec.copyVia} \
--argjson build_start "$build_start" --argjson build_end "$build_end" \
--argjson copy_start "$copy_start" --argjson copy_end "$copy_end" \
--argjson closure_size "$closure_size" \
--argjson builder_load "$builder_load" --argjson builder_cpus "$builder_cpus" \
--argjson builder_mem "$builder_mem" --argjson builder_disk "$builder_disk" \
'$ARGS.named' >> "$portable_cache"/builds.jsonl
${builtins.getAttr deploy-action {
deploy = let
setAndSwitch = /* sh */ ''
old_gen=$(readlink -f /nix/var/nix/profiles/system)
new_gen=$(readlink -f "$system")
if [ "x$old_gen" != "x$new_gen" ]; then
nix-env -p /nix/var/nix/profiles/system --set "$system"
systemd-run --pipe --wait --collect --quiet \
"$system"/bin/switch-to-configuration ${switch}
else
echo 'Configuration is already up to date' >&2
fi
'';
in /* sh */ ''
# Without prune: the rest of the target's /var/src stays.
${pkgs.populate { source = targetSource; target = target'; }}
${onTarget (builtins.getAttr switch {
switch = setAndSwitch;
boot = setAndSwitch;
test = /* sh */ ''
systemd-run --pipe --wait --collect --quiet \
"$system"/bin/switch-to-configuration test
'';
})}
'';
diff = /* sh */ ''
old_drv=$(${onTarget /* sh */ ''
nix-store --query --deriver "$(readlink -f /run/current-system)"
''})
if nix-store --check-validity "$old_drv" 2>/dev/null; then
${pkgs.nix-diff}/bin/nix-diff --environment --skip-already-compared \
"$old_drv" "$drv"
else
echo "$name: no nix-diff: the running system's derivation isn't" \
"here ($old_drv)" >&2
fi
${onTarget /* sh */ ''
${nix} store diff-closures /run/current-system "$system"
"$system"/bin/switch-to-configuration dry-activate
''}
'';
}}
'';
}
|