diff options
| -rw-r--r-- | krops.nix | 288 |
1 files changed, 265 insertions, 23 deletions
@@ -15,6 +15,20 @@ # 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; +# nixpkgs as a symlink to <nixpkgs> when that's at the pinned revision), +# 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 @@ -29,32 +43,39 @@ 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; - source = lib.evalSource [ - { - 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; - }; - } - ]; + 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; @@ -64,7 +85,15 @@ rec { hrm.flake.deploy = mkAction "flake" "deploy"; hrm.flake.diff = mkAction "flake" "diff"; - mkAction = build-method: deploy-action: let + 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 @@ -126,4 +155,217 @@ rec { }} ''} ''; + + # 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"; + git = "${pkgs.git}/bin/git"; + 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 and nixpkgs. + hostCache = let + dir = builtins.getEnv "HOST_CACHEDIR"; + in if dir != "" then dir else toString ~/tmp/cache/hrm; + evalTarget = lib.mkTarget "${hostCache}/src/${name}"; + evalSource = lib.evalSource [ + (removeAttrs sources (lib.attrNames targetSources ++ [ "nixpkgs" ])) + ]; + nixpkgsSource = lib.evalSource [ { inherit (sources) nixpkgs; } ]; + # 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. nixpkgs: this host's <nixpkgs> if it's at the pinned revision, + # as a symlink, else populated like any other git source. + # + eval_dir=${q evalTarget.path} + mkdir -p "$eval_dir" + ${pkgs.populate { source = evalSource; target = evalTarget; }} + nixpkgs=$(nix-instantiate --find-file nixpkgs 2>/dev/null) || nixpkgs= + nixpkgs_has= + if test -z "$nixpkgs"; then + : + elif test -e "$nixpkgs"/.git-revision; then + nixpkgs_has=$(cat "$nixpkgs"/.git-revision) + elif ${git} -C "$nixpkgs" rev-parse --git-dir >/dev/null 2>&1 && + test -z "$(${git} -C "$nixpkgs" status --porcelain --untracked-files=no)"; then + nixpkgs_has=$(${git} -C "$nixpkgs" rev-parse HEAD) + fi + if test "$nixpkgs_has" = ${q sources.nixpkgs.git.ref} && + { test -L "$eval_dir"/nixpkgs || ! test -e "$eval_dir"/nixpkgs; } + then + ln -sfn "$nixpkgs" "$eval_dir"/nixpkgs + else + # populate mustn't follow the symlink into this host's own checkout. + if test -L "$eval_dir"/nixpkgs; then + rm "$eval_dir"/nixpkgs + fi + ${pkgs.populate { source = nixpkgsSource; target = evalTarget; }} + fi + 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 + ''} + ''; + }} + ''; } |
