# 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 \ '' ''; 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 , 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 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 \ '') # # 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 ''} ''; }} ''; }