# Updating an installed router to a newer version of nixos-router. # # A release is a store path (see `lib.mkRelease`): the new source, its # nixpkgs, the configuration flake that points at them and, for offline # routers, the reference system with everything the rebuild needs. It travels # as a binary cache signed with the update key: a bundle file (uploaded in the # web UI or copied over) or a URL the router pulls from. `router-update` # accepts it only when every path in its closure carries a signature of # `routerUpdate.publicKeys`, then # # 1. imports it into the store, # 2. points the configuration flake at it, # 3. migrates settings.json to the release's schema (migrations/N.jq), # 4. rebuilds with `router-apply` (commit-confirm: unless the update is # confirmed in time, the previous system comes back). # # The configuration directory as it was is kept in config.pre-update until the # update is confirmed; a rollback (or a failed update) puts it back. { config, lib, pkgs, ... }: let cfg = config.routerSettings; keys = config.routerUpdate.publicKeys; settings = lib.importJSON cfg.file; snapshot = "${cfg.stateDirectory}/config.pre-update"; updateDir = "${cfg.stateDirectory}/update"; webui = pkgs.callPackage ../../pkgs/router-webui/package.nix { }; migrate = pkgs.callPackage ../../pkgs/router-migrate.nix { }; restore = pkgs.writeShellApplication { name = "router-update-restore"; runtimeInputs = [ pkgs.coreutils pkgs.findutils ]; text = '' [ -d ${snapshot} ] || exit 0 find ${cfg.directory} -mindepth 1 -delete cp -a ${snapshot}/. ${cfg.directory}/ rm -rf ${snapshot} echo "router: restored the configuration from before the update" ''; }; update = pkgs.writeShellApplication { name = "router-update"; runtimeInputs = [ config.nix.package config.systemd.package webui migrate pkgs.coreutils pkgs.curl pkgs.git pkgs.gawk pkgs.jq pkgs.util-linux ]; text = '' usage() { echo "usage: router-update check | [--force] (--request | --bundle FILE | --url URL | --git TAG|latest) [timeout]" >&2 echo " check the newest release tag of router.update.repository, against the installed version" >&2 echo " --git TAG build the release from a tag (vX.Y.Z, or latest) of router.update.repository" >&2 echo " --bundle FILE a bundle made by router-release" >&2 echo " --url URL a server with the release's latest and cache/ (HTTP or HTTPS)" >&2 echo " --request what the web UI asked for (${updateDir}/request.json)" >&2 echo " --force also install a release that is not newer" >&2 exit 2 } die() { echo "router-update: $*" >&2; exit 1; } force=0 mode="" arg="" timeout="" while [ $# -gt 0 ]; do case $1 in check) mode=check ;; --force) force=1 ;; --bundle) shift; [ $# -gt 0 ] || usage; mode=bundle arg=$1 ;; --url) shift; [ $# -gt 0 ] || usage; mode=url arg=$1 ;; --git) shift; [ $# -gt 0 ] || usage; mode=git arg=$1 ;; --request) req=${updateDir}/request.json [ -r "$req" ] || die "no request" mode=$(jq -er .mode "$req") arg=$(jq -r '.url // ""' "$req") force=$(jq -r 'if .force then 1 else 0 end' "$req") rm -f "$req" ;; -*) usage ;; *) timeout=$1 ;; esac shift done [ -n "$mode" ] || usage [ "$(id -u)" -eq 0 ] || die "must run as root" config=${cfg.directory} # The release tags of the repository, "TAG REVISION" per line (an # annotated tag counts with the commit it points to). repository() { jq -r '.router.update.repository // empty' "$config/settings.json"; } 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 } if [ "$mode" = check ]; then # Only looks: no lock, so it runs beside an update. repo=$(repository) if [ -z "$repo" ]; then echo "router-update: no repository (router.update.repository): nothing to look at" exit 0 fi tags=$(git_tags "$repo") || die "cannot read the tags of $repo" [ -n "$tags" ] || die "$repo has no release tags (vX.Y.Z)" read -r tag rev <<<"$(tail -n 1 <<<"$tags")" version=''${tag#v} installed=$(jq -r '.version // "unknown"' /etc/router-release) newer=false if [ "$version" != "$installed" ] && [ "$(printf '%s\n%s\n' "$installed" "$version" | sort -V | tail -n 1)" = "$version" ]; then newer=true fi mkdir -p ${updateDir} jq -n --arg repo "$repo" --arg time "$(date -u +%FT%TZ)" --arg installed "$installed" \ --arg tag "$tag" --arg version "$version" --arg rev "$rev" --argjson newer "$newer" \ '{repository: $repo, time: $time, installed: $installed, newest: {tag: $tag, version: $version, rev: $rev}, newer: $newer}' \ > ${updateDir}/check.json.new chmod 0644 ${updateDir}/check.json.new mv ${updateDir}/check.json.new ${updateDir}/check.json if [ "$newer" = true ]; then echo "router-update: $version is available (installed: $installed)" else echo "router-update: up to date ($installed; the repository's newest is $version)" fi exit 0 fi exec 9>/run/router-update.lock flock -n 9 || die "another update is running" # Bundles and servers are signed; a git repository is trusted as it is. trusted="" if [ "$mode" != git ]; then trusted=$(tr '\n' ' ' < /etc/router-update-keys) [ -n "''${trusted// /}" ] || die "this router has no update key" fi staged=${updateDir}/staged case $mode in bundle) rm -rf "$staged" router-webui unbundle "$arg" "$staged" mode=staged ;; esac case $mode in staged) store="file://$staged/cache" latest=$(cat "$staged/latest") ;; url) base=''${arg%/} store="$base/cache" latest=$(curl -fsS --max-time 30 "$base/latest") ;; git) ;; *) usage ;; esac if [ "$mode" = git ]; then repo=$(repository) [ -n "$repo" ] || die "no repository: set router.update.repository" tags=$(git_tags "$repo") || die "cannot read the tags of $repo" if [ -z "$arg" ] || [ "$arg" = latest ]; then found=$(tail -n 1 <<<"$tags") else [[ $arg =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "not a release tag: $arg" found=$(awk -v t="$arg" '$1 == t' <<<"$tags") fi [ -n "$found" ] || die "$repo has no such release tag" read -r tag rev <<<"$found" src="git+$repo?ref=refs/tags/$tag&rev=$rev" echo "router-update: fetching $tag ($rev) from $repo" # (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 "$tag is not a release this updater can build (no config-flake.nix or VERSION)" fi # What a release carries, made from the source: the files that the rest # of the update reads (the flake that points at the source, its version, # its commit time, its settings migrations). release=${updateDir}/git-release rm -rf "$release" mkdir -p "$release/migrations" tr -d '\n' < "$tree/VERSION" > "$release/version" jq -er .locked.lastModified <<<"$meta" | tr -d '\n' > "$release/serial" printf %s "$rev" > "$release/rev" find "$tree/migrations" -name '*.jq' -exec cp {} "$release/migrations/" \; find "$release/migrations" -name '*.jq' | wc -l | tr -d '\n' > "$release/schema" # (jq, not a shell substitution: the address has a & in it.) jq -rRs --arg source "$src" 'gsub("@SOURCE@"; $source)' "$tree/config-flake.nix" > "$release/flake.nix" else release=$(jq -er .release <<<"$latest") || die "the update has no release" [[ $release =~ ^/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._-]+$ ]] || die "not a store path: $release" # Nothing is trusted until every path of the closure is signed by our key. echo "router-update: verifying $release" nix --option trusted-public-keys "$trusted" store verify \ --store "$store" --no-contents --sigs-needed 1 -r "$release" \ || die "the update is not signed with this router's update key" echo "router-update: importing it" nix --option trusted-public-keys "$trusted" copy --from "$store" "$release" rm -rf "$staged" fi new_version=$(cat "$release/version") new_serial=$(cat "$release/serial") cur_version=$(jq -r '.version // "unknown"' /etc/router-release) cur_serial=$(jq -r '.serial // 0' /etc/router-release) echo "router-update: installed $cur_version, update $new_version" if [ "$new_serial" -le "$cur_serial" ] && [ "$force" -ne 1 ]; then die "this release is not newer than the installed one (--force installs it anyway)" fi config=${cfg.directory} [ ! -d ${snapshot} ] || die "an earlier update is not confirmed yet" cp -a "$config" ${snapshot} fail() { echo "router-update: $*; keeping $cur_version" >&2 ${restore}/bin/router-update-restore exit 1 } install -m 0644 "$release/flake.nix" "$config/flake.nix" rm -f "$config/flake.lock" # A nixpkgs that router-upgrade chose stays, rather than the release's. if [ -r "$config/nixpkgs-pin.json" ]; then nix flake lock --override-input nixos-router/nixpkgs "$(jq -r .ref "$config/nixpkgs-pin.json")" "path:$config" \ || fail "pinning the upgraded nixpkgs failed" fi router-migrate-settings "$release" "$config/settings.json" || fail "migrating the settings failed" echo "router-update: building and activating $new_version" 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 else ${restore}/bin/router-update-restore fi die "applying $new_version failed; $cur_version is back" fi if systemctl is-active --quiet router-rollback.timer; then echo "router-update: $new_version is active; confirm it (router-confirm, or in the web UI) or $cur_version comes back" else rm -rf ${snapshot} # nothing changed: nothing to confirm fi ''; }; in { options = { routerSettings.release = lib.mkOption { type = lib.types.nullOr (lib.types.attrsOf lib.types.anything); default = null; description = "Version, serial, revision and settings schema of this nixos-router (`/etc/router-release`)."; }; routerUpdate.publicKeys = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; example = [ "my-update-key-1:AAAA…=" ]; description = '' Public keys (`nix key convert-secret-to-public`) of the keys whose signatures make an update acceptable. ''; }; }; config = { environment.etc."router-release".text = builtins.toJSON ( if config.routerSettings.release == null then { } else config.routerSettings.release ); environment.etc."router-update-keys".text = lib.concatLines keys; environment.systemPackages = [ update restore ]; assertions = lib.optional (config.routerSettings.release != null) { assertion = (settings.version or 0) == config.routerSettings.release.schema; message = '' settings.json is at version ${ toString (settings.version or 0) }, but this release of nixos-router expects version ${toString config.routerSettings.release.schema}. `router-update` migrates the settings; if you edited them by hand, set "version" accordingly. ''; }; # A rolled back or failed update puts the configuration directory back; # a confirmed one keeps the new one. router.rollback.onRollback = "${restore}/bin/router-update-restore"; router.rollback.onConfirm = "rm -rf ${snapshot}"; # Is there a newer release in router.update.repository? Once a day, and when # the web UI asks. It only reads the repository's tag list. systemd.services.router-update-check = { description = "Look for a newer release of nixos-router"; restartIfChanged = false; stopIfChanged = false; path = [ "/run/current-system/sw" ]; serviceConfig = { Type = "oneshot"; ExecStart = "${lib.getExe update} check"; TimeoutStartSec = "5min"; }; }; systemd.timers.router-update-check = { wantedBy = [ "timers.target" ]; timerConfig = { OnCalendar = "daily"; RandomizedDelaySec = "1h"; Persistent = true; }; }; systemd.services.router-update = { description = "Install a router update"; restartIfChanged = false; stopIfChanged = false; path = [ "/run/current-system/sw" ]; serviceConfig = { Type = "oneshot"; ExecStart = "${lib.getExe update} --request"; TimeoutStartSec = "2h"; }; }; # The router's flakes name their inputs in full; nix would otherwise try to # download the global registry (channels.nixos.org) for a git input and # fail, slowly, without the internet. nix.settings.flake-registry = lib.mkDefault ""; # Old generations (and the updates' leftovers) would fill the disk. nix.gc = { automatic = true; dates = "weekly"; options = "--delete-older-than 30d"; }; }; }