router.update.repository names a public repository whose tags vX.Y.Z are releases. router-update check (daily, and from the Updates page) looks for a newer one and the Overview says so; router-update --git builds the router from a tag like a bundle update: the settings are migrated, the new version must be confirmed, the nixpkgs pin stays. The flake of such a router comes from the release's config-flake.nix. The global flake registry is off. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
373 lines
12 KiB
Go
373 lines
12 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// The packages page: upgrading nixpkgs (the kernel and every package) without
|
|
// a new release of nixos-router. The work is done by router-upgrade (root, the
|
|
// systemd unit router-upgrade.service); the page asks for a step in
|
|
// upgrade/request.json and shows what the steps left in upgrade/: check.json,
|
|
// preview.json and the unit's log. The channel is the setting
|
|
// router.update.channel.
|
|
|
|
func (s System) upgradeDir() string { return filepath.Join(s.StateDir, "upgrade") }
|
|
|
|
func (s System) versionPath() string {
|
|
if s.VersionFile != "" {
|
|
return s.VersionFile
|
|
}
|
|
return "/run/current-system/nixos-version"
|
|
}
|
|
|
|
// runningVersion is the NixOS version of the running system (26.11.20261027.31ecbac).
|
|
func (s System) runningVersion() string {
|
|
data, _ := os.ReadFile(s.versionPath())
|
|
return strings.TrimSpace(string(data))
|
|
}
|
|
|
|
var (
|
|
releaseRe = regexp.MustCompile(`^[0-9]+\.[0-9]+`)
|
|
channelRe = regexp.MustCompile(`^(unstable|[0-9]{2}\.[0-9]{2})$`)
|
|
)
|
|
|
|
// 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.
|
|
type UpgradeCheck struct {
|
|
Channel string `json:"channel"`
|
|
Branch string `json:"branch"`
|
|
Time string `json:"time"`
|
|
Running struct {
|
|
Rev string `json:"rev"`
|
|
Version string `json:"version"`
|
|
} `json:"running"`
|
|
Newest struct {
|
|
Rev string `json:"rev"`
|
|
} `json:"newest"`
|
|
UpToDate bool `json:"upToDate"`
|
|
}
|
|
|
|
// UpgradeChange is a package that has another version in the new system.
|
|
type UpgradeChange struct {
|
|
Name string `json:"name"`
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
}
|
|
|
|
// UpgradePreview is preview.json.
|
|
type UpgradePreview struct {
|
|
Channel string `json:"channel"`
|
|
Release string `json:"release"` // the nixos-router that made it
|
|
Rev string `json:"rev"`
|
|
Version string `json:"version"`
|
|
Time string `json:"time"`
|
|
Download string `json:"download"`
|
|
Builds int `json:"builds"`
|
|
BuildNames []string `json:"buildNames"` // what would be built here
|
|
RebootNeeded bool `json:"rebootNeeded"`
|
|
Changes []UpgradeChange `json:"changes"`
|
|
}
|
|
|
|
// MoreBuilds is how many derivations are built that BuildNames does not name.
|
|
func (p UpgradePreview) MoreBuilds() int { return max(p.Builds-len(p.BuildNames), 0) }
|
|
|
|
func readUpgradeFile(path string, v any) bool {
|
|
data, err := os.ReadFile(path)
|
|
return err == nil && json.Unmarshal(data, v) == nil
|
|
}
|
|
|
|
// channel is the saved setting router.update.channel ("" for none).
|
|
func (s Settings) channel() string { return str(s, "router", "update", "channel") }
|
|
|
|
// setChannel changes router.update.channel in settings.json and, since it takes
|
|
// effect when upgrading rather than when applying, in the confirmed settings
|
|
// too, so it does not show up as an unapplied change.
|
|
func (sys System) setChannel(channel string) error { return sys.setUpdateField("channel", channel) }
|
|
|
|
// setUpdateField does that for a key of router.update ("" removes it).
|
|
func (sys System) setUpdateField(key, value string) error {
|
|
set := func(path string, required bool) error {
|
|
s, err := loadSettings(path)
|
|
if err != nil {
|
|
if !required && os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
router := obj(s, "router")
|
|
if value == "" {
|
|
if u, ok := router["update"].(map[string]any); ok {
|
|
delete(u, key)
|
|
if len(u) == 0 {
|
|
delete(router, "update")
|
|
}
|
|
}
|
|
} else {
|
|
obj(router, "update")[key] = value
|
|
}
|
|
return s.save(path)
|
|
}
|
|
if err := set(sys.settingsPath(), true); err != nil {
|
|
return err
|
|
}
|
|
return set(sys.confirmedPath(), false)
|
|
}
|
|
|
|
// UpgradeRun is the state of the router-upgrade unit.
|
|
type UpgradeRun = UpdateStatus
|
|
|
|
func (s System) UpgradeStatus() UpgradeRun { return unitRun("router-upgrade.service") }
|
|
|
|
// requestUpgrade asks the router-upgrade unit for one step.
|
|
func (s System) requestUpgrade(action string, force, downgrade bool, timeout string) error {
|
|
data, _ := json.Marshal(map[string]any{"action": action, "force": force, "downgrade": downgrade, "timeout": timeout})
|
|
if err := os.MkdirAll(s.upgradeDir(), 0o700); err != nil {
|
|
return err
|
|
}
|
|
if err := writeFileAtomic(filepath.Join(s.upgradeDir(), "request.json"), data, 0o600); err != nil {
|
|
return err
|
|
}
|
|
// The unit removes the request when it starts; the page says what runs.
|
|
writeFileAtomic(filepath.Join(s.upgradeDir(), "action"), []byte(action), 0o600)
|
|
return startUnit("router-upgrade.service")
|
|
}
|
|
|
|
// upgradeTitles say what a running step does, for the page over the site.
|
|
var upgradeTitles = map[string]string{
|
|
"check": "Checking for a newer revision…",
|
|
"preview": "Working out what would change…",
|
|
"download": "Downloading and building…",
|
|
"apply": "Upgrading…",
|
|
}
|
|
|
|
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
|
|
|
|
NewerRelease string // a stable release newer than the followed channel exists
|
|
ReleasesSeen string // when the channel server was last asked which exist
|
|
Updating bool // router-update is running
|
|
Pending bool // a system waits for confirmation
|
|
}
|
|
|
|
// stableChannels are the stable NixOS releases the page offers (the branch
|
|
// nixos-26.05 and so on) until the router has asked the channel server which
|
|
// exist (router-upgrade releases, daily); the release a router runs says
|
|
// nothing about it: nixos-unstable already calls itself the release that comes
|
|
// next.
|
|
var stableChannels = []string{"26.05"}
|
|
|
|
// ReleaseList is releases.json: the stable releases the channel server had.
|
|
type ReleaseList struct {
|
|
Time string `json:"time"`
|
|
Releases []string `json:"releases"`
|
|
}
|
|
|
|
var releaseNameRe = regexp.MustCompile(`^[0-9]{2}\.[0-9]{2}$`)
|
|
|
|
// releaseCmp orders releases like 25.11 and 26.05 (and 100.05) by number.
|
|
func releaseCmp(a, b string) int {
|
|
pa, pb := strings.SplitN(a, ".", 2), strings.SplitN(b, ".", 2)
|
|
for i := range pa {
|
|
if i >= len(pb) {
|
|
return 1
|
|
}
|
|
x, _ := strconv.Atoi(pa[i])
|
|
y, _ := strconv.Atoi(pb[i])
|
|
if x != y {
|
|
return x - y
|
|
}
|
|
}
|
|
if len(pb) > len(pa) {
|
|
return -1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// seenReleases are the stable releases the channel server last answered with,
|
|
// oldest first; none if it has not been asked yet.
|
|
func (s System) seenReleases() ReleaseList {
|
|
var l ReleaseList
|
|
readUpgradeFile(filepath.Join(s.upgradeDir(), "releases.json"), &l)
|
|
var ok []string
|
|
for _, r := range l.Releases {
|
|
if releaseNameRe.MatchString(r) {
|
|
ok = append(ok, r)
|
|
}
|
|
}
|
|
slices.SortFunc(ok, releaseCmp)
|
|
l.Releases = slices.Compact(ok)
|
|
return l
|
|
}
|
|
|
|
// supportedReleases are the stable releases worth following: NixOS supports the
|
|
// newest two. Before the router has asked, the ones built in.
|
|
func supportedReleases(seen []string) []string {
|
|
if len(seen) == 0 {
|
|
return stableChannels
|
|
}
|
|
return seen[max(len(seen)-2, 0):]
|
|
}
|
|
|
|
// newerRelease is the newest stable release that is newer than the one the
|
|
// router follows, "" if it follows unstable (or nothing) or is up to date.
|
|
func newerRelease(current string, seen []string) string {
|
|
if !releaseNameRe.MatchString(current) || len(seen) == 0 {
|
|
return ""
|
|
}
|
|
if newest := seen[len(seen)-1]; releaseCmp(newest, current) > 0 {
|
|
return newest
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// releaseNotice says which newer release exists than the channel being followed.
|
|
func (a *app) releaseNotice() string {
|
|
s, err := loadSettings(a.sys.settingsPath())
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return newerRelease(s.channel(), a.sys.seenReleases().Releases)
|
|
}
|
|
|
|
// channelChoices are the branches worth offering: none (the packages that came
|
|
// with the release), unstable and the stable releases. A configured channel
|
|
// that is none of these stays listed.
|
|
func channelChoices(current string, stable []string) []channelChoice {
|
|
choices := []channelChoice{{"", "None: the packages that came with this release of nixos-router"}, {"unstable", "unstable (newest, may break)"}}
|
|
for _, r := range stable {
|
|
choices = append(choices, channelChoice{r, r + " (stable)"})
|
|
}
|
|
if current != "" && !slices.ContainsFunc(choices, func(c channelChoice) bool { return c.Value == current }) {
|
|
choices = append(choices, channelChoice{current, current})
|
|
}
|
|
return choices
|
|
}
|
|
|
|
func (a *app) upgradeData() upgradeData {
|
|
d := upgradeData{Version: a.sys.runningVersion(), Run: a.sys.UpgradeStatus()}
|
|
d.Updating = a.sys.UpdateStatus().Running
|
|
d.Pending = a.sys.Status().RollbackIn > 0
|
|
if s, err := loadSettings(a.sys.settingsPath()); err == nil {
|
|
d.Channel = s.channel()
|
|
}
|
|
seen := a.sys.seenReleases()
|
|
d.Choices = channelChoices(d.Channel, supportedReleases(seen.Releases))
|
|
d.NewerRelease = newerRelease(d.Channel, seen.Releases)
|
|
d.ReleasesSeen = seen.Time
|
|
if d.Run.Running {
|
|
data, _ := os.ReadFile(filepath.Join(a.sys.upgradeDir(), "action"))
|
|
if d.Title = upgradeTitles[strings.TrimSpace(string(data))]; d.Title == "" {
|
|
d.Title = "Working…"
|
|
}
|
|
}
|
|
// What router-upgrade printed: a finished one-shot unit has no journal to find.
|
|
if data, err := os.ReadFile(filepath.Join(a.sys.upgradeDir(), "last.log")); err == nil {
|
|
d.Run.Log = tail(string(data), 64<<10)
|
|
}
|
|
var c UpgradeCheck
|
|
// 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 {
|
|
d.Check = &c
|
|
}
|
|
var p UpgradePreview
|
|
if readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "preview.json"), &p) && p.Channel == d.Channel && p.Release != "" && p.Release == a.sys.installedRelease().Version {
|
|
d.Preview = &p
|
|
}
|
|
return d
|
|
}
|
|
|
|
func (a *app) upgradeBack(w http.ResponseWriter, r *http.Request, msg string) {
|
|
http.Redirect(w, r, "/update?msg="+url.QueryEscape(msg)+"#packages", http.StatusSeeOther)
|
|
}
|
|
|
|
func (a *app) upgradeChannel(w http.ResponseWriter, r *http.Request, _ session) {
|
|
v := strings.TrimSpace(r.PostFormValue("channel"))
|
|
if !r.PostForm.Has("channel") {
|
|
a.upgradeBack(w, r, "Not saved: no channel was sent.")
|
|
return
|
|
}
|
|
if v != "" && !channelRe.MatchString(v) {
|
|
a.upgradeBack(w, r, "Not saved: the channel is unstable or a release like 26.05.")
|
|
return
|
|
}
|
|
if err := a.sys.setChannel(v); err != nil {
|
|
a.upgradeBack(w, r, "Not saved: "+err.Error())
|
|
return
|
|
}
|
|
a.upgradeBack(w, r, "Saved.")
|
|
}
|
|
|
|
var upgradeSteps = map[string]string{
|
|
"check": "Checking.",
|
|
"preview": "Working out what would change.",
|
|
"download": "Downloading.",
|
|
"apply": "Upgrading.",
|
|
}
|
|
|
|
// upgradeStep starts one step of router-upgrade.
|
|
func (a *app) upgradeStep(w http.ResponseWriter, r *http.Request, _ session) {
|
|
action := r.PathValue("step")
|
|
msg, ok := upgradeSteps[action]
|
|
if !ok {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
// Looking is harmless beside a change that waits for confirmation;
|
|
// changing the system or filling the disk is not.
|
|
if a.sys.UpgradeStatus().Running || a.sys.UpdateStatus().Running {
|
|
a.upgradeBack(w, r, "Another upgrade or update is running.")
|
|
return
|
|
}
|
|
if (action == "download" || action == "apply") && a.busy() {
|
|
a.upgradeBack(w, r, "Another change is in progress or waiting for confirmation.")
|
|
return
|
|
}
|
|
d := a.upgradeData()
|
|
if d.Channel == "" {
|
|
a.upgradeBack(w, r, "Choose a channel first.")
|
|
return
|
|
}
|
|
if (action == "download" || action == "apply") && d.Preview == nil {
|
|
a.upgradeBack(w, r, "Preview first: it says what would change.")
|
|
return
|
|
}
|
|
if err := a.sys.requestUpgrade(action, r.PostFormValue("force") == "on", r.PostFormValue("downgrade") == "on", ""); err != nil {
|
|
a.upgradeBack(w, r, fmt.Sprintf("Could not start it: %v", err))
|
|
return
|
|
}
|
|
a.upgradeBack(w, r, msg)
|
|
}
|
|
|
|
// tail is the last n bytes of s, from a line start.
|
|
func tail(s string, n int) string {
|
|
if len(s) <= n {
|
|
return s
|
|
}
|
|
s = s[len(s)-n:]
|
|
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
|
s = s[i+1:]
|
|
}
|
|
return s
|
|
}
|