# Upgrading the packages (nixpkgs: the kernel and everything else) of an # installed router without a new release of nixos-router. # # The branch to follow is the setting `router.update.channel` (unstable, or a # release like 26.05). nixpkgs is pinned in the configuration flake's # flake.lock, so an upgrade is a new lock: # # router-upgrade check what the channel's newest revision is, against the running one # router-upgrade releases which stable releases exist (nixos-26.05, nixos-26.11, ...), so the # web UI can say when one newer than the followed channel appears # router-upgrade preview lock a copy of the configuration flake to it and evaluate the # system: which packages change version, how much would be # downloaded and built (nothing is downloaded or activated) # router-upgrade download fetch and build it now (a flaky uplink is no problem later) # router-upgrade apply take the lock and run `router-apply` (commit-confirm) # # The revision comes from channels.nixos.org: the branch's last revision that # passed the NixOS tests. A configuration directory that was upgraded keeps # the choice in nixpkgs-pin.json, which `router-update` locks again after it # installs a new release of nixos-router. The directory as it was is kept in # config.pre-update, as for updates: a rollback or a failure puts it back. { config, lib, pkgs, ... }: let cfg = config.routerSettings; up = cfg.upgrade; snapshot = "${cfg.stateDirectory}/config.pre-update"; dir = "${cfg.stateDirectory}/upgrade"; migrate = pkgs.callPackage ../../pkgs/router-migrate.nix { }; repository = toString config.routerUpdate.repository; upgrade = pkgs.writeShellApplication { name = "router-upgrade"; runtimeInputs = [ config.nix.package config.systemd.package migrate pkgs.coreutils pkgs.curl pkgs.gawk pkgs.git pkgs.jq pkgs.util-linux ]; text = '' usage() { echo "usage: router-upgrade check | daily | releases | preview [--force] [--downgrade] | download | apply [timeout] | --request" >&2 echo " check the newest nixpkgs revision of router.update.channel and the newest release tag of nixos-router, against the running ones" >&2 echo " daily check, quietly (a timer runs it)" >&2 echo " releases which stable NixOS releases the channel server has" >&2 echo " preview the new nixos-router and the packages that change, and the size of the download (nothing is fetched)" >&2 echo " download fetch and build what was previewed, without activating it" >&2 echo " apply activate what was previewed (fetching it if need be), with commit-confirm" >&2 exit 2 } die() { echo "router-upgrade: $*" >&2; exit 1; } [ $# -gt 0 ] || usage if [ "$1" = --request ]; then # What the web UI asked for (${dir}/request.json). req=${dir}/request.json [ -r "$req" ] || die "no request" action=$(jq -er .action "$req") force=$(jq -r 'if .force then "--force" else "" end' "$req") downgrade=$(jq -r 'if .downgrade then "--downgrade" else "" end' "$req") timeout=$(jq -r '.timeout // ""' "$req") rm -f "$req" # The web UI shows the last run (a finished unit forgets its journal). exec > >(tee ${dir}/last.log) 2>&1 case $action in preview) set -- preview ''${force:+"$force"} ''${downgrade:+"$downgrade"} ;; apply) set -- apply ''${timeout:+"$timeout"} ;; check | download) set -- "$action" ;; *) die "unknown request: $action" ;; esac fi cmd=$1 shift [ "$(id -u)" -eq 0 ] || die "must run as root" config=${cfg.directory} mkdir -p ${dir} # nixos-router comes from this repository (its tags vX.Y.Z); the packages # (nixpkgs) from the channel, if one is followed. Both are inputs of the # configuration flake, and one lock moves them together. repository=${lib.escapeShellArg repository} channel="" branch="" if [ "$cmd" != releases ]; then channel=$(jq -r '.router.update.channel // empty' "$config/settings.json") if [ "$channel" = unstable ]; then branch=nixos-unstable; elif [ -n "$channel" ]; then branch="nixos-$channel"; fi fi running_rev=$(/run/current-system/sw/bin/nixos-version --revision || true) running_version=$(cat /run/current-system/nixos-version) short() { echo "''${1:0:7}"; } newest_rev() { local rev # (channels.nixos.org answers with a redirect to releases.nixos.org.) rev=$(curl -fsSL --max-time 30 "${up.channelsUrl}/$branch/git-revision") \ || die "cannot read ${up.channelsUrl}/$branch/git-revision (no internet, or no channel of that name)" [[ $rev =~ ^[0-9a-f]{40}$ ]] || die "unexpected answer for $branch: ''${rev:0:60}" echo "$rev" } # The stable releases the channel server has (nixos-YY.05 and nixos-YY.11, from last # year to next year), written to ${dir}/releases.json. A release that is not there yet # answers 404. If nothing answers (no internet) the list is left as it was. releases() { local yy m r code answered=0 local found=() for yy in $(( 10#$(date +%y) - 1 )) $(( 10#$(date +%y) )) $(( 10#$(date +%y) + 1 )); do for m in 05 11; do r="$yy.$m" code=$(curl -sL --max-time 20 -o /dev/null -w '%{http_code}' "${up.channelsUrl}/nixos-$r/git-revision" || true) case $code in 200) found+=("$r"); answered=1 ;; 404) answered=1 ;; esac done done [ "$answered" -eq 1 ] || return 0 jq -n --arg time "$(date -u +%FT%TZ)" '{time: $time, releases: $ARGS.positional}' --args "''${found[@]}" > ${dir}/releases.json.new mv ${dir}/releases.json.new ${dir}/releases.json echo "releases on the channel server: ''${found[*]:-none}" } # The release tags of the repository, "TAG REVISION" per line, oldest first (an # annotated tag counts with the commit it points to). git_tags() { git ls-remote --tags "$1" 'refs/tags/v*' | awk ' { n = $2; sub("^refs/tags/", "", n); peeled = (n ~ /\^\{\}$/); sub(/\^\{\}$/, "", n) if (n !~ /^v[0-9]+\.[0-9]+\.[0-9]+$/) next if (peeled) p[n] = $1; else d[n] = $1 seen[n] = 1 } END { for (n in seen) print n, (n in p ? p[n] : d[n]) }' | sort -V } installed_router=$(jq -r '.version // "unknown"' /etc/router-release 2>/dev/null || echo unknown) r_tag="" r_rev="" r_version="" r_newer=false check() { releases || true local packages_same=true router_json=null tags newest="" if [ -n "$channel" ]; then newest=$(newest_rev) if [ "$newest" != "$running_rev" ]; then packages_same=false; fi fi if [ -n "$repository" ]; then # (Not fatal: the packages can still be looked at.) if tags=$(git_tags "$repository" 2>/dev/null) && [ -n "$tags" ]; then read -r r_tag r_rev <<<"$(tail -n 1 <<<"$tags")" r_version=''${r_tag#v} if [ "$r_version" != "$installed_router" ] \ && [ "$(printf '%s\n%s\n' "$installed_router" "$r_version" | sort -V | tail -n 1)" = "$r_version" ]; then r_newer=true fi router_json=$(jq -n --arg repo "$repository" --arg installed "$installed_router" --arg tag "$r_tag" \ --arg version "$r_version" --arg rev "$r_rev" --argjson newer "$r_newer" \ '{repository: $repo, installed: $installed, newest: {tag: $tag, version: $version, rev: $rev}, newer: $newer}') else echo "router-upgrade: cannot read the release tags of $repository" >&2 fi fi [ -n "$channel" ] || [ "$router_json" != null ] \ || die "nothing to look at: no channel is set (router.update.channel: unstable, or a release like 26.05) and the repository cannot be read" if [ "$packages_same" = true ] && [ "$r_newer" = false ]; then same=true; else same=false; fi jq -n --arg channel "$channel" --arg branch "$branch" --arg time "$(date -u +%FT%TZ)" \ --arg running "$running_rev" --arg version "$running_version" --arg newest "$newest" \ --argjson packagesUpToDate "$packages_same" --argjson upToDate "$same" --argjson router "$router_json" \ '{channel: $channel, branch: $branch, time: $time, running: {rev: $running, version: $version}, newest: {rev: $newest}, packagesUpToDate: $packagesUpToDate, upToDate: $upToDate, router: $router}' > ${dir}/check.json.new mv ${dir}/check.json.new ${dir}/check.json if [ "$router_json" != null ]; then echo "nixos-router ($repository)" echo " installed $installed_router" echo " newest $r_version" fi if [ -n "$channel" ]; then echo "channel $channel ($branch)" echo " running $running_version" echo " newest $(short "$newest")" fi if [ "$same" = true ]; then echo "up to date"; else echo "a newer version is available"; fi } # The names (with versions) of store paths, one per line. names() { sed -e 's|^/nix/store/[a-z0-9]\{32\}-||' -e 's/\.drv$//'; } # The packages of the running system none of whose versions is among the # new system's derivations': {name, from, to}. Approximate: a package that is rebuilt # without a new version is not listed, and build-time versions of a package that # the system does not run are not either. changes() { # file of the running system's paths, file of the new system's jq -n --rawfile old "$1" --rawfile new "$2" ' def lines: split("\n") | map(select(. != "" and (test("\\.(tar|patch|diff|zip|tgz|tbz2?|txz|gz|xz|bz2|sh|py|nix|json|conf|asc|sig|lock)$") | not))); def strip: sub("-(bin|dev|lib|out|man|doc|info|devdoc|static|lib32|modules|modules-shrunk|libgcc|getent|debug)$"; ""); def parse: capture("^(?.*?)-(?[0-9].*)$") // {n: ., v: ""}; # Among the new versions of a package, one that continues another (5.6.0-go next # to 5.6.0) belongs to a build-time part of it (lego-5.6.0-go-modules). def own: . as $all | map(select(. as $v | $all | any(. as $p | $p != $v and ($v | startswith($p + "-"))) | not)); def table: map(strip | parse) | group_by(.n) | map({key: .[0].n, value: (map(.v) | unique)}) | from_entries; ($old | lines | table) as $o | ($new | lines | table) as $n | [ $o | to_entries[] | select($n[.key] != null and .value != [""]) | select(((.value - $n[.key]) | length) == (.value | length) and (($n[.key] - .value) | length) > 0) | {name: .key, from: (.value | join(", ")), to: ($n[.key] - .value | own | join(", "))} ] | map(select(.name | startswith("nixos-system-") | not)) | sort_by(.name)' } preview() { local force=0 downgrade=0 arg for arg in "$@"; do case $arg in --force) force=1 ;; --downgrade) downgrade=1 ;; *) usage ;; esac done check rm -rf ${dir}/preview.json ${dir}/flake ${dir}/base ${dir}/git-release ${dir}/result if [ "$same" = true ] && [ "$force" -eq 0 ]; then return 0; fi mkdir ${dir}/flake ${dir}/base for f in flake.nix settings.json local.nix flake.lock; do if [ -e "$config/$f" ]; then cp "$config/$f" ${dir}/flake/; fi done # What the directory was like: apply refuses to go on when it changed. cp "$config/flake.nix" "$config/settings.json" ${dir}/base/ # A newer nixos-router is one more input to lock: its source, from the tag, and # the flake it brings, which names that source (config-flake.nix, with the # address filled in), and the settings migrated to its schema. router_new=false if [ "$r_newer" = true ]; then src="git+$repository?ref=refs/tags/$r_tag&rev=$r_rev" echo "router-upgrade: fetching nixos-router $r_version ($(short "$r_rev"))" # (No registry: the address is complete, and the global one is a download.) meta=$(nix --option flake-registry "" flake prefetch --json "$src") || die "cannot fetch $src" tree=$(jq -er .storePath <<<"$meta") if [ ! -r "$tree/config-flake.nix" ] || [ ! -r "$tree/VERSION" ]; then die "$r_tag is not a release this updater can build (no config-flake.nix or VERSION)" fi # What a release carries, made from the source: what the migration reads. rel=${dir}/git-release mkdir -p "$rel/migrations" tr -d '\n' < "$tree/VERSION" > "$rel/version" jq -er .locked.lastModified <<<"$meta" | tr -d '\n' > "$rel/serial" printf %s "$r_rev" > "$rel/rev" find "$tree/migrations" -name '*.jq' -exec cp {} "$rel/migrations/" \; find "$rel/migrations" -name '*.jq' | wc -l | tr -d '\n' > "$rel/schema" # (jq, not a shell substitution: the address has a & in it.) jq -rRs --arg source "$src" 'gsub("@SOURCE@"; $source)' "$tree/config-flake.nix" > ${dir}/flake/flake.nix rm -f ${dir}/flake/flake.lock router-migrate-settings "$rel" ${dir}/flake/settings.json || die "migrating the settings to nixos-router $r_version failed" router_new=true fi # The packages: the channel's revision; without a channel the one an earlier # upgrade chose stays, else the nixos-router's own. ref="" pin="" if [ -n "$channel" ]; then ref="${up.nixpkgsRef}" ref=''${ref//%rev%/$newest} elif [ -r "$config/nixpkgs-pin.json" ]; then ref=$(jq -r .ref "$config/nixpkgs-pin.json") fi lock=(nix flake lock) if [ -n "$ref" ]; then lock+=(--override-input nixos-router/nixpkgs "$ref"); fi if [ "$router_new" = true ]; then echo "router-upgrade: locking nixos-router $r_version and the packages" else echo "router-upgrade: locking the packages''${newest:+ to $(short "$newest")}" fi "''${lock[@]}" "path:${dir}/flake" if [ -n "$channel" ]; then node=$(jq -r '.nodes[.nodes[.root].inputs["nixos-router"]].inputs.nixpkgs' ${dir}/flake/flake.lock) hash=$(jq -er --arg n "$node" '.nodes[$n].locked.narHash' ${dir}/flake/flake.lock) case $ref in *narHash=*) pin=$ref ;; *\?*) pin="$ref&narHash=$hash" ;; *) pin="$ref?narHash=$hash" ;; esac fi attr="path:${dir}/flake#nixosConfigurations.router.config.system" echo "router-upgrade: evaluating the new system" new_version=$(nix eval --raw "$attr.nixos.version") # The release (26.05) of a version like 26.05.20260101.abcdef0 or 26.11pre-git. release() { sed -E 's/^([0-9]+\.[0-9]+).*/\1/' <<<"$1"; } newer=$(printf '%s\n%s\n' "$(release "$new_version")" "$(release "$running_version")" | sort -V | tail -1) if [ "$newer" != "$(release "$new_version")" ]; then [ "$downgrade" -eq 1 ] \ || die "$new_version is older than the running $running_version: NixOS cannot be downgraded safely (use --downgrade to try anyway)" echo "router-upgrade: warning: $new_version is older than the running $running_version; state written by the newer release may not work with it" fi drv=$(nix eval --raw "$attr.build.toplevel.drvPath") nix path-info -r /run/current-system | names > ${dir}/old.names nix path-info -r "$drv" | names > ${dir}/new.names changes ${dir}/old.names ${dir}/new.names > ${dir}/changes.json rm -f ${dir}/old.names ${dir}/new.names if [ "$(jq length ${dir}/changes.json)" -gt 0 ]; then jq -r '.[] | " \(.name): \(.from) -> \(.to)"' ${dir}/changes.json else echo " no package changes" fi if jq -e 'any(.[]; .name == "linux")' ${dir}/changes.json > /dev/null; then reboot=true; else reboot=false; fi # Nothing is fetched: the substituters only say what they have. dry=$(nix build --dry-run --no-link "$attr.build.toplevel" 2>&1 || true) download=$(grep -o '([0-9.]* [KMGT]iB download, [0-9.]* [KMGT]iB unpacked)' <<<"$dry" | head -1 || true) builds=$(grep -cE '^ +/nix/store/[^ ]*\.drv$' <<<"$dry" || true) echo " to fetch: ''${download:-nothing, or no cache reachable}; to build here: $builds" # What would be built here: the derivations' names (the system's own pieces, mostly). { grep -E '^ +/nix/store/[^ ]*\.drv$' <<<"$dry" || true; } | sed 's/^ *//' | names | sort -u > ${dir}/builds.txt sed 's/^/ /' ${dir}/builds.txt | head -n 60 if [ "$(wc -l < ${dir}/builds.txt)" -gt 60 ]; then echo " ... and $(( $(wc -l < ${dir}/builds.txt) - 60 )) more"; fi # What changes in nixos-router itself, if it does: shown above the packages. router_change=null if [ "$router_new" = true ]; then router_change=$(jq -n --arg from "$installed_router" --arg to "$r_version" --arg tag "$r_tag" --arg rev "$r_rev" \ '{from: $from, to: $to, tag: $tag, rev: $rev}') echo " nixos-router: $installed_router -> $r_version" fi jq -n --arg channel "$channel" --arg release "$installed_router" --arg rev "$newest" --arg ref "$pin" --arg version "$new_version" \ --arg time "$(date -u +%FT%TZ)" --arg download "$download" --argjson builds "$builds" --argjson router "$router_change" \ --argjson reboot "$reboot" --slurpfile changes ${dir}/changes.json --rawfile buildNames ${dir}/builds.txt \ '{channel: $channel, release: $release, rev: $rev, ref: $ref, version: $version, time: $time, download: $download, builds: $builds, buildNames: ($buildNames | split("\n") | map(select(. != "")) | .[:300]), rebootNeeded: $reboot, router: $router, changes: $changes[0]}' > ${dir}/preview.json rm -f ${dir}/builds.txt echo "$new_version$([ "$reboot" = false ] || echo ' (a new kernel runs after a reboot)'): router-upgrade apply activates it" } download() { [ -r ${dir}/preview.json ] || die "nothing is previewed (router-upgrade preview)" free=$(df --output=avail -B1M /nix/store | tail -1) [ "$free" -ge 3072 ] || die "less than 3 GiB free on /nix/store (''${free} MiB): free some space first" echo "router-upgrade: fetching and building (nothing is activated)" nix build --no-link --out-link ${dir}/result \ "path:${dir}/flake#nixosConfigurations.router.config.system.build.toplevel" echo "downloaded $(jq -r .version ${dir}/preview.json); router-upgrade apply activates it" } apply() { local timeout=''${1:-} [ -r ${dir}/preview.json ] || die "nothing is previewed (router-upgrade preview)" exec 9>/run/router-update.lock flock -n 9 || die "an update or upgrade is running" [ ! -d ${snapshot} ] || die "an earlier update or upgrade is not confirmed yet" cmp -s "$config/flake.nix" ${dir}/base/flake.nix \ || die "the configuration flake changed since it was previewed: preview again" # A new nixos-router brings migrated settings: they are taken over whole. router_to=$(jq -r '.router.to // ""' ${dir}/preview.json) if [ -n "$router_to" ]; then cmp -s "$config/settings.json" ${dir}/base/settings.json \ || die "the settings changed since the upgrade was previewed: preview again" fi cp -a "$config" ${snapshot} fail() { echo "router-upgrade: $*" >&2 /run/current-system/sw/bin/router-update-restore exit 1 } if [ -n "$router_to" ]; then cp ${dir}/flake/flake.nix "$config/flake.nix" cp ${dir}/flake/settings.json "$config/settings.json" fi cp ${dir}/flake/flake.lock "$config/flake.lock" # The packages that were chosen stay chosen when nixos-router is updated later. if [ -n "$(jq -r '.ref // ""' ${dir}/preview.json)" ]; then jq '{channel, rev, ref}' ${dir}/preview.json > "$config/nixpkgs-pin.json" fi echo "router-upgrade: building and activating ''${router_to:+nixos-router $router_to on }$(jq -r .version ${dir}/preview.json)" if ! router-apply ''${timeout:+"$timeout"}; then if systemctl is-active --quiet router-rollback.timer; then # Activation failed half way: the rollback restores the configuration. systemctl start router-rollback.service die "the upgrade failed; the previous system is back" fi fail "the upgrade failed; the previous system is back" fi rm -rf ${dir}/preview.json ${dir}/flake ${dir}/base ${dir}/git-release ${dir}/result if systemctl is-active --quiet router-rollback.timer; then echo "router-upgrade: active; confirm it (router-confirm, or in the web UI) or the previous system comes back" else rm -rf ${snapshot} # nothing changed: nothing to confirm fi } case $cmd in check) check ;; # For the timer: a router with nothing to look at, or no internet, is no failure. daily) check || echo "router-upgrade: nothing was looked at" >&2 ;; releases) releases ;; preview) preview "$@" ;; download) download ;; apply) apply "$@" ;; *) usage ;; esac ''; }; in { options.routerSettings.upgrade = { channelsUrl = lib.mkOption { type = lib.types.str; default = "https://channels.nixos.org"; description = "Where the newest revision of a nixpkgs branch is read (`/git-revision`)."; }; nixpkgsRef = lib.mkOption { type = lib.types.str; default = "github:NixOS/nixpkgs/%rev%"; description = "The flake reference of a nixpkgs revision (`%rev%` stands for it)."; }; }; config = { environment.systemPackages = [ upgrade ]; # The web UI starts this rather than running anything itself, so a switch # that restarts the UI does not cut an upgrade short; a switch must not # restart or stop it either (router-apply is what runs the switch). # Is there something newer (a nixos-router release, a nixpkgs revision of the # channel, a NixOS release), once a day: the web UI says so on the Overview. It # only asks the servers and writes small files, so it is a unit of its own that # never holds up an upgrade. systemd.services.router-upgrade-notice = { description = "Look for newer versions of nixos-router and NixOS"; path = [ "/run/current-system/sw" ]; serviceConfig = { Type = "oneshot"; ExecStart = "${lib.getExe upgrade} daily"; TimeoutStartSec = "5min"; }; }; systemd.timers.router-upgrade-notice = { wantedBy = [ "timers.target" ]; timerConfig = { OnCalendar = "daily"; RandomizedDelaySec = "1h"; Persistent = true; }; }; systemd.services.router-upgrade = { description = "Look for, prepare or apply a nixpkgs upgrade"; restartIfChanged = false; stopIfChanged = false; path = [ "/run/current-system/sw" ]; serviceConfig = { Type = "oneshot"; ExecStart = "${lib.getExe upgrade} --request"; TimeoutStartSec = "2h"; }; }; }; }