diff --git a/SPECS.md b/SPECS.md index c12a3b6..ea13993 100644 --- a/SPECS.md +++ b/SPECS.md @@ -289,12 +289,12 @@ Package upgrades (see above) - **Reset**: go back to the nixpkgs that came with the release (`channel = null` and remove the pin). - **Real package changes in tests**: the upgrade tests use an identical nixpkgs copy, so no real version change is ever exercised. - **Merge the Update and Packages pages, and take releases from git** (decided 2026-11-24, not built). The repository is public, so no key is needed on the router; trusting the git server (TLS and the tag) is enough, so no signatures on this path; the packages come from cache.nixos.org and the small parts of nixos-router are built on the router; gitea has to be reachable to update this way. Plan: - 1. **Done (0.13.2):** one "Updates" page with the parts "Router software" and "Packages", one overlay and one confirmation banner, both logs. Still to do for it: one check, one preview and one apply for both (needs step 3). + 1. **Done (0.13.2):** one "Updates" page with the parts "Router software" and "Packages", one overlay and one confirmation banner, both logs. One check, one preview and one apply for both: see "Unified upgrade" below. 2. **Done (0.13.3, fixed in 0.13.4):** the repository is hardcoded: the module option `routerUpdate.repository` (beside `routerUpdate.publicKeys`; not a `router.*` setting, so it is not in the settings, the options listing or the web UI) defaults to `https://git.stinnesbeck.com/nils/nixos-router`, is baked into `router-update` and written to `/etc/router-update-repository` for the web UI, and the page only names it (no field: a fork or a test sets the option in a module; a moved repository needs a bundle update). `router-update check` (daily timer `router-update-check`, and the page's button) lists the repository's tags with `git ls-remote`, takes the newest `vX.Y.Z` (other tags are ignored) and writes `update/check.json` (repository, time, installed, newest tag/version/revision, newer). The Overview and the Updates page show it while it is about this repository and the installed version. 3. **Done (0.13.3), without a preview:** `router-update --git TAG|latest` (the web UI's "Install"): `nix flake prefetch` of `git+?ref=refs/tags/&rev=`, then the steps of a bundle update from the serial guard on (snapshot, flake, nixpkgs pin, migration, `router-apply` with commit-confirm, rollback). The flake is the source's `config-flake.nix` with `@SOURCE@` replaced by that address, so `flake.lock` and `flake.nix` agree and nothing moves by itself (this file is a contract with every updater already installed: change it only compatibly). The release data (version, serial = the commit's time, schema = the number of `migrations/*.jq`) is read from the fetched source. No signature is checked. Still to do: preview (package changes, download and builds of both inputs), and the nixpkgs-pin interplay for a pin chosen later. 4. **Tag: done (0.13.5).** A release is a tag `vX.Y.Z` on the release commit: `nix run .#release` (which still writes the bundle for the installer and offline routers) ends by creating the annotated tag, locally (push it with the branch; `--no-tag` skips it). It refuses when HEAD's `VERSION` is another version or the tag is on another commit, does nothing outside a git checkout (the VM tests), and tags last so a failed release leaves no tag. Still to do: refuse a `flake.lock` whose nixpkgs is not a channel revision (`git-revision`), so cache.nixos.org has its packages. 5. **Done:** the `update` VM test serves a repository from the builder (`common.gitServer`: `git http-backend` over HTTP) and covers the check, tags that are no releases, refused tags, install through the web UI with migration, confirm, the rebuild without the server, and "not newer". - Bundles and `--url` stay (offline, installer, gitea down). + 6. **Unified upgrade (decided 2026-11-26).** nixos-router is a flake input like nixpkgs, so it is part of `router-upgrade`, not a separate update: `router-update check`, `router-update --git`, the unit `router-update-check` and the page's "Releases from git" are gone (steps 2 and 3 above describe where it started). `router-upgrade check` reads the channel's newest nixpkgs revision *and* the repository's newest tag (a repository that cannot be read is a warning; with no channel the packages are skipped) and writes both to `upgrade/check.json` (`router: {repository, installed, newest, newer}`, `packagesUpToDate`, `upToDate` = both); the daily timer (`router-upgrade-notice`) runs `router-upgrade daily` and feeds the Overview notices. `preview` fetches the tag, builds what a release carries (version, serial, schema, migrations, and the flake from `config-flake.nix`), puts the new flake and the migrated settings into a copy of the configuration, locks it (the nixpkgs override as before; without a channel an earlier pin stays), and writes the usual package diff to `preview.json` plus `router: {from, to, tag, rev}`; the page shows one table with the nixos-router row highlighted, and one "Upgrade" button. `apply` refuses when `flake.nix` (or, with a new router, `settings.json`) changed since the preview, and otherwise snapshots, copies flake, migrated settings and lock, writes the pin only when a channel override was used, and runs `router-apply` with commit-confirm as before. The page has no "Update server" any more (it was a setting nobody needs after the hardcoded repository); `router-update` keeps `--url`, `--bundle` and uploads (offline, installer, gitea down), and the page keeps "Install a bundle". Tested in the `update` VM test (check, ignored non-release tags, preview with the router row, apply, confirm, rebuild without the server) and the Go tests. Web UI polish (list of 2026-11-24) - Folds inside panels (Packages "What is built here", WireGuard) may jump like the certificate log did. diff --git a/config-flake.nix b/config-flake.nix index db775a0..e93b6a0 100644 --- a/config-flake.nix +++ b/config-flake.nix @@ -1,6 +1,6 @@ # The flake.nix of an installed router's configuration directory when its # nixos-router comes from a git repository (routerUpdate.repository). -# `router-update --git` writes it with @SOURCE@ replaced by the address of the +# `router-upgrade` writes it with @SOURCE@ replaced by the address of the # release it installs (git+URL?ref=refs/tags/vX.Y.Z&rev=COMMIT), so the lock # file and this file always agree and nothing moves to a newer commit by itself. # diff --git a/modules/settings/update.nix b/modules/settings/update.nix index 74d65a5..e42b8a9 100644 --- a/modules/settings/update.nix +++ b/modules/settings/update.nix @@ -55,16 +55,14 @@ let migrate pkgs.coreutils pkgs.curl - pkgs.git - pkgs.gawk pkgs.jq pkgs.util-linux ]; text = '' + # (A release from the git repository is not installed here but by + # router-upgrade, with the packages: this is for signed bundles.) usage() { - echo "usage: router-update check | [--force] (--request | --bundle FILE | --url URL | --git TAG|latest) [timeout]" >&2 - echo " check the newest release tag of the repository, against the installed version" >&2 - echo " --git TAG build the release from a tag (vX.Y.Z, or latest) of the repository" >&2 + echo "usage: router-update [--force] (--request | --bundle FILE | --url URL) [timeout]" >&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 @@ -76,11 +74,9 @@ let 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" @@ -94,60 +90,12 @@ let 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() { echo ${lib.escapeShellArg (toString config.routerUpdate.repository)}; } - 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: this router has no 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 + trusted=$(tr '\n' ' ' < /etc/router-update-keys) + [ -n "''${trusted// /}" ] || die "this router has no update key" staged=${updateDir}/staged case $mode in @@ -164,56 +112,20 @@ let 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 "this router has no repository to update from" - 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" + 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 + # 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" new_version=$(cat "$release/version") new_serial=$(cat "$release/serial") @@ -274,12 +186,11 @@ in example = "https://git.example.org/me/nixos-router"; description = '' The public git repository of nixos-router whose tags `vX.Y.Z` are - releases. `router-update check` (daily, and in the web UI) looks for a - newer tag, and `router-update --git` builds the router from it, like an - update from a bundle. The repository is trusted (TLS and the tag), - nothing is signed on this path. It belongs to the installed version, not - to the settings: a fork or a test sets it in a module. null: updates - come from bundles and update servers only. + releases. `router-upgrade` (daily, and in the web UI) looks for a newer + tag and, with the packages, locks the configuration flake to it. The + repository is trusted (TLS and the tag), nothing is signed on this path. + It belongs to the installed version, not to the settings: a fork or a + test sets it in a module. null: updates come from bundles only. ''; }; routerUpdate.publicKeys = lib.mkOption { @@ -321,28 +232,6 @@ in router.rollback.onRollback = "${restore}/bin/router-update-restore"; router.rollback.onConfirm = "rm -rf ${snapshot}"; - # Is there a newer release in the 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; diff --git a/modules/settings/upgrade.nix b/modules/settings/upgrade.nix index 1a511da..2c8b3bf 100644 --- a/modules/settings/upgrade.nix +++ b/modules/settings/upgrade.nix @@ -30,23 +30,29 @@ let 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 | releases | preview [--force] [--downgrade] | download | apply [timeout] | --request" >&2 - echo " check the newest revision of router.update.channel, against the running one" >&2 - echo " releases which stable NixOS releases the channel server has (a timer runs it daily)" >&2 - echo " preview the packages that change and the size of the download (nothing is fetched)" >&2 + 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 @@ -78,12 +84,15 @@ let 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") - [ -n "$channel" ] || die "no channel: set router.update.channel (unstable, or a release like 26.05)" - if [ "$channel" = unstable ]; then branch=nixos-unstable; else branch="nixos-$channel"; fi + 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) @@ -121,20 +130,64 @@ let 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 - newest=$(newest_rev) - if [ "$newest" = "$running_rev" ]; then same=true; else same=false; fi + 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 upToDate "$same" \ + --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}, upToDate: $upToDate}' > ${dir}/check.json.new + newest: {rev: $newest}, packagesUpToDate: $packagesUpToDate, upToDate: $upToDate, router: $router}' > ${dir}/check.json.new mv ${dir}/check.json.new ${dir}/check.json - echo "channel $channel ($branch)" - echo " running $running_version" - echo " newest $(short "$newest")" - if [ "$same" = true ]; then echo "up to date"; else echo "a newer revision is available"; fi + 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. @@ -171,24 +224,71 @@ let esac done check - rm -rf ${dir}/preview.json ${dir}/flake ${dir}/result + 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 + 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 - ref="${up.nixpkgsRef}" - ref=''${ref//%rev%/$newest} - echo "router-upgrade: locking nixpkgs to $(short "$newest")" - nix flake lock --override-input nixos-router/nixpkgs "$ref" "path:${dir}/flake" - 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 + # 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" @@ -224,13 +324,19 @@ let 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 - release_version=$(jq -r '.version // ""' /etc/router-release 2>/dev/null || true) - jq -n --arg channel "$channel" --arg release "$release_version" --arg rev "$newest" --arg ref "$pin" --arg version "$new_version" \ - --arg time "$(date -u +%FT%TZ)" --arg download "$download" --argjson builds "$builds" \ + # 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, changes: $changes[0]}' > ${dir}/preview.json + 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" } @@ -251,18 +357,31 @@ let 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}/flake/flake.nix \ + 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" - jq '{channel, rev, ref}' ${dir}/preview.json > "$config/nixpkgs-pin.json" + # 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 $(jq -r .version ${dir}/preview.json)" + 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. @@ -271,7 +390,7 @@ let fi fail "the upgrade failed; the previous system is back" fi - rm -rf ${dir}/preview.json ${dir}/flake ${dir}/result + 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 @@ -281,6 +400,8 @@ let 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 ;; @@ -310,15 +431,16 @@ in # 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). - # Which stable releases exist, once a day: the web UI says when a newer one than - # the followed channel appears. It only asks the channel server and writes a small - # file, so it is a unit of its own that never holds up an upgrade. + # 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 new NixOS releases"; + description = "Look for newer versions of nixos-router and NixOS"; path = [ "/run/current-system/sw" ]; serviceConfig = { Type = "oneshot"; - ExecStart = "${lib.getExe upgrade} releases"; + ExecStart = "${lib.getExe upgrade} daily"; TimeoutStartSec = "5min"; }; }; diff --git a/pkgs/router-webui/gitupdate.go b/pkgs/router-webui/gitupdate.go index dfc5115..91986eb 100644 --- a/pkgs/router-webui/gitupdate.go +++ b/pkgs/router-webui/gitupdate.go @@ -1,35 +1,16 @@ package main import ( - "net/http" - "net/url" "os" "path/filepath" - "regexp" "strings" ) -// Updates from a git repository: router-update check looks at the -// repository's release tags (vX.Y.Z) once a day and when the page asks, and -// writes what it found to update/check.json; installing builds the router -// from a tag, like an update from a bundle. The repository is part of the -// installed version (routerUpdate.repository, written to -// /etc/router-update-repository), not something the page sets. - -var releaseTagRe = regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`) - -// GitCheck is update/check.json: the newest release tag of the repository. -type GitCheck struct { - Repository string `json:"repository"` - Time string `json:"time"` - Installed string `json:"installed"` - Newest struct { - Tag string `json:"tag"` - Version string `json:"version"` - Rev string `json:"rev"` - } `json:"newest"` - Newer bool `json:"newer"` -} +// nixos-router is an input of the configuration flake like nixpkgs, and comes +// from a git repository whose tags vX.Y.Z are releases. Looking for it and +// locking it is router-upgrade's, with the packages (check.json has both). The +// repository is part of the installed version (routerUpdate.repository, +// written to /etc/router-update-repository), not something the page sets. // repository is where releases come from ("" if the router has none). func (s System) repository() string { @@ -41,60 +22,15 @@ func (s System) repository() string { return strings.TrimSpace(string(data)) } -const gitCheckUnit = "router-update-check.service" - -// gitCheck is what the last check found, if it is still about this repository -// and this installed version. -func (a *app) gitCheck() *GitCheck { - var c GitCheck - repository := a.sys.repository() - if repository == "" || !readUpgradeFile(filepath.Join(a.sys.updateDir(), "check.json"), &c) { - return nil - } - if c.Repository != repository || c.Installed != a.sys.installedRelease().Version || c.Newest.Tag == "" { - return nil - } - return &c -} - -// newRouterVersion is the version of a release that is out and not installed, -// for the Overview ("" if there is none or nothing was checked). +// newRouterVersion is the version of a release of nixos-router that is out and +// not installed, for the Overview ("" if there is none or nothing was checked). func (a *app) newRouterVersion() string { - if c := a.gitCheck(); c != nil && c.Newer { - return c.Newest.Version + var c UpgradeCheck + if !readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) { + return "" + } + if r := c.Router; r != nil && r.Newer && r.Installed == a.sys.installedRelease().Version { + return r.Newest.Version } return "" } - -func (a *app) updateGitCheck(w http.ResponseWriter, r *http.Request, _ session) { - if a.sys.repository() == "" { - a.updateBack(w, r, "This router has no repository to look at.") - return - } - if err := startUnit(gitCheckUnit); err != nil { - a.updateBack(w, r, "Could not look: "+err.Error()) - return - } - a.updateBack(w, r, "Looking at the repository.") -} - -func (a *app) updateGitInstall(w http.ResponseWriter, r *http.Request, _ session) { - if a.busy() { - a.updateBack(w, r, "Another change is in progress or waiting for confirmation.") - return - } - tag := r.PostFormValue("tag") - if tag != "" && !releaseTagRe.MatchString(tag) { - a.updateBack(w, r, "Not a release tag: "+url.QueryEscape(tag)) - return - } - if a.sys.repository() == "" { - a.updateBack(w, r, "This router has no repository to update from.") - return - } - if err := a.sys.requestUpdate("git", tag, r.PostFormValue("force") == "on"); err != nil { - a.updateBack(w, r, "Could not start the update: "+err.Error()) - return - } - a.updateBack(w, r, "Updating.") -} diff --git a/pkgs/router-webui/gitupdate_test.go b/pkgs/router-webui/gitupdate_test.go index 3af9dd4..56ae921 100644 --- a/pkgs/router-webui/gitupdate_test.go +++ b/pkgs/router-webui/gitupdate_test.go @@ -11,96 +11,40 @@ import ( const testRepository = "https://git.example.org/me/nixos-router" -// While the look at the repository runs, the page is covered by the same kind -// of box as an update, and keeps asking for itself until it is done. -func TestLookingAtTheRepositoryShowsABox(t *testing.T) { - a, sys := newTestApp(t) - sys.RepositoryFile = filepath.Join(t.TempDir(), "router-update-repository") - os.WriteFile(sys.RepositoryFile, []byte(testRepository), 0o644) - a.sys = sys - orig := unitProperty - state := "inactive" - unitProperty = func(unit, prop string) string { - if unit == gitCheckUnit && prop == "ActiveState" { - return state - } - return "" - } - defer func() { unitProperty = orig }() - h := a.routes() - cookie := login(t, h) - - body := do(h, "GET", "/update", nil, cookie).Body.String() - if strings.Contains(body, "Looking at the repository…") || strings.Contains(body, "data-live") { - t.Fatalf("a box with nothing running:\n%s", body) - } - if !strings.Contains(body, "Look for a newer release") { - t.Fatalf("no button:\n%s", body) - } - - state = "activating" - body = do(h, "GET", "/update", nil, cookie).Body.String() - if !strings.Contains(body, "Looking at the repository…") || !strings.Contains(body, `class="upload-overlay"`) || !strings.Contains(body, "data-live") { - t.Fatalf("no box while looking:\n%s", body) - } - if !strings.Contains(body, testRepository) { - t.Fatalf("the box does not say where it looks:\n%s", body) - } -} - -func TestUpdatesFromGit(t *testing.T) { +// One check, one preview: the page shows nixos-router and the packages +// together, and the preview marks the router's own row. +func TestUpgradeShowsRouterAndPackages(t *testing.T) { a, sys := newTestApp(t) dir := t.TempDir() sys.ReleaseFile = filepath.Join(dir, "router-release") sys.RepositoryFile = filepath.Join(dir, "router-update-repository") os.WriteFile(sys.ReleaseFile, []byte(`{"version":"1.0.0","serial":1000}`), 0o600) + os.WriteFile(sys.RepositoryFile, []byte(testRepository+"\n"), 0o644) a.sys = sys - orig := startUnit - var started []string - startUnit = func(unit string) error { started = append(started, unit); return nil } - defer func() { startUnit = orig }() h := a.routes() cookie := login(t, h) - token := csrfFrom(t, do(h, "GET", "/update", nil, cookie).Body.String()) - post := func(path string, form url.Values) string { - form.Set("csrf", token) - return do(h, "POST", path, form, cookie).Header().Get("Location") - } - // A router without a repository has nothing to look at. - if loc := post("/update/gitcheck", url.Values{}); !strings.Contains(loc, "no+repository") || len(started) != 0 { - t.Fatalf("a check without a repository: %q %v", loc, started) + body := do(h, "GET", "/update", nil, cookie).Body.String() + for _, want := range []string{testRepository, "Check for upgrades"} { + if !strings.Contains(body, want) { + t.Fatalf("the page lacks %q:\n%s", want, body) + } } - if loc := post("/update/gitinstall", url.Values{"tag": {"v1.1.0"}}); !strings.Contains(loc, "no+repository") { - t.Fatalf("an install without a repository: %q", loc) - } - if rec := do(h, "POST", "/update/repository", url.Values{"csrf": {token}, "repository": {"https://evil.example.org/r"}}, cookie); rec.Code != 404 && rec.Code != 405 { - t.Fatalf("the repository can be set from the page: %d", rec.Code) - } - if body := do(h, "GET", "/update", nil, cookie).Body.String(); strings.Contains(body, `name="repository"`) { + if strings.Contains(body, `name="repository"`) { t.Fatalf("the page has a field for the repository:\n%s", body) } - - // The repository is the installed version's; the page names it. - os.WriteFile(sys.RepositoryFile, []byte(testRepository+"\n"), 0o644) - if body := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(body, testRepository) || !strings.Contains(body, "Not looked yet") { - t.Fatalf("the page does not say which repository:\n%s", body) + if rec := do(h, "POST", "/update/repository", nil, cookie); rec.Code != 404 && rec.Code != 405 { + t.Fatalf("the repository can be set from the page: %d", rec.Code) } - // Looking starts the unit; what it found is shown while it is about this repository and version. - post("/update/gitcheck", url.Values{}) - if len(started) != 1 || started[0] != "router-update-check.service" { - t.Fatalf("started %v", started) - } + token := csrfFrom(t, body) + do(h, "POST", "/upgrade/channel", url.Values{"csrf": {token}, "channel": {"26.05"}}, cookie) write := func(repo, installed string, newer bool) { - os.MkdirAll(sys.updateDir(), 0o755) - data, _ := json.Marshal(map[string]any{"repository": repo, "time": "2026-11-26T08:00:00Z", "installed": installed, - "newest": map[string]string{"tag": "v1.1.0", "version": "1.1.0", "rev": "0123456789abcdef0123456789abcdef01234567"}, "newer": newer}) - os.WriteFile(filepath.Join(sys.updateDir(), "check.json"), data, 0o644) - } - write("https://git.example.org/someone-else/nixos-router", "1.0.0", true) - if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") { - t.Fatalf("a notice from another repository:\n%s", body) + os.MkdirAll(sys.upgradeDir(), 0o755) + data, _ := json.Marshal(map[string]any{"channel": "26.05", "running": map[string]string{"version": a.sys.runningVersion()}, "time": "2026-11-26T08:00:00Z", "upToDate": !newer, "packagesUpToDate": true, + "router": map[string]any{"repository": repo, "installed": installed, "newer": newer, + "newest": map[string]string{"tag": "v1.1.0", "version": "1.1.0", "rev": "0123456789abcdef0123456789abcdef01234567"}}}) + os.WriteFile(filepath.Join(sys.upgradeDir(), "check.json"), data, 0o644) } write(testRepository, "0.9.0", true) if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") { @@ -117,22 +61,15 @@ func TestUpdatesFromGit(t *testing.T) { t.Fatalf("a notice when up to date") } - // Installing asks the update unit to build the tag, and only a release tag. - if loc := post("/update/gitinstall", url.Values{"tag": {"v1.1.0; reboot"}}); !strings.Contains(loc, "Not+a+release+tag") { - t.Fatalf("a bad tag: %q", loc) - } - started = nil - post("/update/gitinstall", url.Values{"tag": {"v1.1.0"}, "force": {"on"}}) - var req struct { - Mode string `json:"mode"` - URL string `json:"url"` - Force bool `json:"force"` - } - data, _ := os.ReadFile(filepath.Join(sys.updateDir(), "request.json")) - if err := json.Unmarshal(data, &req); err != nil || req.Mode != "git" || req.URL != "v1.1.0" || !req.Force { - t.Fatalf("request: %s", data) - } - if len(started) != 1 || started[0] != "router-update.service" { - t.Fatalf("started %v", started) + // A preview that includes the router: one table, the router's row marked. + preview, _ := json.Marshal(map[string]any{"channel": "26.05", "release": "1.0.0", "rev": "", "version": "26.05", "time": "t", + "router": map[string]string{"from": "1.0.0", "to": "1.1.0", "tag": "v1.1.0", "rev": "abc"}, + "changes": []map[string]string{{"name": "curl", "from": "8.0", "to": "8.1"}}}) + os.WriteFile(filepath.Join(sys.upgradeDir(), "preview.json"), preview, 0o644) + body = do(h, "GET", "/update", nil, cookie).Body.String() + for _, want := range []string{`class="highlight"`, "nixos-router", "curl", "Upgrade nixos-router to 1.1.0 and"} { + if !strings.Contains(body, want) { + t.Fatalf("the preview lacks %q:\n%s", want, body) + } } } diff --git a/pkgs/router-webui/main.go b/pkgs/router-webui/main.go index 54fd3f2..28847d5 100644 --- a/pkgs/router-webui/main.go +++ b/pkgs/router-webui/main.go @@ -338,11 +338,6 @@ func (a *app) routes() http.Handler { mux.HandleFunc("POST /prefs", a.auth(a.savePrefs)) mux.HandleFunc("POST /backup", a.auth(a.backup)) mux.HandleFunc("GET /update", a.auth(a.updatePage)) - mux.HandleFunc("POST /update/url", a.auth(a.updateSaveURL)) - mux.HandleFunc("POST /update/check", a.auth(a.updateCheck)) - mux.HandleFunc("POST /update/install", a.auth(a.updateInstall)) - mux.HandleFunc("POST /update/gitcheck", a.auth(a.updateGitCheck)) - mux.HandleFunc("POST /update/gitinstall", a.auth(a.updateGitInstall)) mux.HandleFunc("POST /update/upload", a.updateUpload) mux.HandleFunc("GET /upgrade", a.auth(upgradeRedirect)) mux.HandleFunc("POST /upgrade/channel", a.auth(a.upgradeChannel)) diff --git a/pkgs/router-webui/static/style.css b/pkgs/router-webui/static/style.css index 36e4530..f41db96 100644 --- a/pkgs/router-webui/static/style.css +++ b/pkgs/router-webui/static/style.css @@ -152,6 +152,7 @@ table { border-collapse: collapse; } th { text-align: left; font-size: .82rem; font-weight: 600; color: var(--muted); padding: 0 .45rem .35rem; white-space: nowrap; border-bottom: 1px solid var(--line); } td { padding: .3rem .45rem; } table tr:nth-child(even) td { background: var(--zebra); } +table tr.highlight td { font-weight: 600; background: var(--zebra); border-left: 3px solid var(--tick); } pre.log { background: var(--code); padding: .85rem 1rem; border-radius: var(--radius); overflow-x: auto; font-size: 12.5px; max-height: 30rem; } code { font-size: .88em; overflow-wrap: anywhere; background: var(--code); padding: .1em .35em; border-radius: 3px; } pre code { background: none; padding: 0; } diff --git a/pkgs/router-webui/templates/update.html b/pkgs/router-webui/templates/update.html index d9de95d..16c8eb4 100644 --- a/pkgs/router-webui/templates/update.html +++ b/pkgs/router-webui/templates/update.html @@ -22,101 +22,12 @@

The page reloads when it is done. The web UI restarts when an upgrade is switched on, and you log in again.

-{{else if $u.GitRun.Running}} - {{else if $u.Pending}}

Waiting for confirmation

A new system is active and not confirmed yet. Confirm it on the Overview, or the router goes back to the previous one.

{{end}} -

Router software

- -
-

Installed

-
-
Version
{{or $u.Installed.Version "unknown"}}{{if $u.Installed.Rev}} {{$u.Installed.Rev}}{{end}}
-
Settings schema
{{$u.Installed.Schema}}
-
-
- -
-

Releases from git

-

The router looks once a day at the release tags (vX.Y.Z) of {{or $u.Repository "no repository"}} - and says here and on the Overview when a newer one exists. Installing builds it on the router, like a bundle: the - settings are kept (and migrated), and the new version must be confirmed afterwards, or the router goes back. The - repository is trusted as it is: nothing is signed on this path.

- {{if $u.Repository}} -
- - -
- {{if and $u.GitRun.Result (ne $u.GitRun.Result "success")}}

The last look failed:

{{$u.GitRun.Log}}
{{end}} - {{with $u.Git}} -
-
Installed
{{.Installed}}
-
Newest
{{.Newest.Version}} {{printf "%.7s" .Newest.Rev}}, looked {{.Time}}
-
-
- - - {{if .Newer}}

A newer release is available.

- {{else}}

Up to date.

{{end}} - {{if .Newer}}Install {{.Newest.Version}}{{else}}Install {{.Newest.Version}} again{{end}} - - {{else}} -

Not looked yet.

- {{end}} - {{end}} -
- -
-

Install a bundle

-

A .bundle file made with nix run .#release. It is installed only if it is signed with - this router's update key. The settings are kept (and migrated if the new version needs it); the new version - must be confirmed afterwards, or the router goes back.

-
-

-

-
-
- -
-

Update server

-
- - - -
- {{if $u.URL}} -
- - -
- {{end}} - {{if $u.OfferErr}}

Could not check: {{$u.OfferErr}}

{{end}} - {{with $u.Offer}} -

{{if .Newer}}Available: {{.Version}}{{if .Rev}} {{.Rev}}{{end}}.{{else}}Nothing newer: the server has {{.Version}}.{{end}}

-
- - {{if not .Newer}}

{{end}} - -
- {{end}} -

The server only has to serve static files: the latest file and cache/ that - nix run .#release writes. The data is signed, so plain HTTP works too.

-
- -

Packages

- {{with $g.NewerRelease}}

NixOS {{.}} is out

@@ -130,14 +41,16 @@
{{end}} -
-

Channel

-

Upgrades the kernel and all programs (NixOS) without a new release of nixos-router. Nothing is downloaded until - you ask for it, and an upgrade is activated like a settings change: unless you confirm it in time, the router - goes back to the previous system.

+
+

Installed

-
Running
{{or $g.Version "unknown"}}
+
nixos-router
{{or $g.Router.Version "unknown"}}{{if $g.Router.Rev}} {{printf "%.7s" $g.Router.Rev}}{{end}}
+
Settings schema
{{$g.Router.Schema}}
+
NixOS
{{or $g.Version "unknown"}}
+

An upgrade brings the newest nixos-router{{if $g.Repository}} (from {{$g.Repository}}){{end}} and the packages + (the kernel and all programs) of the channel you follow. Nothing is downloaded until you ask for it, and an upgrade is + activated like a settings change: unless you confirm it in time, the router goes back to the previous system.

-{{if $g.Channel}} +{{if or $g.Channel $g.Repository}}

Check

@@ -162,11 +75,11 @@
{{with $g.Check}}
-
Channel
{{.Branch}}
-
Running
{{.Running.Version}}
-
Newest
{{printf "%.7s" .Newest.Rev}} checked {{.Time}}
+ {{with .Router}}
nixos-router
{{.Installed}}{{if .Newer}} → {{.Newest.Version}}{{else}} (the newest){{end}}
{{end}} + {{if .Channel}}
Packages
{{.Channel}}: {{printf "%.7s" .Newest.Rev}}{{if .PackagesUpToDate}} (what runs){{else}} newer than the running {{printf "%.7s" .Running.Rev}}{{end}}
{{end}} +
Checked
{{.Time}}
- {{if .UpToDate}}

Up to date.

{{else}}

A newer revision is available.

{{end}} + {{if .UpToDate}}

Up to date.

{{else}}

A newer version is available.

{{end}} {{end}}
@@ -178,15 +91,19 @@ -

Works it out from the new revision's description: no package is downloaded.

+

Works it out from the new versions' descriptions: no package is downloaded.

{{with $g.Preview}} -

{{$g.Version}} → {{.Version}} {{printf "%.7s" .Rev}}, previewed {{.Time}}

- {{if .Changes}} +

{{$g.Version}} → {{.Version}} {{if .Rev}}{{printf "%.7s" .Rev}}, {{end}}previewed {{.Time}}

+ {{if or .Router .Changes}} - {{range .Changes}}{{end}} + + {{with .Router}}{{end}} + {{range .Changes}}{{end}} +
PackageNowNew
{{.Name}}{{.From}}→{{.To}}
nixos-router{{.From}}→{{.To}}
{{.Name}}{{.From}}→{{.To}}
{{else}}

No package changes.

{{end}} + {{if .Router}}

The highlighted row is the router software itself: this upgrade installs it too.

{{end}}

The list shows the versions of programs the router runs; a program that is only rebuilt does not appear.

To download
{{or .Download "nothing, or the package cache cannot be reached"}}
@@ -208,7 +125,7 @@
- Upgrade to {{.Version}} + Upgrade{{with .Router}} nixos-router to {{.To}} and{{end}} to {{.Version}}

Downloading first lets you start the upgrade later without needing the internet. Upgrading @@ -219,16 +136,27 @@

Choose a channel to look for upgrades.

{{end}} +
+

Install a bundle

+

For a router without a route to the repository, or when it is down: a .bundle file made with + nix run .#release. It is installed only if it is signed with this router's update key. The settings are kept + (and migrated if the new version needs it); the new version must be confirmed afterwards, or the router goes back.

+
+

+

+
+
+ {{if and $u.Status.Log (not $u.Status.Running)}}
-

Last update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}

+

Last bundle update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}

{{$u.Status.Log}}
{{end}} {{if and $g.Run.Log (not $g.Run.Running)}}
-

Last package run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}

+

Last upgrade run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}

{{$g.Run.Log}}
{{end}} diff --git a/pkgs/router-webui/update.go b/pkgs/router-webui/update.go index 60e645b..df53e4c 100644 --- a/pkgs/router-webui/update.go +++ b/pkgs/router-webui/update.go @@ -14,7 +14,6 @@ import ( "path/filepath" "regexp" "strings" - "time" ) // Updates arrive as a tar of a signed binary cache (see lib.mkRelease): @@ -142,67 +141,10 @@ func (s System) installedRelease() Release { return r } -func (s System) updateDir() string { return filepath.Join(s.StateDir, "update") } -func (s System) updateURLPath() string { return filepath.Join(s.StateDir, "webui", "update.json") } +func (s System) updateDir() string { return filepath.Join(s.StateDir, "update") } -func (s System) updateURL() string { - var v struct { - URL string `json:"url"` - } - if data, err := os.ReadFile(s.updateURLPath()); err == nil { - json.Unmarshal(data, &v) - } - return v.URL -} - -func (s System) saveUpdateURL(u string) error { - data, _ := json.Marshal(struct { - URL string `json:"url"` - }{u}) - if err := os.MkdirAll(filepath.Dir(s.updateURLPath()), 0o700); err != nil { - return err - } - return writeFileAtomic(s.updateURLPath(), data, 0o600) -} - -// parseUpdateURL accepts the base of an update server: http or https, no -// credentials, no query. The data is signed, so plain HTTP is no risk to the -// router; it only lets an attacker withhold updates. -func parseUpdateURL(v string) (string, error) { - v = strings.TrimRight(strings.TrimSpace(v), "/") - u, err := url.Parse(v) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || - u.RawQuery != "" || u.Fragment != "" { - return "", errors.New("an http:// or https:// address without credentials") - } - return v, nil -} - -// Available is what the update server offers. -type Available struct { - Release - Newer bool -} - -func (s System) checkUpdate(base string) (Available, error) { - client := &http.Client{Timeout: 15 * time.Second} - resp, err := client.Get(base + "/latest") - if err != nil { - return Available{}, err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return Available{}, fmt.Errorf("the server answered %s", resp.Status) - } - var a Available - if err := json.NewDecoder(io.LimitReader(resp.Body, maxLatest)).Decode(&a); err != nil || a.Version == "" { - return Available{}, errors.New("the server's latest file is not an update description") - } - a.Newer = a.Serial > s.installedRelease().Serial - return a, nil -} - -// request asks the router-update unit to install; it reads this file. +// requestUpdate asks the router-update unit to install what is staged; it +// reads this file. (Updates from the repository are router-upgrade's.) func (s System) requestUpdate(mode, url string, force bool) error { data, _ := json.Marshal(map[string]any{"mode": mode, "url": url, "force": force}) if err := os.MkdirAll(s.updateDir(), 0o700); err != nil { @@ -251,7 +193,6 @@ func updateProgress(log string) (int, string) { pct int what string }{ - {"router-update: fetching", 10, "Fetching the release from the repository"}, {"router-update: verifying", 10, "Verifying the signature"}, {"router-update: importing", 30, "Importing the release"}, {"router-update: installed", 50, "Checking the version"}, @@ -272,14 +213,7 @@ type updateData struct { Progress int // percent, while updating Step string // what it does now Status UpdateStatus - URL string - Offer *Available - OfferErr string Pending bool // an update waits for confirmation - - Repository string // routerUpdate.repository - Git *GitCheck // what the last look at it found - GitRun UpdateStatus // the look that is running or ran last } func (a *app) updateData() updateData { @@ -287,12 +221,8 @@ func (a *app) updateData() updateData { d := updateData{ Installed: a.sys.installedRelease(), Status: a.sys.UpdateStatus(), - URL: a.sys.updateURL(), Pending: st.RollbackIn > 0, - GitRun: unitRun(gitCheckUnit), } - d.Repository = a.sys.repository() - d.Git = a.gitCheck() d.Progress, d.Step = updateProgress(d.Status.Log) return d } @@ -311,7 +241,7 @@ func (a *app) updatesData() updatesData { func (a *app) updatePage(w http.ResponseWriter, r *http.Request, sess session) { d := a.updatesData() p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true, Data: d, Flash: r.URL.Query().Get("msg")} - if d.Update.Status.Running || d.Upgrade.Run.Running || d.Update.GitRun.Running { + if d.Update.Status.Running || d.Upgrade.Run.Running { p.Live = 3 } a.render(w, "update", p) @@ -331,56 +261,6 @@ func (a *app) busy() bool { return st.Applying || st.ConfirmRunning || st.RollbackIn > 0 || a.sys.UpdateStatus().Running || a.sys.UpgradeStatus().Running } -func (a *app) updateSaveURL(w http.ResponseWriter, r *http.Request, _ session) { - v := strings.TrimSpace(r.PostFormValue("url")) - if v != "" { - var err error - if v, err = parseUpdateURL(v); err != nil { - a.updateBack(w, r, "Not saved: "+err.Error()) - return - } - } - if err := a.sys.saveUpdateURL(v); err != nil { - a.updateBack(w, r, "Not saved: "+err.Error()) - return - } - a.updateBack(w, r, "Saved.") -} - -func (a *app) updateCheck(w http.ResponseWriter, r *http.Request, sess session) { - d := a.updatesData() - p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true} - if d.Update.URL == "" { - a.updateBack(w, r, "Set the update server first.") - return - } - offer, err := a.sys.checkUpdate(d.Update.URL) - if err != nil { - d.Update.OfferErr = err.Error() - } else { - d.Update.Offer = &offer - } - p.Data = d - a.render(w, "update", p) -} - -func (a *app) updateInstall(w http.ResponseWriter, r *http.Request, _ session) { - if a.busy() { - a.updateBack(w, r, "Another change is in progress or waiting for confirmation.") - return - } - u := a.sys.updateURL() - if u == "" { - a.updateBack(w, r, "Set the update server first.") - return - } - if err := a.sys.requestUpdate("url", u, r.PostFormValue("force") == "on"); err != nil { - a.updateBack(w, r, "Could not start the update: "+err.Error()) - return - } - a.updateBack(w, r, "Updating.") -} - // updateUpload takes a bundle as multipart/form-data and streams it into the // staging directory; a bundle is hundreds of megabytes. The CSRF token is in // the query string, since the body must not be read before it is checked. diff --git a/pkgs/router-webui/update_test.go b/pkgs/router-webui/update_test.go index 71a9e40..9499ae7 100644 --- a/pkgs/router-webui/update_test.go +++ b/pkgs/router-webui/update_test.go @@ -116,53 +116,6 @@ func TestUnbundleRefusesHostileBundles(t *testing.T) { } } -func TestParseUpdateURL(t *testing.T) { - for in, want := range map[string]string{ - "https://updates.example.com/router/": "https://updates.example.com/router", - " http://192.168.1.5:8000 ": "http://192.168.1.5:8000", - } { - if got, err := parseUpdateURL(in); err != nil || got != want { - t.Errorf("%q: %q %v", in, got, err) - } - } - for _, in := range []string{"", "ftp://x/y", "file:///etc", "https://user:pw@host/x", "https://host/x?y=1", "updates.example.com", "https://"} { - if _, err := parseUpdateURL(in); err == nil { - t.Errorf("%q accepted", in) - } - } -} - -func TestCheckUpdate(t *testing.T) { - a, sys := newTestApp(t) - _ = a - sys.ReleaseFile = filepath.Join(t.TempDir(), "router-release") - os.WriteFile(sys.ReleaseFile, []byte(`{"version":"0.2.0","serial":1000,"schema":0}`), 0o600) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/new/latest": - w.Write([]byte(`{"release":"/nix/store/x","version":"0.3.0","serial":2000,"schema":1}`)) - case "/same/latest": - w.Write([]byte(`{"version":"0.2.0","serial":1000}`)) - case "/junk/latest": - w.Write([]byte(`hello`)) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - if o, err := sys.checkUpdate(srv.URL + "/new"); err != nil || !o.Newer || o.Version != "0.3.0" { - t.Fatalf("new: %+v %v", o, err) - } - if o, err := sys.checkUpdate(srv.URL + "/same"); err != nil || o.Newer { - t.Fatalf("same: %+v %v", o, err) - } - for _, p := range []string{"/junk", "/missing"} { - if _, err := sys.checkUpdate(srv.URL + p); err == nil { - t.Fatalf("%s: no error", p) - } - } -} - func upload(t *testing.T, h http.Handler, token string, cookie *http.Cookie, bundle []byte, force bool) *httptest.ResponseRecorder { t.Helper() var body bytes.Buffer @@ -227,21 +180,11 @@ func TestUpdateUploadAndInstall(t *testing.T) { t.Fatalf("not staged: %v", err) } - // Pulling: the saved server, through install. - if rec := do(h, "POST", "/update/url", url.Values{"csrf": {token}, "url": {"ftp://nope"}}, cookie); !strings.Contains(rec.Header().Get("Location"), "Not+saved") { - t.Fatalf("bad url: %q", rec.Header().Get("Location")) - } - do(h, "POST", "/update/url", url.Values{"csrf": {token}, "url": {"http://192.168.10.60:8000/"}}, cookie) - if sys.updateURL() != "http://192.168.10.60:8000" { - t.Fatalf("url: %q", sys.updateURL()) - } - do(h, "POST", "/update/install", url.Values{"csrf": {token}}, cookie) - data, _ = os.ReadFile(filepath.Join(sys.updateDir(), "request.json")) - if !strings.Contains(string(data), `"mode":"url"`) || !strings.Contains(string(data), "192.168.10.60:8000") { - t.Fatalf("request: %s", data) - } - if page := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(page, "192.168.10.60:8000") { - t.Fatalf("the page lacks the saved server:\n%s", page) + // The page has no update server any more. + for _, p := range []string{"/update/url", "/update/install", "/update/check"} { + if rec := do(h, "POST", p, url.Values{"csrf": {token}}, cookie); rec.Code != 404 && rec.Code != 405 { + t.Fatalf("%s still exists: %d", p, rec.Code) + } } } diff --git a/pkgs/router-webui/upgrade.go b/pkgs/router-webui/upgrade.go index 8292032..0f60332 100644 --- a/pkgs/router-webui/upgrade.go +++ b/pkgs/router-webui/upgrade.go @@ -43,9 +43,23 @@ var ( // releaseOf is the release (26.11) of a version like 26.11.20261027.31ecbac. func releaseOf(version string) string { return releaseRe.FindString(version) } -// UpgradeCheck is check.json: the channel's newest revision against the running one. +// RouterCheck is what the repository has: its newest release tag against the +// installed version of nixos-router. +type RouterCheck struct { + Repository string `json:"repository"` + Installed string `json:"installed"` + Newest struct { + Tag string `json:"tag"` + Version string `json:"version"` + Rev string `json:"rev"` + } `json:"newest"` + Newer bool `json:"newer"` +} + +// UpgradeCheck is check.json: the newest nixos-router and the channel's newest +// nixpkgs revision, against the installed and the running ones. type UpgradeCheck struct { - Channel string `json:"channel"` + Channel string `json:"channel"` // "" if no channel is followed Branch string `json:"branch"` Time string `json:"time"` Running struct { @@ -55,7 +69,17 @@ type UpgradeCheck struct { Newest struct { Rev string `json:"rev"` } `json:"newest"` - UpToDate bool `json:"upToDate"` + PackagesUpToDate bool `json:"packagesUpToDate"` + UpToDate bool `json:"upToDate"` // both + Router *RouterCheck `json:"router"` // nil if the repository could not be read +} + +// RouterChange is the update of nixos-router that a preview includes. +type RouterChange struct { + From string `json:"from"` + To string `json:"to"` + Tag string `json:"tag"` + Rev string `json:"rev"` } // UpgradeChange is a package that has another version in the new system. @@ -76,6 +100,7 @@ type UpgradePreview struct { Builds int `json:"builds"` BuildNames []string `json:"buildNames"` // what would be built here RebootNeeded bool `json:"rebootNeeded"` + Router *RouterChange `json:"router"` // nixos-router changes too Changes []UpgradeChange `json:"changes"` } @@ -154,13 +179,15 @@ var upgradeTitles = map[string]string{ type channelChoice struct{ Value, Label string } type upgradeData struct { - Version string // the running NixOS version - Channel string - Choices []channelChoice - Check *UpgradeCheck - Preview *UpgradePreview - Run UpgradeRun - Title string // what the running step does + Router Release // the installed nixos-router + Repository string // where its releases come from + Version string // the running NixOS version + Channel string + Choices []channelChoice + Check *UpgradeCheck + Preview *UpgradePreview + Run UpgradeRun + Title string // what the running step does NewerRelease string // a stable release newer than the followed channel exists ReleasesSeen string // when the channel server was last asked which exist @@ -263,7 +290,8 @@ func channelChoices(current string, stable []string) []channelChoice { } func (a *app) upgradeData() upgradeData { - d := upgradeData{Version: a.sys.runningVersion(), Run: a.sys.UpgradeStatus()} + d := upgradeData{Version: a.sys.runningVersion(), Run: a.sys.UpgradeStatus(), + Router: a.sys.installedRelease(), Repository: a.sys.repository()} d.Updating = a.sys.UpdateStatus().Running d.Pending = a.sys.Status().RollbackIn > 0 if s, err := loadSettings(a.sys.settingsPath()); err == nil { @@ -287,7 +315,8 @@ func (a *app) upgradeData() upgradeData { // What was checked before another channel was chosen or before the last // upgrade says nothing about now; nor does a preview that another // nixos-router made (it may list packages differently). - if readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) && c.Channel == d.Channel && c.Running.Version == d.Version { + if readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) && c.Channel == d.Channel && c.Running.Version == d.Version && + (c.Router == nil || c.Router.Installed == a.sys.installedRelease().Version) { d.Check = &c } var p UpgradePreview @@ -344,8 +373,8 @@ func (a *app) upgradeStep(w http.ResponseWriter, r *http.Request, _ session) { return } d := a.upgradeData() - if d.Channel == "" { - a.upgradeBack(w, r, "Choose a channel first.") + if d.Channel == "" && d.Repository == "" { + a.upgradeBack(w, r, "Choose a channel first: this router has no repository to look at either.") return } if (action == "download" || action == "apply") && d.Preview == nil { diff --git a/pkgs/router-webui/upgrade_test.go b/pkgs/router-webui/upgrade_test.go index 5d8e5aa..ba5db11 100644 --- a/pkgs/router-webui/upgrade_test.go +++ b/pkgs/router-webui/upgrade_test.go @@ -46,11 +46,16 @@ func TestOneUpdatesPage(t *testing.T) { t.Fatalf("/upgrade: %d %q", rec.Code, rec.Header().Get("Location")) } body := do(h, "GET", "/update", nil, cookie).Body.String() - for _, want := range []string{"Router software", "Install a bundle", "Update server", `id="packages"`, "Choose a channel", `aria-current="page">Updates`} { + for _, want := range []string{"Install a bundle", `id="packages"`, "Choose a channel", `aria-current="page">Updates`} { if !strings.Contains(body, want) { t.Errorf("the page lacks %q", want) } } + for _, not := range []string{"Update server", "Releases from git", "Look for a newer release"} { + if strings.Contains(body, not) { + t.Errorf("the page still has %q", not) + } + } if strings.Contains(body, `href="/upgrade"`) { t.Error("the menu still links /upgrade") } @@ -245,7 +250,7 @@ func TestUpgradePage(t *testing.T) { t.Run("the last run's output is shown", func(t *testing.T) { os.WriteFile(filepath.Join(a.sys.upgradeDir(), "last.log"), []byte("channel 26.11 (nixos-26.11)\nup to date\n"), 0o600) - if body := page(); !strings.Contains(body, "Last package run") || !strings.Contains(body, "nixos-26.11)") { + if body := page(); !strings.Contains(body, "Last upgrade run") || !strings.Contains(body, "nixos-26.11)") { t.Fatalf("no log:\n%s", body) } if got := tail("a\nbb\nccc\n", 6); got != "ccc\n" { @@ -280,11 +285,11 @@ func TestUpgradePage(t *testing.T) { post("/upgrade/channel", url.Values{"channel": {"26.05"}}) check := `{"channel":"26.05","branch":"nixos-26.05","time":"2026-11-09T10:00:00Z","running":{"rev":"aaa","version":"%s"},"newest":{"rev":"0123456789abcdef"},"upToDate":false}` os.WriteFile(filepath.Join(a.sys.upgradeDir(), "check.json"), []byte(strings.Replace(check, "%s", "26.11.20261001.old", 1)), 0o600) - if strings.Contains(page(), "A newer revision is available") { + if strings.Contains(page(), "A newer version is available") { t.Fatal("an outdated check is shown") } os.WriteFile(filepath.Join(a.sys.upgradeDir(), "check.json"), []byte(strings.Replace(check, "%s", "26.11.20261027.31ecbac", 1)), 0o600) - if body := page(); !strings.Contains(body, "A newer revision is available") || !strings.Contains(body, "0123456") { + if body := page(); !strings.Contains(body, "A newer version is available") || !strings.Contains(body, "0123456") { t.Fatalf("the current check is not shown:\n%s", body) } }) diff --git a/tests/apply.nix b/tests/apply.nix index 05a6eb2..f1a9390 100644 --- a/tests/apply.nix +++ b/tests/apply.nix @@ -47,6 +47,8 @@ let { modulesPath, ... }: { imports = [ (modulesPath + "/testing/test-instrumentation.nix") ]; + # No release repository: this test is about the packages (update.nix has one). + routerUpdate.repository = null; routerSettings.upgrade = { channelsUrl = "http://192.168.10.50:8080"; nixpkgsRef = "path:/var/lib/newer-nixpkgs?lastModified=${toString self.inputs.nixpkgs.lastModified}&rev=%rev%"; @@ -352,7 +354,7 @@ pkgs.testers.runNixOSTest { rev = "0123456789abcdef0123456789abcdef01234567" channel(rev) out = target.succeed("router-upgrade check 2>&1") - assert "a newer revision is available" in out, out + assert "a newer version is available" in out, out assert json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))["upToDate"] is False channel(running_rev) out = target.succeed("router-upgrade check 2>&1") @@ -448,7 +450,7 @@ pkgs.testers.runNixOSTest { assert curl(f"-o /dev/null -w '%{{redirect_url}}' {ui}/upgrade").endswith("/update#packages") page = curl(f"{ui}/update") - assert "Packages" in page and "Router software" in page and 'value="26.05" selected' in page and target.succeed("cat /run/current-system/nixos-version").strip() in page, page + assert "Check for upgrades" in page and "Install a bundle" in page and 'value="26.05" selected' in page and target.succeed("cat /run/current-system/nixos-version").strip() in page, page assert curl(f"-o /dev/null -w '%{{http_code}}' -d csrf={csrf('/update')} -d 'channel=nixos-26.05%3Bx' {ui}/upgrade/channel") == "303" assert "26.05" in target.succeed("jq -r .router.update.channel /var/lib/router/config/settings.json") assert curl(f"-o /dev/null -w '%{{http_code}}' -d csrf=wrong {ui}/upgrade/check") == "403" @@ -461,6 +463,6 @@ pkgs.testers.runNixOSTest { step("apply") assert "Upgrade to" not in curl(f"{ui}/update") assert json.loads(target.succeed("cat /var/lib/router/config/nixpkgs-pin.json"))["rev"] == running_rev - assert "Last package run" in curl(f"{ui}/update") + assert "Last upgrade run" in curl(f"{ui}/update") ''; } diff --git a/tests/update.nix b/tests/update.nix index c91a2bd..69b72d9 100644 --- a/tests/update.nix +++ b/tests/update.nix @@ -351,14 +351,15 @@ pkgs.testers.runNixOSTest { pinned() target.wait_for_unit("router-webui.service") - with subtest("the same update, pulled from a server in the web UI, can be confirmed"): + with subtest("the same update, pulled from a server, can be confirmed in the web UI"): login() - token = csrf("/update") - form = lambda path, data: builder.succeed( - f"curl -sk -b /tmp/jar -o /tmp/out -w '%{{http_code}}' --data-urlencode csrf={token} {data} {ui}{path}").strip() - assert form("/update/url", "--data-urlencode url=http://${builderIp}:8004/") == "303" - assert "Available: 2.0.0" in (form("/update/check", "") and builder.succeed("cat /tmp/out")) - assert form("/update/install", "") == "303" + # The page has no update server to set any more; the command line still pulls. + page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update") + assert "Update server" not in page, page + # (As the unit, like the web UI starts it: the switch restarts the web UI.) + target.succeed("mkdir -p /var/lib/router/update" + " && echo '{\"mode\":\"url\",\"url\":\"http://${builderIp}:8004\",\"force\":false}' > /var/lib/router/update/request.json" + " && systemctl start --no-block router-update.service") update_finished() assert version() == "2.0.0" target.succeed("systemctl is-active router-rollback.timer") @@ -382,7 +383,14 @@ pkgs.testers.runNixOSTest { assert rc != 0 and "not newer" in out, out assert version() == "2.0.0" - with subtest("a release in a git repository is found, built and installed like a bundle"): + def upgrade_finished(): + target.wait_until_succeeds( + "state=$(systemctl show -p ActiveState --value router-upgrade.service);" + " test $state = inactive -o $state = failed", timeout=300) + result = target.succeed("systemctl show -p Result --value router-upgrade.service").strip() + assert result == "success", (result, target.succeed("journalctl -u router-upgrade.service --no-pager | tail -30")) + + with subtest("a release in a git repository is found with the packages, previewed and installed like any upgrade"): repo = "http://${builderIp}:8005/router.git" builder.succeed("cp -r ${v3.src} /root/v3 && chmod -R u+w /root/v3") builder.succeed("cd /root/v3 && git init -q -b main && git add -A" @@ -401,30 +409,33 @@ pkgs.testers.runNixOSTest { form = lambda path, data: builder.succeed( f"curl -sk -b /tmp/jar -o /tmp/out -w '%{{http_code}}' --data-urlencode csrf={token} {data} {ui}{path}").strip() assert form("/update/repository", f"--data-urlencode repository={repo}") in ("404", "405") - assert form("/update/gitcheck", "") == "303" - target.wait_until_succeeds( - "test $(systemctl show -p ActiveState --value router-update-check.service) = inactive" - " && test $(systemctl show -p Result --value router-update-check.service) = success", timeout=120) - check = json.loads(target.succeed("cat /var/lib/router/update/check.json")) - assert check["newer"] is True and check["newest"] == {"tag": "v3.0.0", "version": "3.0.0", "rev": commit} and check["installed"] == "2.0.0", check + assert form("/update/gitcheck", "") in ("404", "405") + # One check looks at both: the repository and the channel. + assert form("/upgrade/check", "") == "303" + upgrade_finished() + check = json.loads(target.succeed("cat /var/lib/router/upgrade/check.json")) + assert check["router"]["newer"] is True and check["router"]["newest"] == {"tag": "v3.0.0", "version": "3.0.0", "rev": commit}, check + assert check["router"]["installed"] == "2.0.0" and check["packagesUpToDate"] is True and check["upToDate"] is False, check assert "nixos-router 3.0.0 is out" in builder.succeed(f"curl -sk -b /tmp/jar {ui}/") - assert "Install 3.0.0" in builder.succeed(f"curl -sk -b /tmp/jar {ui}/update") + page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update") + assert "3.0.0" in page and "A newer version is available" in page, page # Only tags that are versions are releases; a newer tag of another kind is ignored. builder.succeed("cd /root/v3 && git tag nightly && git tag v4.0 && git push -q /srv/git/router.git nightly v4.0") - target.succeed("router-update check >&2") - assert json.loads(target.succeed("cat /var/lib/router/update/check.json"))["newest"]["tag"] == "v3.0.0" + target.succeed("router-upgrade check >&2") + assert json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))["router"]["newest"]["tag"] == "v3.0.0" - rc, out = target.execute("router-update --git v9.9.9 2>&1") - assert rc != 0 and "no such release tag" in out, out - rc, out = target.execute("router-update --git 'v3.0.0; reboot' 2>&1") - assert rc != 0 and "not a release tag" in out, out - assert version() == "2.0.0" + # The preview names the router's own update, in the table with the packages. + assert form("/upgrade/preview", "") == "303" + upgrade_finished() + preview = json.loads(target.succeed("cat /var/lib/router/upgrade/preview.json")) + assert preview["router"]["from"] == "2.0.0" and preview["router"]["to"] == "3.0.0", preview + page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update") + assert 'class="highlight"' in page and "nixos-router" in page and "Upgrade nixos-router to 3.0.0 and" in page, page + # Nothing has changed on the router until the upgrade is applied. + assert version() == "2.0.0" and "v3.0.0" not in target.succeed("cat /var/lib/router/config/flake.nix") - login() - token = csrf("/update") - assert form("/update/gitinstall", "--data-urlencode tag=v3.0.0") == "303" - update_finished() + target.succeed("router-upgrade apply 5min >&2") assert version() == "3.0.0", release_json() flake = target.succeed("cat /var/lib/router/config/flake.nix") assert f"git+{repo}?ref=refs/tags/v3.0.0&rev={commit}" in flake, flake @@ -433,7 +444,6 @@ pkgs.testers.runNixOSTest { assert locked["type"] == "git" and locked["rev"] == commit, locked settings = target.succeed("cat /var/lib/router/config/settings.json") assert '"version": 2' in settings and "Europe/Paris" in settings, settings - assert "router-update-check" not in settings pinned() target.succeed("systemctl is-active router-rollback.timer") login() @@ -449,10 +459,10 @@ pkgs.testers.runNixOSTest { assert "no changes" in out, out builder.succeed("systemd-run --unit=git-server-again /etc/git-server.py /srv/git 8005") builder.wait_for_open_port(8005, "${builderIp}") - target.succeed("router-update check >&2") - check = json.loads(target.succeed("cat /var/lib/router/update/check.json")) - assert check["newer"] is False and check["installed"] == "3.0.0", check - rc, out = target.execute("router-update --git latest 2>&1") - assert rc != 0 and "not newer" in out, out + target.succeed("router-upgrade check >&2") + check = json.loads(target.succeed("cat /var/lib/router/upgrade/check.json")) + assert check["router"]["newer"] is False and check["router"]["installed"] == "3.0.0" and check["upToDate"] is True, check + out = target.succeed("router-upgrade preview 2>&1") + assert "up to date" in out, out ''; }