Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
205ad9a1c7 | ||
|
|
553361f811 | ||
|
|
2aa70630d4 | ||
|
|
7cf8cb62a2 | ||
|
|
b1d181a1dd | ||
|
|
2b7cd86e98 | ||
|
|
3e6eee0b9c | ||
|
|
da206a5237 | ||
|
|
3881c623cf | ||
|
|
83343f7a18 | ||
|
|
3afd7ed4cc | ||
|
|
ad9de15344 |
@@ -246,6 +246,19 @@ Two sources, so nothing the machine already exports is written twice.
|
||||
- **node_exporter** (`router.metrics.nodeExporter`, `modules/router/metrics.nix`): CPU, memory, disks, interfaces and systemd units. Off by default. It listens on all addresses, but the firewall opens its port (9100) only to the zones in `zones` (one allow rule each, to `local`); `wan` is refused by an assertion. With no zone it can only be read on the router itself.
|
||||
- Tested in `webui` (token needed, the samples, node_exporter from the LAN and on the router, the rule names the LAN's device only) and `assertions`. The **Prometheus page** (Services → Prometheus, `exporter.go`) edits the exporter's settings (enable, port, zones to open it to; `wan` and the router's own ports are refused) and shows the scrape config for `/metrics` and for node_exporter. Not done: per-LAN traffic of the web UI's own history (node_exporter has the interface counters), and alert rules or a Grafana dashboard.
|
||||
|
||||
## Load balancers (2026-11-27)
|
||||
|
||||
A service on several hosts that must be reachable from outside and inside, with backend checks (the first case: an API on `hv1` and `hv2`). `router.loadBalancers.<name>` (`options.nix`, `modules/router/loadbalancer.nix`) generates an HAProxy configuration (`services.haproxy`); nothing else on the router changes.
|
||||
|
||||
- **Listening:** `listen.port` and `listen.zones` (`wan` = the uplink, or the zones of LANs and tunnels). The firewall opens that port in those zones itself (`lbInput` in `firewall.nix`), so no rule is needed. IPv4 and IPv6 are bound apart: one dual-stack socket shows IPv4 clients as `::ffff:a.b.c.d` in `X-Forwarded-For` (found by the VM test).
|
||||
- **TLS, a decision per service:** `terminate` (the router decrypts with `certificate`, a PEM with chain and key, or with its own ACME certificate when `router.acme.domains` covers `hosts`; to the backends in the clear or, with `backendTls.enable`, encrypted again, verified only if `backendTls.verify`), `passthrough` (bytes only; the backends have the certificate, and only the checks speak TLS) or `none`. `protocol` is `http` (adds `X-Forwarded-For`) or `tcp` (always with passthrough). `proxyProtocol` sends the client's address to backends that read it (for tcp).
|
||||
- **Backends:** names of DHCP reservations or IPv4 addresses, on `backendPort` (default the listen port). `balance`: `roundrobin`, `leastconn`, `source`. Checks: an HTTP GET of `check.path` (2xx/3xx) every `check.interval`, `fall` failures take a backend out, `rise` successes bring it back; `check.useHttp = false` only connects. With no backend up the service answers 503.
|
||||
- **Host names:** `hosts` is the Host header or TLS name that selects the service, so services may share a port (each needs `hosts`; they must agree on `tls` and `protocol`). The names are also published in the local DNS (`dns.hosts`, `mkDefault`) as the router's addresses on the LANs the service listens in, so inside and outside use the same name. This is the host-based routing that was open for ports 80/443 (TLS name or Host header; the web UI's own port still has to be another one).
|
||||
- **Assertions:** a backend that is neither a reservation nor an address, an unknown zone, a port the router itself uses (SSH, DNS, the web UI) or that `firewall.nat` forwards, shared ports without `hosts`, services on a port that disagree, passthrough with `http`, no certificate without ACME, a certificate that does not cover `hosts`.
|
||||
- **Web UI:** Network → Load balancers (`loadbalancer.go`): the saved configuration beside what HAProxy says (`show stat` on `/run/haproxy/haproxy.sock`: state, last check, connections, time in the state), refreshed every 10 s; "not applied" for a saved service HAProxy does not know yet. Services are edited in Advanced (no form yet).
|
||||
- Tested in the `loadbalancer` VM test (both backends used from outside and inside, `X-Forwarded-For`, the DNS name, passthrough, the closed port, a sick and a stopped backend, 503, the statistics columns the page reads), `assertions` and the Go tests. Not tested: the PROXY protocol, `balance = source`, `backendTls.verify`, shared ports in a VM, the router's own ACME certificate.
|
||||
- Open: a form for the settings, backend state in `/metrics` and the MCP tools, UDP, drain/maintenance of a backend from the page.
|
||||
|
||||
## Not done yet (2026-11-01, after 0.12.0)
|
||||
|
||||
Remote access
|
||||
@@ -256,7 +269,7 @@ Remote access
|
||||
- Rule for all of it: changes go through `settings.json` and `router-apply` (commit-confirm), never straight to the live system; tokens have scopes; every call is logged.
|
||||
|
||||
Firewall and networking
|
||||
- **Host-based routing on 80/443**: decide by TLS server name (or the `Host` header) between the router's web UI and a host behind it. It needs an SNI proxy on the router and loses the client address unless the host takes the PROXY protocol. Until then, expose the web UI and SSH on their own ports with `wan -> local` rules.
|
||||
- **Host-based routing on 80/443**: *mostly done by the load balancers* (see above: services sharing a port by `hosts`). Still open: sharing 443 with the router's own web UI, which needs the web UI behind the proxy. Until then, expose the web UI and SSH on their own ports with `wan -> local` rules.
|
||||
- **WireGuard**: live status (handshake, transfer) in the web UI; a tunnel with `dns = true` but no address.
|
||||
- **IPv6** for forwards: a pinhole for a host behind the router is possible by hand (`wan -> lan` with an IPv6 `destination`), nothing helps with finding the host's delegated address. Also open: other LANs are IPv4-only (PD serves one LAN), DHCPv6 reservations, NPTv6.
|
||||
- **Multi-WAN failover**, **QoS** (CAKE/SQM): deferred, not started.
|
||||
@@ -289,12 +302,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).
|
||||
2. **Done (0.13.3):** `router.update.repository` (an http(s) address, no credentials or query; saved like the channel, in the confirmed settings too, so it is no unapplied change). `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.
|
||||
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+<repo>?ref=refs/tags/<tag>&rev=<commit>`, 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. Still to do: a release is a tag `vX.Y.Z` on the release commit (`router-release` tags it, still writes a bundle for the installer and offline routers) and refuses a `flake.lock` whose nixpkgs is not a channel revision (`git-revision`), so cache.nixos.org has its packages.
|
||||
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.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# The flake.nix of an installed router's configuration directory when its
|
||||
# nixos-router comes from a git repository (router.update.repository).
|
||||
# `router-update --git` writes it with @SOURCE@ replaced by the address of the
|
||||
# nixos-router comes from a git repository (routerUpdate.repository).
|
||||
# `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.
|
||||
#
|
||||
|
||||
@@ -222,6 +222,7 @@
|
||||
name = "router-release";
|
||||
runtimeInputs = with pkgs; [
|
||||
nix
|
||||
git
|
||||
gnutar
|
||||
coreutils
|
||||
jq
|
||||
|
||||
@@ -437,6 +437,99 @@ let
|
||||
}
|
||||
];
|
||||
|
||||
lbs = cfg.loadBalancers;
|
||||
lbReserved = lib.foldl' (acc: l: acc // l.dhcp.reservations) { } lans;
|
||||
lbBackendOk = b: validIp b || lib.hasAttr b lbReserved;
|
||||
# A name the router's certificate covers (a wildcard covers one label).
|
||||
acmeCovers =
|
||||
h:
|
||||
lib.any (
|
||||
d:
|
||||
d == h
|
||||
|| (
|
||||
lib.hasPrefix "*." d
|
||||
&& lib.hasInfix "." h
|
||||
&& lib.removePrefix "*" d == "." + lib.concatStringsSep "." (lib.tail (lib.splitString "." h))
|
||||
)
|
||||
) cfg.acme.domains;
|
||||
lbPortsTaken = [ 22 ] ++ [ 53 ] ++ cfg.managementPorts;
|
||||
lbDnatPorts = lib.concatMap (n: lib.filter lib.isInt n.ports) (
|
||||
lib.filter (n: n.type == "dnat") cfg.firewall.nat
|
||||
);
|
||||
lbAssertions =
|
||||
name: lb:
|
||||
let
|
||||
where = "router.loadBalancers.${name}";
|
||||
sharing = lib.filter (n: n != name && lbs.${n}.listen.port == lb.listen.port) (lib.attrNames lbs);
|
||||
in
|
||||
[
|
||||
{
|
||||
assertion = lb.backends != [ ];
|
||||
message = "${where}.backends: at least one backend.";
|
||||
}
|
||||
{
|
||||
assertion = lib.all lbBackendOk lb.backends;
|
||||
message = "${where}.backends: `${
|
||||
lib.concatStringsSep ", " (lib.filter (b: !lbBackendOk b) lb.backends)
|
||||
}` is neither a DHCP reservation nor an IPv4 address.";
|
||||
}
|
||||
{
|
||||
assertion = lib.all (z: z == "wan" || lib.elem z zoneNames) lb.listen.zones && lb.listen.zones != [ ];
|
||||
message = "${where}.listen.zones: unknown zone (zones: wan, ${lib.concatStringsSep ", " zoneNames}).";
|
||||
}
|
||||
{
|
||||
assertion = lib.all dnsNameOk lb.hosts;
|
||||
message = "${where}.hosts: a name is not a valid DNS name.";
|
||||
}
|
||||
{
|
||||
assertion = lb.tls != "passthrough" || lb.protocol == "tcp";
|
||||
message = "${where}: passthrough only forwards bytes: protocol must be \"tcp\".";
|
||||
}
|
||||
{
|
||||
assertion = lb.hosts == [ ] || lb.tls != "none" || lb.protocol == "http";
|
||||
message = "${where}.hosts: without TLS the host name is only visible in HTTP: use protocol \"http\", or leave hosts empty.";
|
||||
}
|
||||
{
|
||||
assertion = lb.tls == "terminate" || lb.certificate == null;
|
||||
message = "${where}.certificate: only a service that terminates TLS has one.";
|
||||
}
|
||||
{
|
||||
assertion = lb.tls != "terminate" || lb.certificate != null || cfg.acme.enable;
|
||||
message = "${where}: it terminates TLS but has no `certificate` and router.acme is not enabled.";
|
||||
}
|
||||
{
|
||||
assertion =
|
||||
lb.tls != "terminate" || lb.certificate != null || !cfg.acme.enable || lib.all acmeCovers lb.hosts;
|
||||
message = "${where}.hosts: the router's certificate (router.acme.domains) does not cover ${
|
||||
lib.concatStringsSep ", " (lib.filter (h: !acmeCovers h) lb.hosts)
|
||||
}; add the name there or give the service its own `certificate`.";
|
||||
}
|
||||
{
|
||||
assertion = lb.backendTls.enable || !lb.backendTls.verify;
|
||||
message = "${where}.backendTls.verify needs backendTls.enable.";
|
||||
}
|
||||
{
|
||||
assertion = !(lib.elem lb.listen.port lbPortsTaken);
|
||||
message = "${where}.listen.port ${toString lb.listen.port} is used by the router itself (SSH, DNS, the web UI).";
|
||||
}
|
||||
{
|
||||
assertion = !(lib.elem lb.listen.port lbDnatPorts);
|
||||
message = "${where}.listen.port ${toString lb.listen.port} is also forwarded by router.firewall.nat: the forward would take the connections first.";
|
||||
}
|
||||
{
|
||||
assertion = sharing == [ ] || (lb.hosts != [ ] && lib.all (n: lbs.${n}.hosts != [ ]) sharing);
|
||||
message = "${where}: port ${toString lb.listen.port} is shared with ${lib.concatStringsSep ", " sharing}: every service on it needs `hosts`.";
|
||||
}
|
||||
{
|
||||
assertion = lib.all (n: lbs.${n}.tls == lb.tls && lbs.${n}.protocol == lb.protocol) sharing;
|
||||
message = "${where}: services that share port ${toString lb.listen.port} must agree on tls and protocol.";
|
||||
}
|
||||
{
|
||||
assertion = lib.all (n: !(lib.any (h: lib.elem h lbs.${n}.hosts) lb.hosts)) sharing;
|
||||
message = "${where}.hosts: another service on port ${toString lb.listen.port} has one of these names.";
|
||||
}
|
||||
];
|
||||
|
||||
overlapsLan = n: lib.any (l: ipv4.overlaps n l) lanNets;
|
||||
|
||||
wgAssertions =
|
||||
@@ -597,6 +690,7 @@ in
|
||||
]
|
||||
++ lib.concatLists (lib.mapAttrsToList perLan lansByName)
|
||||
++ dnsAssertions
|
||||
++ lib.concatLists (lib.mapAttrsToList lbAssertions lbs)
|
||||
++ lib.concatMap ruleAssertions cfg.firewall.rules
|
||||
++ lib.concatMap natAssertions cfg.firewall.nat
|
||||
++ [
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
./firewall.nix
|
||||
./dhcp.nix
|
||||
./dns.nix
|
||||
./loadbalancer.nix
|
||||
./ddns.nix
|
||||
./acme.nix
|
||||
./rollback.nix
|
||||
|
||||
@@ -62,6 +62,19 @@ let
|
||||
|
||||
setOf = xs: "{ ${lib.concatMapStringsSep ", " toString xs} }";
|
||||
|
||||
# Load balancers listen on the router: their port is open in their zones.
|
||||
lbInput = lib.concatLists (
|
||||
lib.mapAttrsToList (
|
||||
name: lb:
|
||||
let
|
||||
devs = lib.unique (
|
||||
lib.concatMap (z: if z == "wan" then uplinks else zoneDevices z) lb.listen.zones
|
||||
);
|
||||
in
|
||||
lib.optional (devs != [ ]) "iifname ${set devs} tcp dport ${toString lb.listen.port} accept # load balancer ${name}"
|
||||
) cfg.loadBalancers
|
||||
);
|
||||
|
||||
# Layer 4 match; `ports` and `sports` may be ints or "a-b" ranges.
|
||||
l4 =
|
||||
proto: ports: sports:
|
||||
@@ -261,6 +274,7 @@ in
|
||||
lib.concatMapStringsSep ", " toString listenPorts
|
||||
} } accept # wireguard"
|
||||
}
|
||||
${lib.concatStringsSep "\n " lbInput}
|
||||
${lib.optionalString (dhcpIfaces != [ ]) "iifname ${set dhcpIfaces} udp dport 67 accept"}
|
||||
${lib.optionalString (mgmtIfaces != [ ]) "iifname ${set mgmtIfaces} tcp dport { ${
|
||||
lib.concatMapStringsSep ", " toString ([ 22 ] ++ config.router.managementPorts)
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
{ config, lib, ... }:
|
||||
let
|
||||
cfg = config.router;
|
||||
lbs = cfg.loadBalancers;
|
||||
names = lib.attrNames lbs;
|
||||
lans = lib.attrValues cfg.lans;
|
||||
acme = cfg.acme;
|
||||
acmeName = if acme.domains == [ ] then "unset" else lib.head acme.domains;
|
||||
acmePem = "/var/lib/acme/${acmeName}/full.pem";
|
||||
|
||||
# Reservation name -> address, across the LANs.
|
||||
reserved = lib.foldl' (acc: l: acc // lib.mapAttrs (_: r: r.address) l.dhcp.reservations) { } lans;
|
||||
isAddress = b: builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" b != null;
|
||||
addressOf = b: if isAddress b then b else reserved.${b} or null;
|
||||
|
||||
backendPort = lb: if lb.backendPort != null then lb.backendPort else lb.listen.port;
|
||||
usesAcme = lb: lb.tls == "terminate" && lb.certificate == null;
|
||||
certOf = lb: if lb.certificate != null then toString lb.certificate else acmePem;
|
||||
|
||||
# Services by port: one frontend each, the host name chooses the backend.
|
||||
ports = lib.unique (map (n: lbs.${n}.listen.port) names);
|
||||
onPort = port: lib.filter (n: lbs.${n}.listen.port == port) names;
|
||||
|
||||
hostAcl =
|
||||
lb: hosts:
|
||||
let
|
||||
list = lib.concatMapStringsSep " " (h: lib.toLower h) hosts;
|
||||
in
|
||||
if lb.tls == "passthrough" then
|
||||
"{ req_ssl_sni -i ${list} }"
|
||||
else if lb.protocol == "http" then
|
||||
"{ hdr(host),field(1,:) -i ${list} }"
|
||||
else
|
||||
"{ ssl_fc_sni -i ${list} }";
|
||||
|
||||
frontend =
|
||||
port:
|
||||
let
|
||||
members = onPort port;
|
||||
first = lbs.${lib.head members};
|
||||
certs = lib.unique (map (n: certOf lbs.${n}) (lib.filter (n: lbs.${n}.tls == "terminate") members));
|
||||
withHosts = lib.filter (n: lbs.${n}.hosts != [ ]) members;
|
||||
without = lib.filter (n: lbs.${n}.hosts == [ ]) members;
|
||||
http = first.protocol == "http";
|
||||
# (IPv4 and IPv6 apart: one dual-stack socket shows IPv4 clients as ::ffff:a.b.c.d.)
|
||||
tlsArgs = lib.optionalString (first.tls == "terminate") (
|
||||
" ssl ${lib.concatMapStringsSep " " (c: "crt ${c}") certs}${lib.optionalString http " alpn h2,http/1.1"}"
|
||||
);
|
||||
in
|
||||
''
|
||||
frontend fe_${toString port}
|
||||
mode ${first.protocol}
|
||||
bind 0.0.0.0:${toString port}${tlsArgs}
|
||||
bind :::${toString port} v6only${tlsArgs}
|
||||
${lib.optionalString (first.tls == "passthrough") ''
|
||||
tcp-request inspect-delay 5s
|
||||
tcp-request content accept if { req_ssl_hello_type 1 }
|
||||
''}${lib.concatMapStrings (n: ''
|
||||
use_backend be_${n} if ${hostAcl lbs.${n} lbs.${n}.hosts}
|
||||
'') withHosts}${lib.concatMapStrings (n: ''
|
||||
default_backend be_${n}
|
||||
'') without}
|
||||
'';
|
||||
|
||||
server =
|
||||
lb: n: b:
|
||||
let
|
||||
addr = addressOf b;
|
||||
secure = lb.backendTls.enable;
|
||||
verify =
|
||||
if lb.backendTls.verify then
|
||||
"verify required${lib.optionalString (lb.backendTls.caFile != null) " ca-file ${toString lb.backendTls.caFile}"}"
|
||||
else
|
||||
"verify none";
|
||||
# Passthrough sends the client's bytes as they are: only the checks speak TLS.
|
||||
traffic = lib.optionalString (secure && lb.tls != "passthrough") " ssl ${verify}";
|
||||
checks = " check${lib.optionalString secure " check-ssl ${verify}"}${lib.optionalString lb.proxyProtocol " check-send-proxy"}";
|
||||
proxy = lib.optionalString lb.proxyProtocol " send-proxy-v2";
|
||||
in
|
||||
" server ${lib.replaceStrings [ "." ] [ "-" ] b} ${addr}:${toString (backendPort lb)}${checks}${traffic}${proxy}";
|
||||
|
||||
backend = n: ''
|
||||
backend be_${n}
|
||||
mode ${lbs.${n}.protocol}
|
||||
balance ${lbs.${n}.balance}
|
||||
timeout check ${lbs.${n}.check.timeout}
|
||||
default-server inter ${lbs.${n}.check.interval} fall ${toString lbs.${n}.check.fall} rise ${toString lbs.${n}.check.rise}
|
||||
${lib.optionalString lbs.${n}.check.useHttp ''
|
||||
option httpchk
|
||||
http-check send meth GET uri ${lbs.${n}.check.path} ver HTTP/1.1 hdr Host ${
|
||||
if lbs.${n}.hosts == [ ] then "localhost" else lib.head lbs.${n}.hosts
|
||||
}
|
||||
''}${lib.optionalString (lbs.${n}.protocol == "http") ''
|
||||
option forwardfor
|
||||
''}${
|
||||
# (An unknown backend is an assertion's to report; the text must still be valid.)
|
||||
lib.concatMapStringsSep "\n" (b: server lbs.${n} n b) (lib.filter (b: addressOf b != null) lbs.${n}.backends)
|
||||
}
|
||||
'';
|
||||
|
||||
haproxyConfig = ''
|
||||
defaults
|
||||
log stdout format raw local0
|
||||
timeout connect 5s
|
||||
timeout client 1m
|
||||
timeout server 1m
|
||||
timeout check 2s
|
||||
option redispatch
|
||||
retries 2
|
||||
|
||||
${lib.concatMapStringsSep "\n" frontend ports}
|
||||
${lib.concatMapStringsSep "\n" backend names}
|
||||
'';
|
||||
in
|
||||
{
|
||||
config = lib.mkIf (cfg.enable && names != [ ]) {
|
||||
services.haproxy = {
|
||||
enable = true;
|
||||
config = haproxyConfig;
|
||||
};
|
||||
|
||||
# The router's own certificate, for services that decrypt with it.
|
||||
security.acme.certs = lib.mkIf (acme.enable && lib.any (n: usesAcme lbs.${n}) names) {
|
||||
${acmeName} = {
|
||||
group = "haproxy";
|
||||
reloadServices = [ "haproxy.service" ];
|
||||
};
|
||||
};
|
||||
|
||||
# A service's names are the router's own for the LANs it listens in.
|
||||
router.dns.hosts = lib.mkMerge (
|
||||
map (
|
||||
n:
|
||||
let
|
||||
lb = lbs.${n};
|
||||
addrs = lib.concatMap (l: lib.optional (lib.elem l.zone lb.listen.zones) l.ipv4.address) lans;
|
||||
in
|
||||
lib.mkIf (addrs != [ ]) (lib.genAttrs lb.hosts (_: lib.mkDefault addrs))
|
||||
) names
|
||||
);
|
||||
};
|
||||
}
|
||||
+218
-14
@@ -426,6 +426,224 @@ in
|
||||
);
|
||||
};
|
||||
|
||||
loadBalancers = mkOption {
|
||||
default = { };
|
||||
example = {
|
||||
api = {
|
||||
listen.port = 8443;
|
||||
listen.zones = [
|
||||
"wan"
|
||||
"lan"
|
||||
];
|
||||
tls = "terminate";
|
||||
hosts = [ "api.example.org" ];
|
||||
backends = [
|
||||
"hv1"
|
||||
"hv2"
|
||||
];
|
||||
backendTls.enable = true;
|
||||
check.path = "/healthz";
|
||||
};
|
||||
};
|
||||
description = ''
|
||||
Services that spread their connections over several hosts (HAProxy),
|
||||
keyed by name. A backend that fails its checks gets no connections
|
||||
until it passes them again. The service listens on the router, in the
|
||||
zones named in `listen.zones` (`wan` is the uplink): the router opens
|
||||
the port there, so no firewall rule is needed. Clients inside reach it
|
||||
through the router's address; `hosts` also publishes those names in the
|
||||
local DNS (to the router's LAN addresses), so that inside and outside
|
||||
use the same name. Backends are names of DHCP reservations or
|
||||
IPv4 addresses.
|
||||
|
||||
A service either decrypts TLS on the router (`tls = "terminate"`) or
|
||||
passes the connections through untouched (`"passthrough"`); the
|
||||
backend then sees the router's address, unless `proxyProtocol` hands
|
||||
it the client's. For HTTP the client's address is in `X-Forwarded-For`.
|
||||
'';
|
||||
type = types.attrsOf (
|
||||
types.submodule (
|
||||
{ config, ... }:
|
||||
{
|
||||
options = {
|
||||
listen = {
|
||||
port = mkOption {
|
||||
type = types.port;
|
||||
example = 443;
|
||||
description = ''
|
||||
TCP port the service listens on, in every zone of `zones`.
|
||||
Services may share a port when each has `hosts` and they
|
||||
agree on `tls` and `protocol` (the host name chooses).
|
||||
'';
|
||||
};
|
||||
zones = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ "wan" ];
|
||||
example = [
|
||||
"wan"
|
||||
"lan"
|
||||
];
|
||||
description = ''
|
||||
Where the service is reachable: `wan` (the uplink) and the
|
||||
zones of LANs and tunnels.
|
||||
'';
|
||||
};
|
||||
};
|
||||
tls = mkOption {
|
||||
type = types.enum [
|
||||
"terminate"
|
||||
"passthrough"
|
||||
"none"
|
||||
];
|
||||
default = "terminate";
|
||||
description = ''
|
||||
`terminate`: the router decrypts (its certificate: see
|
||||
`certificate`) and sends on to the backends, encrypted again
|
||||
if `backendTls.enable`. `passthrough`: the connection goes to
|
||||
the backend as it is; the router only reads the requested
|
||||
host name, and the backend has the certificate. `none`: no
|
||||
TLS between the client and the router.
|
||||
'';
|
||||
};
|
||||
protocol = mkOption {
|
||||
type = types.enum [
|
||||
"http"
|
||||
"tcp"
|
||||
];
|
||||
default = if config.tls == "passthrough" then "tcp" else "http";
|
||||
defaultText = ''"tcp" with passthrough, else "http"'';
|
||||
description = ''
|
||||
`http`: the router reads the requests (adds `X-Forwarded-For`,
|
||||
routes by `Host`). `tcp`: bytes only. Passthrough is always `tcp`.
|
||||
'';
|
||||
};
|
||||
certificate = mkOption {
|
||||
type = types.nullOr types.path;
|
||||
default = null;
|
||||
example = "/var/lib/router/lb-api.pem";
|
||||
description = ''
|
||||
`terminate`: a file with the certificate chain and the
|
||||
private key (PEM). null: the router's own certificate
|
||||
(`router.acme`), which then has to cover `hosts`.
|
||||
'';
|
||||
};
|
||||
hosts = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
example = [ "api.example.org" ];
|
||||
description = ''
|
||||
The names the service answers to: the request's `Host` (or the
|
||||
requested TLS name) chooses the service on a shared port, and
|
||||
a name that is not on a shared port still has to match. The
|
||||
names are published in the local DNS for the LANs the service
|
||||
listens in. Empty: the service takes everything on its port.
|
||||
'';
|
||||
};
|
||||
backends = mkOption {
|
||||
type = types.listOf types.str;
|
||||
example = [
|
||||
"hv1"
|
||||
"hv2"
|
||||
];
|
||||
description = "Names of DHCP reservations, or IPv4 addresses.";
|
||||
};
|
||||
backendPort = mkOption {
|
||||
type = types.nullOr types.port;
|
||||
default = null;
|
||||
description = "The port on the backends; null: the same as `listen.port`.";
|
||||
};
|
||||
backendTls = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = config.tls == "passthrough";
|
||||
defaultText = "true with passthrough, else false";
|
||||
description = ''
|
||||
The backends speak TLS. With `terminate` or `none` the
|
||||
router encrypts toward them; with `passthrough` it only
|
||||
makes its health checks encrypted.
|
||||
'';
|
||||
};
|
||||
verify = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Check the backends' certificates (against `caFile`, or the
|
||||
system's) when connecting to them and when checking them.
|
||||
Off by default: backends often have a self-signed one.
|
||||
'';
|
||||
};
|
||||
caFile = mkOption {
|
||||
type = types.nullOr types.path;
|
||||
default = null;
|
||||
description = "Certificate authority of the backends, for `verify`.";
|
||||
};
|
||||
};
|
||||
balance = mkOption {
|
||||
type = types.enum [
|
||||
"roundrobin"
|
||||
"leastconn"
|
||||
"source"
|
||||
];
|
||||
default = "roundrobin";
|
||||
description = ''
|
||||
How a new connection picks a backend: in turn, the one with
|
||||
the fewest connections, or by the client's address (the same
|
||||
client keeps its backend while the backends stay as they are).
|
||||
'';
|
||||
};
|
||||
proxyProtocol = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Send the client's address to the backends in a PROXY protocol
|
||||
(v2) header, for passthrough or `tcp`. The backends must expect
|
||||
it, or every connection fails.
|
||||
'';
|
||||
};
|
||||
check = {
|
||||
path = mkOption {
|
||||
type = types.str;
|
||||
default = "/";
|
||||
example = "/healthz";
|
||||
description = ''
|
||||
An HTTP GET of this path decides whether a backend is up
|
||||
(a 2xx or 3xx answer), also for TLS backends and in
|
||||
passthrough. With the first of `hosts` as `Host`, else
|
||||
`localhost`.
|
||||
'';
|
||||
};
|
||||
useHttp = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "Check with an HTTP request; false: only that the port accepts connections.";
|
||||
};
|
||||
interval = mkOption {
|
||||
type = types.strMatching "[0-9]+(ms|s|m)";
|
||||
default = "2s";
|
||||
description = "Time between two checks of a backend.";
|
||||
};
|
||||
timeout = mkOption {
|
||||
type = types.strMatching "[0-9]+(ms|s|m)";
|
||||
default = "2s";
|
||||
description = "How long a check may take before it counts as failed.";
|
||||
};
|
||||
fall = mkOption {
|
||||
type = types.ints.positive;
|
||||
default = 3;
|
||||
description = "Failed checks in a row that take a backend out.";
|
||||
};
|
||||
rise = mkOption {
|
||||
type = types.ints.positive;
|
||||
default = 2;
|
||||
description = "Passed checks in a row that bring it back.";
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
wireguardEndpointRefresh = mkOption {
|
||||
type = types.nullOr (types.strMatching "[0-9]+(s|min|h)");
|
||||
default = "1min";
|
||||
@@ -440,20 +658,6 @@ in
|
||||
'';
|
||||
};
|
||||
|
||||
update.repository = mkOption {
|
||||
type = types.nullOr (types.strMatching "https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?");
|
||||
default = null;
|
||||
example = "https://git.example.org/me/nixos-router";
|
||||
description = ''
|
||||
A 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 settings are migrated and the new version must be
|
||||
confirmed. The repository is trusted (TLS and the tag), nothing is
|
||||
signed on this path. null: updates come from bundles and update servers.
|
||||
'';
|
||||
};
|
||||
|
||||
update.channel = mkOption {
|
||||
type = types.nullOr (types.strMatching "unstable|[0-9]{2}\\.[0-9]{2}");
|
||||
default = null;
|
||||
|
||||
+18
-113
@@ -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 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 "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() { 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
|
||||
@@ -164,44 +112,9 @@ 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 "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"
|
||||
|
||||
@@ -213,7 +126,6 @@ let
|
||||
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")
|
||||
@@ -268,6 +180,19 @@ in
|
||||
default = null;
|
||||
description = "Version, serial, revision and settings schema of this nixos-router (`/etc/router-release`).";
|
||||
};
|
||||
routerUpdate.repository = lib.mkOption {
|
||||
type = lib.types.nullOr (lib.types.strMatching "https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?");
|
||||
default = "https://git.stinnesbeck.com/nils/nixos-router";
|
||||
example = "https://git.example.org/me/nixos-router";
|
||||
description = ''
|
||||
The public git repository of nixos-router whose tags `vX.Y.Z` are
|
||||
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 {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [ ];
|
||||
@@ -284,6 +209,8 @@ in
|
||||
if config.routerSettings.release == null then { } else config.routerSettings.release
|
||||
);
|
||||
environment.etc."router-update-keys".text = lib.concatLines keys;
|
||||
# For the web UI.
|
||||
environment.etc."router-update-repository".text = toString config.routerUpdate.repository;
|
||||
environment.systemPackages = [
|
||||
update
|
||||
restore
|
||||
@@ -305,28 +232,6 @@ in
|
||||
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;
|
||||
|
||||
+148
-26
@@ -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
|
||||
local packages_same=true router_json=null tags
|
||||
newest=""
|
||||
if [ -n "$channel" ]; then
|
||||
newest=$(newest_rev)
|
||||
if [ "$newest" = "$running_rev" ]; then same=true; else same=false; fi
|
||||
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
|
||||
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")"
|
||||
if [ "$same" = true ]; then echo "up to date"; else echo "a newer revision is available"; fi
|
||||
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,17 +224,63 @@ 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
|
||||
# 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}
|
||||
echo "router-upgrade: locking nixpkgs to $(short "$newest")"
|
||||
nix flake lock --override-input nixos-router/nixpkgs "$ref" "path:${dir}/flake"
|
||||
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
|
||||
@@ -189,6 +288,7 @@ let
|
||||
*\?*) 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"
|
||||
# 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";
|
||||
};
|
||||
};
|
||||
|
||||
@@ -319,6 +319,8 @@ type dashboard struct {
|
||||
Events []Event
|
||||
Charts []Chart
|
||||
Prefs Prefs
|
||||
Version string // the installed release of nixos-router
|
||||
NixOS string // the NixOS it runs on
|
||||
}
|
||||
|
||||
func (a *app) dashboardData(rangeName string) dashboard {
|
||||
@@ -326,7 +328,8 @@ func (a *app) dashboardData(rangeName string) dashboard {
|
||||
now := time.Now()
|
||||
s, _ := loadSettings(a.sys.settingsPath())
|
||||
f := s.form()
|
||||
d := dashboard{Range: rg.Name, Interval: 5, Snap: a.metrics.Snapshot(), Prefs: a.sys.loadPrefs()}
|
||||
d := dashboard{Range: rg.Name, Interval: 5, Snap: a.metrics.Snapshot(), Prefs: a.sys.loadPrefs(),
|
||||
Version: a.sys.installedRelease().Version, NixOS: a.sys.runningVersion()}
|
||||
// Newest first, the last few.
|
||||
ev := d.Snap.Uplink.Events
|
||||
d.Events = make([]Event, 0, 10)
|
||||
|
||||
@@ -155,6 +155,25 @@ func TestDashboardRenders(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDashboardNamesTheVersion(t *testing.T) {
|
||||
a, sys := newTestApp(t)
|
||||
dir := t.TempDir()
|
||||
sys.ReleaseFile = filepath.Join(dir, "router-release")
|
||||
sys.VersionFile = filepath.Join(dir, "nixos-version")
|
||||
os.WriteFile(sys.ReleaseFile, []byte(`{"version":"4.5.6"}`), 0o600)
|
||||
os.WriteFile(sys.VersionFile, []byte("26.11.20261113.d5cc683\n"), 0o600)
|
||||
a.sys = sys
|
||||
h := a.routes()
|
||||
cookie := login(t, h)
|
||||
// The page and the fragment that refreshes it say what runs.
|
||||
for _, path := range []string{"/", "/dashboard?range=24h"} {
|
||||
body := do(h, "GET", path, nil, cookie).Body.String()
|
||||
if !strings.Contains(body, "nixos-router 4.5.6") || !strings.Contains(body, "NixOS 26.11.20261113.d5cc683") {
|
||||
t.Errorf("%s does not name the version:\n%s", path, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackup(t *testing.T) {
|
||||
a, sys := newTestApp(t)
|
||||
h := a.routes()
|
||||
|
||||
@@ -1,115 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Updates from a git repository (router.update.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.
|
||||
// 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.
|
||||
|
||||
var (
|
||||
// The same shape the option accepts: no credentials, no query.
|
||||
repositoryRe = regexp.MustCompile(`^https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?$`)
|
||||
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"`
|
||||
// repository is where releases come from ("" if the router has none).
|
||||
func (s System) repository() string {
|
||||
path := s.RepositoryFile
|
||||
if path == "" {
|
||||
path = "/etc/router-update-repository"
|
||||
}
|
||||
data, _ := os.ReadFile(path)
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func (s Settings) repository() string { return str(s, "router", "update", "repository") }
|
||||
|
||||
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(repository string) *GitCheck {
|
||||
var c GitCheck
|
||||
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 {
|
||||
s, err := loadSettings(a.sys.settingsPath())
|
||||
if err != nil {
|
||||
var c UpgradeCheck
|
||||
if !readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) {
|
||||
return ""
|
||||
}
|
||||
if c := a.gitCheck(s.repository()); c != nil && c.Newer {
|
||||
return c.Newest.Version
|
||||
if r := c.Router; r != nil && r.Newer && r.Installed == a.sys.installedRelease().Version {
|
||||
return r.Newest.Version
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (a *app) updateSaveRepository(w http.ResponseWriter, r *http.Request, _ session) {
|
||||
v := strings.TrimRight(strings.TrimSpace(r.PostFormValue("repository")), "/")
|
||||
if !r.PostForm.Has("repository") {
|
||||
a.updateBack(w, r, "Not saved: no address was sent.")
|
||||
return
|
||||
}
|
||||
if v != "" && !repositoryRe.MatchString(v) {
|
||||
a.updateBack(w, r, "Not saved: an http:// or https:// address of a public repository, without credentials or a query.")
|
||||
return
|
||||
}
|
||||
if err := a.sys.setUpdateField("repository", v); err != nil {
|
||||
a.updateBack(w, r, "Not saved: "+err.Error())
|
||||
return
|
||||
}
|
||||
a.updateBack(w, r, "Saved.")
|
||||
}
|
||||
|
||||
func (a *app) updateGitCheck(w http.ResponseWriter, r *http.Request, _ session) {
|
||||
s, err := loadSettings(a.sys.settingsPath())
|
||||
if err != nil || s.repository() == "" {
|
||||
a.updateBack(w, r, "Set the repository first.")
|
||||
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
|
||||
}
|
||||
s, err := loadSettings(a.sys.settingsPath())
|
||||
if err != nil || s.repository() == "" {
|
||||
a.updateBack(w, r, "Set the repository first.")
|
||||
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.")
|
||||
}
|
||||
|
||||
@@ -9,94 +9,67 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdatesFromGit(t *testing.T) {
|
||||
const testRepository = "https://git.example.org/me/nixos-router"
|
||||
|
||||
// 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)
|
||||
sys.ReleaseFile = filepath.Join(t.TempDir(), "router-release")
|
||||
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")
|
||||
|
||||
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 strings.Contains(body, `name="repository"`) {
|
||||
t.Fatalf("the page has a field for the 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)
|
||||
}
|
||||
|
||||
// The repository: an address of a public repository, nothing else.
|
||||
for _, bad := range []string{"git@git.example.org:me/r.git", "https://user:pw@git.example.org/r", "https://git.example.org/r?x=1", "file:///etc", "https://git.example.org/a b"} {
|
||||
if loc := post("/update/repository", url.Values{"repository": {bad}}); !strings.Contains(loc, "Not+saved") {
|
||||
t.Errorf("%q was accepted: %s", bad, loc)
|
||||
}
|
||||
}
|
||||
if loc := post("/update/gitcheck", url.Values{}); !strings.Contains(loc, "Set+the+repository") || len(started) != 0 {
|
||||
t.Fatalf("a check without a repository: %q %v", loc, started)
|
||||
}
|
||||
if loc := post("/update/gitinstall", url.Values{"tag": {"v1.1.0"}}); !strings.Contains(loc, "Set+the+repository") {
|
||||
t.Fatalf("an install without a repository: %q", loc)
|
||||
}
|
||||
post("/update/repository", url.Values{"repository": {"https://git.example.org/me/nixos-router/"}})
|
||||
s, _ := loadSettings(sys.settingsPath())
|
||||
if got := s.repository(); got != "https://git.example.org/me/nixos-router" {
|
||||
t.Fatalf("repository: %q", got)
|
||||
}
|
||||
// It takes effect when updating, so it is no unapplied change.
|
||||
if c, err := loadSettings(sys.confirmedPath()); err == nil && c.repository() != "" {
|
||||
t.Logf("confirmed settings carry it: %q", c.repository())
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
if body := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(body, "Not looked yet") {
|
||||
t.Fatalf("a result before any look:\n%s", body)
|
||||
}
|
||||
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)
|
||||
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("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)
|
||||
}
|
||||
write("https://git.example.org/me/nixos-router", "0.9.0", true)
|
||||
write(testRepository, "0.9.0", true)
|
||||
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") {
|
||||
t.Fatalf("a notice from before the last update:\n%s", body)
|
||||
}
|
||||
write("https://git.example.org/me/nixos-router", "1.0.0", true)
|
||||
write(testRepository, "1.0.0", true)
|
||||
for _, path := range []string{"/", "/update"} {
|
||||
if body := do(h, "GET", path, nil, cookie).Body.String(); !strings.Contains(body, "1.1.0") || (path == "/" && !strings.Contains(body, "nixos-router 1.1.0 is out")) {
|
||||
t.Fatalf("%s lacks the release:\n%s", path, body)
|
||||
}
|
||||
}
|
||||
write("https://git.example.org/me/nixos-router", "1.0.0", false)
|
||||
write(testRepository, "1.0.0", false)
|
||||
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "nixos-router 1.1.0 is out") {
|
||||
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)
|
||||
// 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"`, "<td>nixos-router</td>", "<td>curl</td>", "Upgrade nixos-router to 1.1.0 and"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("the preview lacks %q:\n%s", want, body)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +204,7 @@ func syncDynamic(ctl controller, published, want map[string]DynRecord, fresh boo
|
||||
|
||||
// dynStatus is what the daemon leaves for the web UI.
|
||||
type dynStatus struct {
|
||||
Pid string `json:"pid,omitempty"` // of the Unbound that has Published
|
||||
Published []DynRecord `json:"published"`
|
||||
Skipped []DynSkip `json:"skipped"`
|
||||
Updated time.Time `json:"updated"`
|
||||
@@ -264,6 +265,18 @@ func parseUnboundPID(status string) (string, error) {
|
||||
return "", fmt.Errorf("no pid in unbound-control status")
|
||||
}
|
||||
|
||||
// stillThere is what an earlier run published that the running Unbound still
|
||||
// has: all of it if it is the same Unbound, nothing if it is a new one. A new
|
||||
// Unbound has none of it, and removing it by name would remove what the
|
||||
// configuration publishes under that name now (a client name that became a
|
||||
// DHCP reservation: the restart that brought the reservation is this case).
|
||||
func stillThere(published map[string]DynRecord, publishedPid, currentPid string) map[string]DynRecord {
|
||||
if publishedPid != "" && publishedPid == currentPid {
|
||||
return published
|
||||
}
|
||||
return map[string]DynRecord{}
|
||||
}
|
||||
|
||||
// leasesDNS is `router-webui leases-dns`.
|
||||
func leasesDNS(args []string) {
|
||||
fs := flag.NewFlagSet("leases-dns", flag.ExitOnError)
|
||||
@@ -286,7 +299,9 @@ func leasesDNS(args []string) {
|
||||
// What a previous run published is removed first: the daemon may have
|
||||
// been restarted while Unbound kept its data.
|
||||
published := map[string]DynRecord{}
|
||||
publishedPid := ""
|
||||
if st, ok := readDynStatus(*run); ok {
|
||||
publishedPid = st.Pid
|
||||
for _, r := range st.Published {
|
||||
published[r.Name] = r
|
||||
}
|
||||
@@ -302,6 +317,10 @@ func leasesDNS(args []string) {
|
||||
} else {
|
||||
if cur != pid {
|
||||
fresh = true // a new Unbound has none of it
|
||||
if pid != "" {
|
||||
publishedPid = pid
|
||||
}
|
||||
published = stillThere(published, publishedPid, cur)
|
||||
}
|
||||
var now map[string]DynRecord
|
||||
if now, err = syncDynamic(ctl, published, want, fresh); err == nil {
|
||||
@@ -309,7 +328,7 @@ func leasesDNS(args []string) {
|
||||
}
|
||||
published = now
|
||||
}
|
||||
status := dynStatus{Published: recordsOf(published), Skipped: skipped, Updated: time.Now()}
|
||||
status := dynStatus{Pid: pid, Published: recordsOf(published), Skipped: skipped, Updated: time.Now()}
|
||||
if err != nil {
|
||||
status.Error = err.Error()
|
||||
if status.Error != lastErr {
|
||||
|
||||
@@ -150,6 +150,28 @@ func TestSyncDynamic(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A client name that became a DHCP reservation: the restart that brought the
|
||||
// reservation must not remove the configuration's record by removing what an
|
||||
// earlier Unbound was given.
|
||||
func TestNewUnboundForgetsWhatTheOldOneHad(t *testing.T) {
|
||||
hv1 := DynRecord{Name: "hv1.home.example.org", Address: "192.168.1.21"}
|
||||
old := map[string]DynRecord{hv1.Name: hv1}
|
||||
if got := stillThere(old, "100", "200"); len(got) != 0 {
|
||||
t.Errorf("a new Unbound still has %v", got)
|
||||
}
|
||||
if got := stillThere(old, "", "200"); len(got) != 0 {
|
||||
t.Errorf("an unknown Unbound still has %v", got)
|
||||
}
|
||||
if got := stillThere(old, "200", "200"); len(got) != 1 {
|
||||
t.Errorf("the same Unbound lost %v", got)
|
||||
}
|
||||
// So the fresh sync sends nothing for it: the static record stays.
|
||||
ctl := &fakeCtl{}
|
||||
if _, err := syncDynamic(ctl, stillThere(old, "100", "200"), nil, true); err != nil || len(ctl.cmds) != 0 {
|
||||
t.Errorf("removed after a restart: %v %v", ctl.cmds, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUnboundPID(t *testing.T) {
|
||||
out := "version: 1.26.1\nverbosity: 1\nthreads: 1\nuptime: 0 seconds\nunbound (pid 1458081) is running...\n"
|
||||
if pid, err := parseUnboundPID(out); err != nil || pid != "1458081" {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Load balancers (router.loadBalancers) are run by HAProxy; this page shows
|
||||
// what it says about each backend. The configuration is edited in Advanced.
|
||||
|
||||
// LBServer is one backend of a service, as HAProxy sees it.
|
||||
type LBServer struct {
|
||||
Name string
|
||||
Address string
|
||||
Status string // UP, DOWN, MAINT, NOLB, ... (HAProxy's words)
|
||||
Check string // what the last check found, e.g. "L7OK/200"
|
||||
Current int // connections now
|
||||
Total int // connections since HAProxy started
|
||||
Since int // seconds in this state
|
||||
Up bool
|
||||
}
|
||||
|
||||
// LBStatus is one service: the saved configuration and the running state.
|
||||
type LBStatus struct {
|
||||
Name string
|
||||
Port int
|
||||
Zones string
|
||||
TLS string
|
||||
Protocol string
|
||||
Hosts string
|
||||
Balance string
|
||||
Servers []LBServer
|
||||
Running bool // HAProxy knows the service
|
||||
Up bool // the service has at least one backend that is up
|
||||
}
|
||||
|
||||
func (s System) haproxySocket() string {
|
||||
if s.HAProxySocket != "" {
|
||||
return s.HAProxySocket
|
||||
}
|
||||
return "/run/haproxy/haproxy.sock"
|
||||
}
|
||||
|
||||
// haproxyCommand sends one command to HAProxy's socket and returns the answer.
|
||||
func haproxyCommand(socket, command string) (string, error) {
|
||||
c, err := net.DialTimeout("unix", socket, 2*time.Second)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
if _, err := io.WriteString(c, command+"\n"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(c, 4<<20))
|
||||
return string(data), err
|
||||
}
|
||||
|
||||
// parseServerAddresses reads `show servers state` (a version line, then a
|
||||
// "# " line naming the columns, then one line per server) into the address
|
||||
// of each server, keyed "backend/server". (The `addr` column of `show stat`
|
||||
// is empty in the CSV.)
|
||||
func parseServerAddresses(data string) map[string]string {
|
||||
out := map[string]string{}
|
||||
var col map[string]int
|
||||
for _, line := range strings.Split(data, "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) == 0 {
|
||||
continue
|
||||
}
|
||||
if f[0] == "#" {
|
||||
col = map[string]int{}
|
||||
for i, name := range f[1:] {
|
||||
col[name] = i
|
||||
}
|
||||
continue
|
||||
}
|
||||
be, sv, addr, port := col["be_name"], col["srv_name"], col["srv_addr"], col["srv_port"]
|
||||
if col == nil || len(f) <= max(be, sv, addr, port) {
|
||||
continue
|
||||
}
|
||||
out[f[be]+"/"+f[sv]] = f[addr] + ":" + f[port]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parseHAProxyStat reads the CSV of `show stat` (its first line names the
|
||||
// columns) into the servers of each backend, keyed by the proxy name.
|
||||
func parseHAProxyStat(data string) (map[string][]LBServer, error) {
|
||||
data = strings.TrimPrefix(strings.TrimSpace(data), "# ")
|
||||
r := csv.NewReader(strings.NewReader(data))
|
||||
r.FieldsPerRecord = -1
|
||||
rows, err := r.ReadAll()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil, errors.New("HAProxy answered nothing")
|
||||
}
|
||||
col := map[string]int{}
|
||||
for i, name := range rows[0] {
|
||||
col[name] = i
|
||||
}
|
||||
for _, need := range []string{"pxname", "svname", "status"} {
|
||||
if _, ok := col[need]; !ok {
|
||||
return nil, fmt.Errorf("the statistics have no %q column", need)
|
||||
}
|
||||
}
|
||||
get := func(row []string, name string) string {
|
||||
if i, ok := col[name]; ok && i < len(row) {
|
||||
return row[i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
num := func(row []string, name string) int {
|
||||
n, _ := strconv.Atoi(get(row, name))
|
||||
return n
|
||||
}
|
||||
out := map[string][]LBServer{}
|
||||
for _, row := range rows[1:] {
|
||||
px, sv := get(row, "pxname"), get(row, "svname")
|
||||
if !strings.HasPrefix(px, "be_") || sv == "" {
|
||||
continue
|
||||
}
|
||||
status := get(row, "status")
|
||||
srv := LBServer{
|
||||
Name: sv, Address: get(row, "addr"), Status: status,
|
||||
Current: num(row, "scur"), Total: num(row, "stot"), Since: num(row, "lastchg"),
|
||||
Up: strings.HasPrefix(status, "UP") || status == "OPEN",
|
||||
}
|
||||
if cs := get(row, "check_status"); cs != "" {
|
||||
srv.Check = cs
|
||||
if code := get(row, "check_code"); code != "" {
|
||||
srv.Check += "/" + code
|
||||
}
|
||||
}
|
||||
out[strings.TrimPrefix(px, "be_")] = append(out[strings.TrimPrefix(px, "be_")], srv)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// loadBalancers is the saved configuration with HAProxy's state beside it.
|
||||
func (a *app) loadBalancers(s Settings) ([]LBStatus, string) {
|
||||
router, _ := s["router"].(map[string]any)
|
||||
cfg, _ := router["loadBalancers"].(map[string]any)
|
||||
var out []LBStatus
|
||||
for name, v := range cfg {
|
||||
lb, _ := v.(map[string]any)
|
||||
st := LBStatus{Name: name, TLS: str(lb, "tls"), Protocol: str(lb, "protocol"), Balance: str(lb, "balance"),
|
||||
Hosts: strings.Join(stringList(lb, "hosts"), ", ")}
|
||||
if st.TLS == "" {
|
||||
st.TLS = "terminate"
|
||||
}
|
||||
if st.Balance == "" {
|
||||
st.Balance = "roundrobin"
|
||||
}
|
||||
if st.Protocol == "" {
|
||||
st.Protocol = map[bool]string{true: "tcp", false: "http"}[st.TLS == "passthrough"]
|
||||
}
|
||||
listen, _ := lb["listen"].(map[string]any)
|
||||
if p, ok := listen["port"].(float64); ok {
|
||||
st.Port = int(p)
|
||||
}
|
||||
zones := stringList(listen, "zones")
|
||||
if len(zones) == 0 {
|
||||
zones = []string{"wan"}
|
||||
}
|
||||
st.Zones = strings.Join(zones, ", ")
|
||||
out = append(out, st)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
if len(out) == 0 {
|
||||
return nil, ""
|
||||
}
|
||||
raw, err := haproxyCommand(a.sys.haproxySocket(), "show stat")
|
||||
if err != nil {
|
||||
return out, "HAProxy is not running: the services are saved but not applied yet, or it failed to start."
|
||||
}
|
||||
servers, err := parseHAProxyStat(raw)
|
||||
if err != nil {
|
||||
return out, err.Error()
|
||||
}
|
||||
state, _ := haproxyCommand(a.sys.haproxySocket(), "show servers state")
|
||||
addrs := parseServerAddresses(state)
|
||||
for i := range out {
|
||||
if sv, ok := servers[out[i].Name]; ok {
|
||||
out[i].Running = true
|
||||
for _, x := range sv {
|
||||
if x.Name == "BACKEND" {
|
||||
out[i].Up = x.Up
|
||||
} else if x.Name != "FRONTEND" {
|
||||
if x.Address == "" {
|
||||
x.Address = addrs["be_"+out[i].Name+"/"+x.Name]
|
||||
}
|
||||
out[i].Servers = append(out[i].Servers, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, ""
|
||||
}
|
||||
|
||||
func (a *app) loadBalancersPage(w http.ResponseWriter, r *http.Request, sess session) {
|
||||
p := page{Title: "Load balancers", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg"), Live: 10}
|
||||
s, err := loadSettings(a.sys.settingsPath())
|
||||
if err != nil {
|
||||
p.Error = err.Error()
|
||||
a.render(w, "loadbalancers", p)
|
||||
return
|
||||
}
|
||||
services, note := a.loadBalancers(s)
|
||||
p.Data = struct {
|
||||
Services []LBStatus
|
||||
Note string
|
||||
}{services, note}
|
||||
a.render(w, "loadbalancers", p)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// What `show stat` says for two services (columns cut down to the ones that matter).
|
||||
const sampleStat = `# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,addr
|
||||
fe_8443,FRONTEND,,,0,5,,12,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,1,,,,,
|
||||
be_api,hv1,0,0,2,3,,7,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,300,0,,1,3,1,,7,,2,0,,1,L7OK,200,3,
|
||||
be_api,hv2,0,0,0,0,,5,0,0,,0,,0,0,0,0,DOWN,1,1,0,3,1,40,40,,1,3,2,,5,,2,0,,1,L7STS,503,2,
|
||||
be_api,BACKEND,0,0,2,3,,12,0,0,0,0,,0,0,0,0,UP,1,1,0,,0,300,0,,1,3,0,,12,,1,0,,1,,,,
|
||||
be_raw,hv1,0,0,0,0,,0,0,0,,0,,0,0,0,0,DOWN,1,1,0,5,1,10,10,,1,4,1,,0,,2,0,,0,L4CON,,0,
|
||||
be_raw,BACKEND,0,0,0,0,,0,0,0,0,0,,0,0,0,0,DOWN,1,1,0,,1,10,10,,1,4,0,,0,,1,0,,0,,,,
|
||||
`
|
||||
|
||||
func TestParseHAProxyStat(t *testing.T) {
|
||||
got, err := parseHAProxyStat(sampleStat)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
api := got["api"]
|
||||
if len(api) != 3 || api[0].Name != "hv1" || !api[0].Up || api[0].Address != "" ||
|
||||
api[0].Check != "L7OK/200" || api[0].Current != 2 || api[0].Total != 7 || api[0].Since != 300 {
|
||||
t.Fatalf("api: %+v", api)
|
||||
}
|
||||
if api[1].Up || api[1].Status != "DOWN" || api[1].Check != "L7STS/503" {
|
||||
t.Fatalf("a down backend: %+v", api[1])
|
||||
}
|
||||
if _, ok := got["8443"]; ok || len(got["raw"]) != 2 {
|
||||
t.Fatalf("frontends or raw: %+v", got)
|
||||
}
|
||||
if _, err := parseHAProxyStat("# a,b\n1,2\n"); err == nil {
|
||||
t.Error("statistics without the columns were accepted")
|
||||
}
|
||||
if _, err := parseHAProxyStat(""); err == nil {
|
||||
t.Error("nothing was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// The addresses are not in the CSV; `show servers state` has them.
|
||||
const sampleState = `1
|
||||
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_port
|
||||
3 be_api 1 hv1 192.168.10.21 2 8443
|
||||
3 be_api 2 hv2 192.168.10.22 0 8443
|
||||
4 be_raw 1 hv1 192.168.10.21 0 8443
|
||||
`
|
||||
|
||||
func TestParseServerAddresses(t *testing.T) {
|
||||
got := parseServerAddresses(sampleState)
|
||||
if got["be_api/hv2"] != "192.168.10.22:8443" || got["be_raw/hv1"] != "192.168.10.21:8443" || len(got) != 3 {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if len(parseServerAddresses("")) != 0 || len(parseServerAddresses("1\n3 be_api 1 hv1 x\n")) != 0 {
|
||||
t.Error("addresses out of nothing")
|
||||
}
|
||||
}
|
||||
|
||||
// serveStat answers `show stat` (and `show servers state`) on a socket, like HAProxy.
|
||||
func serveStat(t *testing.T, path, answer string) {
|
||||
t.Helper()
|
||||
l, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { l.Close() })
|
||||
go func() {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 64)
|
||||
n, _ := c.Read(buf)
|
||||
if strings.HasPrefix(string(buf[:n]), "show servers state") {
|
||||
c.Write([]byte(sampleState))
|
||||
} else {
|
||||
c.Write([]byte(answer))
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func TestLoadBalancersPage(t *testing.T) {
|
||||
a, sys := newTestApp(t)
|
||||
// (A short path: a unix socket's name is limited.)
|
||||
sys.HAProxySocket = filepath.Join(os.TempDir(), "lb-test-"+filepath.Base(t.TempDir())+".sock")
|
||||
a.sys = sys
|
||||
h := a.routes()
|
||||
cookie := login(t, h)
|
||||
menu := do(h, "GET", "/", nil, cookie).Body.String()
|
||||
if !strings.Contains(menu, `href="/loadbalancers"`) {
|
||||
t.Fatalf("no menu entry:\n%s", menu)
|
||||
}
|
||||
|
||||
// Nothing configured: the page says how.
|
||||
body := do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
|
||||
if !strings.Contains(body, "No load balancer is set up") || !strings.Contains(body, "router.loadBalancers") {
|
||||
t.Fatalf("empty page:\n%s", body)
|
||||
}
|
||||
|
||||
settings := `{"system":{"hostName":"router","stateVersion":"26.11"},"router":{"loadBalancers":{
|
||||
"api":{"listen":{"port":8443,"zones":["wan","lan"]},"hosts":["api.example.org"],"backends":["hv1","hv2"]},
|
||||
"raw":{"listen":{"port":9443},"tls":"passthrough","backends":["hv1"]}}}}`
|
||||
os.WriteFile(sys.settingsPath(), []byte(settings), 0o600)
|
||||
|
||||
// Saved, HAProxy not running: say so, show the configuration.
|
||||
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
|
||||
for _, want := range []string{"HAProxy is not running", "<h2>api", "port 8443 in wan, lan", "api.example.org", "<h2>raw", "passed through", "roundrobin"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("without HAProxy the page lacks %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, `class="badge`) {
|
||||
t.Errorf("a status badge without knowing:\n%s", body)
|
||||
}
|
||||
|
||||
// Running: one service up (one backend down), one down.
|
||||
serveStat(t, sys.HAProxySocket, sampleStat)
|
||||
body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String()
|
||||
for _, want := range []string{"192.168.10.21:8443", "L7OK/200", "L7STS/503", "badge ok", "badge bad", "7 in all", "300 s", `data-live="10"`} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("the page lacks %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, "HAProxy is not running") {
|
||||
t.Errorf("claims HAProxy is down:\n%s", body)
|
||||
}
|
||||
|
||||
// A service HAProxy does not know yet is "not applied".
|
||||
os.WriteFile(sys.settingsPath(), []byte(strings.Replace(settings, `"raw"`, `"new"`, 1)), 0o600)
|
||||
if body = do(h, "GET", "/loadbalancers", nil, cookie).Body.String(); !strings.Contains(body, `badge">not applied`) {
|
||||
t.Errorf("a new service is not marked:\n%s", body)
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ func newApp(sys System, metrics *Collector, dev bool) *app {
|
||||
func (a *app) parseTemplates() (map[string]*template.Template, error) {
|
||||
files := map[string][]string{"overview": {"templates/dashboard.html"}}
|
||||
pages := map[string]*template.Template{}
|
||||
for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} {
|
||||
for _, page := range []string{"login", "overview", "network", "dhcp", "dns", "wireguard", "firewall", "loadbalancers", "ddns", "dnsproviders", "certificate", "exporter", "advanced", "update", "tokens", "changes"} {
|
||||
t, err := template.New("layout.html").Funcs(a.funcs).
|
||||
ParseFS(assets, append([]string{"templates/layout.html", "templates/" + page + ".html"}, files[page]...)...)
|
||||
if err != nil {
|
||||
@@ -328,6 +328,7 @@ func (a *app) routes() http.Handler {
|
||||
mux.HandleFunc("POST /dnsproviders", a.auth(a.providersSave))
|
||||
mux.HandleFunc("GET /certificate", a.auth(a.certificatePage))
|
||||
mux.HandleFunc("POST /certificate", a.auth(a.certificateSave))
|
||||
mux.HandleFunc("GET /loadbalancers", a.auth(a.loadBalancersPage))
|
||||
mux.HandleFunc("GET /prometheus", a.auth(a.exporterPage))
|
||||
mux.HandleFunc("POST /prometheus", a.auth(a.exporterSave))
|
||||
mux.HandleFunc("GET /firewall", a.auth(a.firewallPage))
|
||||
@@ -338,12 +339,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/repository", a.auth(a.updateSaveRepository))
|
||||
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))
|
||||
|
||||
@@ -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; }
|
||||
@@ -160,6 +161,7 @@ pre code { background: none; padding: 0; }
|
||||
.muted { color: var(--muted); }
|
||||
.bad { color: var(--bad); }
|
||||
.ok { color: var(--good); }
|
||||
.badge { font-size: .75em; font-weight: 600; padding: .1em .55em; border: 1px solid currentColor; border-radius: 1em; vertical-align: middle; }
|
||||
|
||||
body.bare { padding-left: 0; }
|
||||
.bare header { position: static; width: auto; flex-direction: row; background: none; padding: 1rem 1.25rem; }
|
||||
|
||||
@@ -21,10 +21,14 @@ type System struct {
|
||||
StateDir string // /var/lib/router: secrets, UI state
|
||||
// ReleaseFile describes the installed nixos-router; /etc/router-release if empty.
|
||||
ReleaseFile string
|
||||
// RepositoryFile holds the git repository releases come from; /etc/router-update-repository if empty.
|
||||
RepositoryFile string
|
||||
// VersionFile holds the running NixOS version; /run/current-system/nixos-version if empty.
|
||||
VersionFile string
|
||||
// LeasesDNSDir is where leases-dns leaves its status; /run/router-leases-dns if empty.
|
||||
LeasesDNSDir string
|
||||
// HAProxySocket is where the load balancers' statistics are; /run/haproxy/haproxy.sock if empty.
|
||||
HAProxySocket string
|
||||
ACMEDir string // where the ACME client keeps the web UI's certificate (fullchain.pem, key.pem), if any
|
||||
}
|
||||
|
||||
@@ -47,7 +51,8 @@ func command(name string, args ...string) (string, error) {
|
||||
return strings.TrimSpace(string(out)), err
|
||||
}
|
||||
|
||||
func unitProperty(unit, prop string) string {
|
||||
// unitProperty is a property of a systemd unit (replaced in tests).
|
||||
var unitProperty = func(unit, prop string) string {
|
||||
out, _ := command("systemctl", "show", "--value", "-p", prop, unit)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
<section class="card">
|
||||
<h2>System</h2>
|
||||
<dl>
|
||||
{{if $d.Version}}<dt>Version</dt><dd>nixos-router {{$d.Version}}{{if $d.NixOS}} <span class="muted">on NixOS {{$d.NixOS}}</span>{{end}}</dd>{{end}}
|
||||
<dt>Uptime</dt><dd>{{age $sys.Uptime}}</dd>
|
||||
{{if $sys.Kernel}}<dt>Kernel</dt><dd>{{$sys.Kernel}}{{if $sys.KernelNext}} <span class="bad">reboot to run {{$sys.KernelNext}}</span> <button type="button" class="link" data-dialog="Reboot the router now? Routing stops for a minute or two." data-dialog-ok="Reboot" data-post="/reboot">Reboot</button>{{end}}</dd>{{end}}
|
||||
{{if $sys.BootPending}}<dt>Reboot</dt><dd><span class="bad">a new configuration starts at the next reboot</span> <button type="button" class="link" data-dialog="Reboot the router now? Routing stops for a minute or two." data-dialog-ok="Reboot" data-post="/reboot">Reboot</button></dd>{{end}}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<a href="/dns"{{if eq .Title "DNS"}} aria-current="page"{{end}}>DNS</a>
|
||||
<a href="/wireguard"{{if eq .Title "WireGuard"}} aria-current="page"{{end}}>WireGuard</a>
|
||||
<a href="/firewall"{{if eq .Title "Firewall"}} aria-current="page"{{end}}>Firewall</a>
|
||||
<a href="/loadbalancers"{{if eq .Title "Load balancers"}} aria-current="page"{{end}}>Load balancers</a>
|
||||
</div>
|
||||
<div class="group"><span>Services</span>
|
||||
<a href="/ddns"{{if eq .Title "Dynamic DNS"}} aria-current="page"{{end}}>Dynamic DNS</a>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{{define "content"}}
|
||||
{{with .Data}}
|
||||
{{if .Note}}<p class="flash">{{.Note}}</p>{{end}}
|
||||
{{range .Services}}
|
||||
<section>
|
||||
<h2>{{.Name}}
|
||||
{{if not $.Data.Note}}{{if not .Running}}<span class="badge">not applied</span>{{else if .Up}}<span class="badge ok">up</span>{{else}}<span class="badge bad">down</span>{{end}}{{end}}
|
||||
</h2>
|
||||
<dl>
|
||||
<dt>Listens on</dt><dd>port {{.Port}} in {{.Zones}}</dd>
|
||||
<dt>TLS</dt><dd>{{if eq .TLS "terminate"}}decrypted on the router{{else if eq .TLS "passthrough"}}passed through{{else}}none{{end}}, {{.Protocol}}</dd>
|
||||
{{if .Hosts}}<dt>Names</dt><dd>{{.Hosts}}</dd>{{end}}
|
||||
<dt>Balancing</dt><dd>{{.Balance}}</dd>
|
||||
</dl>
|
||||
{{if .Servers}}
|
||||
<table>
|
||||
<thead><tr><th>Backend</th><th>Address</th><th>State</th><th>Last check</th><th>Connections</th><th>In this state</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Servers}}<tr>
|
||||
<td>{{.Name}}</td><td>{{.Address}}</td>
|
||||
<td>{{if .Up}}<span class="badge ok">{{.Status}}</span>{{else}}<span class="badge bad">{{.Status}}</span>{{end}}</td>
|
||||
<td>{{.Check}}</td><td>{{.Current}} now, {{.Total}} in all</td><td>{{.Since}} s</td>
|
||||
</tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else if .Running}}<p class="muted">HAProxy has no backend for it.</p>{{end}}
|
||||
</section>
|
||||
{{else}}
|
||||
<section>
|
||||
<p>No load balancer is set up. A load balancer spreads the connections to a service over several hosts and leaves out a host
|
||||
that fails its checks. Add one under <code>router.loadBalancers</code> in <a href="/advanced">Advanced</a>, for example:</p>
|
||||
<pre class="log">"loadBalancers": {
|
||||
"api": {
|
||||
"listen": { "port": 8443, "zones": ["wan", "lan"] },
|
||||
"tls": "terminate",
|
||||
"hosts": ["api.example.org"],
|
||||
"backends": ["hv1", "hv2"],
|
||||
"backendTls": { "enable": true },
|
||||
"check": { "path": "/healthz" }
|
||||
}
|
||||
}</pre>
|
||||
<p>The backends are names of DHCP reservations or addresses. With <code>"tls": "passthrough"</code> the backends keep their
|
||||
certificate and the router only forwards; the client's address then reaches them with <code>"proxyProtocol": true</code>
|
||||
(if they read it). Saved changes take effect when you apply them.</p>
|
||||
</section>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}
|
||||
@@ -28,90 +28,6 @@
|
||||
previous one.</p></section>
|
||||
{{end}}
|
||||
|
||||
<h2 class="part">Router software</h2>
|
||||
|
||||
<section>
|
||||
<h2>Installed</h2>
|
||||
<dl>
|
||||
<dt>Version</dt><dd>{{or $u.Installed.Version "unknown"}}{{if $u.Installed.Rev}} <span class="muted">{{$u.Installed.Rev}}</span>{{end}}</dd>
|
||||
<dt>Settings schema</dt><dd>{{$u.Installed.Schema}}</dd>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Releases from git</h2>
|
||||
<p>The router looks once a day at the release tags (<code>vX.Y.Z</code>) of a public 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.</p>
|
||||
<form method="post" action="/update/repository" class="actions">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label>Repository <input name="repository" value="{{$u.Repository}}" size="44" placeholder="https://git.example.org/me/nixos-router"></label>
|
||||
<button class="secondary">Save</button>
|
||||
</form>
|
||||
{{if $u.Repository}}
|
||||
<form method="post" action="/update/gitcheck" class="actions">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="secondary"{{if $u.GitRun.Running}} disabled{{end}}>{{if $u.GitRun.Running}}Looking…{{else}}Look for a newer release{{end}}</button>
|
||||
</form>
|
||||
{{if and $u.GitRun.Result (ne $u.GitRun.Result "success")}}<p class="error">The last look failed:</p><pre class="log">{{$u.GitRun.Log}}</pre>{{end}}
|
||||
{{with $u.Git}}
|
||||
<dl>
|
||||
<dt>Installed</dt><dd>{{.Installed}}</dd>
|
||||
<dt>Newest</dt><dd>{{.Newest.Version}} <span class="muted">{{printf "%.7s" .Newest.Rev}}, looked {{.Time}}</span></dd>
|
||||
</dl>
|
||||
<form method="post" action="/update/gitinstall">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<input type="hidden" name="tag" value="{{.Newest.Tag}}">
|
||||
{{if .Newer}}<p>A newer release is available.</p>
|
||||
{{else}}<p>Up to date.</p><p><label><input type="checkbox" name="force"> install it anyway</label></p>{{end}}
|
||||
<button{{if $u.Pending}} disabled{{end}}>{{if .Newer}}Install {{.Newest.Version}}{{else}}Install {{.Newest.Version}} again{{end}}</button>
|
||||
</form>
|
||||
{{else}}
|
||||
<p class="hint">Not looked yet.</p>
|
||||
{{end}}
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Install a bundle</h2>
|
||||
<p>A <code>.bundle</code> file made with <code>nix run .#release</code>. 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.</p>
|
||||
<form method="post" action="/update/upload?csrf={{.CSRF}}" enctype="multipart/form-data" data-upload>
|
||||
<p><label><input type="checkbox" name="force"> also install a version that is not newer</label></p>
|
||||
<p><input type="file" name="bundle" required> <button>Upload and install</button></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Update server</h2>
|
||||
<form method="post" action="/update/url" class="actions">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label>Address <input name="url" value="{{$u.URL}}" size="40" placeholder="https://updates.example.com/router"></label>
|
||||
<button class="secondary">Save</button>
|
||||
</form>
|
||||
{{if $u.URL}}
|
||||
<form method="post" action="/update/check" class="actions">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<button class="secondary">Check for updates</button>
|
||||
</form>
|
||||
{{end}}
|
||||
{{if $u.OfferErr}}<p class="error">Could not check: {{$u.OfferErr}}</p>{{end}}
|
||||
{{with $u.Offer}}
|
||||
<p>{{if .Newer}}Available: <strong>{{.Version}}</strong>{{if .Rev}} <span class="muted">{{.Rev}}</span>{{end}}.{{else}}Nothing newer: the server has {{.Version}}.{{end}}</p>
|
||||
<form method="post" action="/update/install">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
{{if not .Newer}}<p><label><input type="checkbox" name="force"> install it anyway</label></p>{{end}}
|
||||
<button>{{if .Newer}}Install {{.Version}}{{else}}Install{{end}}</button>
|
||||
</form>
|
||||
{{end}}
|
||||
<p class="hint">The server only has to serve static files: the <code>latest</code> file and <code>cache/</code> that
|
||||
<code>nix run .#release</code> writes. The data is signed, so plain HTTP works too.</p>
|
||||
</section>
|
||||
|
||||
<h2 class="part" id="packages">Packages</h2>
|
||||
|
||||
{{with $g.NewerRelease}}
|
||||
<section class="notice">
|
||||
<h2>NixOS {{.}} is out</h2>
|
||||
@@ -125,14 +41,16 @@
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<section>
|
||||
<h2>Channel</h2>
|
||||
<p>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.</p>
|
||||
<section id="packages">
|
||||
<h2>Installed</h2>
|
||||
<dl>
|
||||
<dt>Running</dt><dd>{{or $g.Version "unknown"}}</dd>
|
||||
<dt>nixos-router</dt><dd>{{or $g.Router.Version "unknown"}}{{if $g.Router.Rev}} <span class="muted">{{printf "%.7s" $g.Router.Rev}}</span>{{end}}</dd>
|
||||
<dt>Settings schema</dt><dd>{{$g.Router.Schema}}</dd>
|
||||
<dt>NixOS</dt><dd>{{or $g.Version "unknown"}}</dd>
|
||||
</dl>
|
||||
<p>An upgrade brings the newest nixos-router{{if $g.Repository}} (from <code>{{$g.Repository}}</code>){{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.</p>
|
||||
<form method="post" action="/upgrade/channel" class="actions">
|
||||
<input type="hidden" name="csrf" value="{{.CSRF}}">
|
||||
<label>Follow
|
||||
@@ -143,12 +61,12 @@
|
||||
<button class="secondary">Save</button>
|
||||
</form>
|
||||
{{if $g.ReleasesSeen}}<p class="hint">Stable releases as the channel server listed them on {{$g.ReleasesSeen}}; Check for upgrades asks again.</p>{{end}}
|
||||
<p class="hint">The channel only chooses what an upgrade offers; saving it changes nothing on the router. Going back to an older release
|
||||
<p class="hint">The channel only chooses which packages an upgrade offers; saving it changes nothing on the router. Going back to an older release
|
||||
(unstable to 26.05) is refused unless you tick "downgrade anyway" when previewing; state written by the newer
|
||||
release may not work with the older one.</p>
|
||||
</section>
|
||||
|
||||
{{if $g.Channel}}
|
||||
{{if or $g.Channel $g.Repository}}
|
||||
<section>
|
||||
<h2>Check</h2>
|
||||
<form method="post" action="/upgrade/check" class="actions">
|
||||
@@ -157,11 +75,11 @@
|
||||
</form>
|
||||
{{with $g.Check}}
|
||||
<dl>
|
||||
<dt>Channel</dt><dd>{{.Branch}}</dd>
|
||||
<dt>Running</dt><dd>{{.Running.Version}}</dd>
|
||||
<dt>Newest</dt><dd>{{printf "%.7s" .Newest.Rev}} <span class="muted">checked {{.Time}}</span></dd>
|
||||
{{with .Router}}<dt>nixos-router</dt><dd>{{.Installed}}{{if .Newer}} → <strong>{{.Newest.Version}}</strong>{{else}} <span class="muted">(the newest)</span>{{end}}</dd>{{end}}
|
||||
{{if .Channel}}<dt>Packages</dt><dd>{{.Channel}}: {{printf "%.7s" .Newest.Rev}}{{if .PackagesUpToDate}} <span class="muted">(what runs)</span>{{else}} <strong>newer than the running {{printf "%.7s" .Running.Rev}}</strong>{{end}}</dd>{{end}}
|
||||
<dt>Checked</dt><dd>{{.Time}}</dd>
|
||||
</dl>
|
||||
{{if .UpToDate}}<p>Up to date.</p>{{else}}<p>A newer revision is available.</p>{{end}}
|
||||
{{if .UpToDate}}<p>Up to date.</p>{{else}}<p>A newer version is available.</p>{{end}}
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
@@ -173,15 +91,19 @@
|
||||
<label><input type="checkbox" name="downgrade"> downgrade anyway</label>
|
||||
<button class="secondary"{{if or $g.Run.Running $g.Updating}} disabled{{end}}>Preview</button>
|
||||
</form>
|
||||
<p class="hint">Works it out from the new revision's description: no package is downloaded.</p>
|
||||
<p class="hint">Works it out from the new versions' descriptions: no package is downloaded.</p>
|
||||
{{with $g.Preview}}
|
||||
<p>{{$g.Version}} → <strong>{{.Version}}</strong> <span class="muted">{{printf "%.7s" .Rev}}, previewed {{.Time}}</span></p>
|
||||
{{if .Changes}}
|
||||
<p>{{$g.Version}} → <strong>{{.Version}}</strong> <span class="muted">{{if .Rev}}{{printf "%.7s" .Rev}}, {{end}}previewed {{.Time}}</span></p>
|
||||
{{if or .Router .Changes}}
|
||||
<table>
|
||||
<thead><tr><th>Package</th><th>Now</th><th></th><th>New</th></tr></thead>
|
||||
<tbody>{{range .Changes}}<tr><td>{{.Name}}</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}</tbody>
|
||||
<tbody>
|
||||
{{with .Router}}<tr class="highlight" title="This upgrade also installs a new version of nixos-router itself, and migrates the settings to it if it needs that."><td>nixos-router</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}
|
||||
{{range .Changes}}<tr><td>{{.Name}}</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}<p>No package changes.</p>{{end}}
|
||||
{{if .Router}}<p class="hint">The highlighted row is the router software itself: this upgrade installs it too.</p>{{end}}
|
||||
<p class="hint">The list shows the versions of programs the router runs; a program that is only rebuilt does not appear.</p>
|
||||
<dl>
|
||||
<dt>To download</dt><dd>{{or .Download "nothing, or the package cache cannot be reached"}}</dd>
|
||||
@@ -203,7 +125,7 @@
|
||||
</form>
|
||||
<form method="post" action="/upgrade/apply">
|
||||
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
||||
<button{{if or $g.Run.Running $g.Updating $g.Pending}} disabled{{end}}>Upgrade to {{.Version}}</button>
|
||||
<button{{if or $g.Run.Running $g.Updating $g.Pending}} disabled{{end}}>Upgrade{{with .Router}} nixos-router to {{.To}} and{{end}} to {{.Version}}</button>
|
||||
</form>
|
||||
</div>
|
||||
<p class="hint">Downloading first lets you start the upgrade later without needing the internet. Upgrading
|
||||
@@ -214,16 +136,27 @@
|
||||
<section><p>Choose a channel to look for upgrades.</p></section>
|
||||
{{end}}
|
||||
|
||||
<section>
|
||||
<h2>Install a bundle</h2>
|
||||
<p>For a router without a route to the repository, or when it is down: a <code>.bundle</code> file made with
|
||||
<code>nix run .#release</code>. 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.</p>
|
||||
<form method="post" action="/update/upload?csrf={{.CSRF}}" enctype="multipart/form-data" data-upload>
|
||||
<p><label><input type="checkbox" name="force"> also install a version that is not newer</label></p>
|
||||
<p><input type="file" name="bundle" required> <button>Upload and install</button></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{{if and $u.Status.Log (not $u.Status.Running)}}
|
||||
<section>
|
||||
<h2>Last update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}</h2>
|
||||
<h2>Last bundle update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}</h2>
|
||||
<pre class="log">{{$u.Status.Log}}</pre>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
{{if and $g.Run.Log (not $g.Run.Running)}}
|
||||
<section>
|
||||
<h2>Last package run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}</h2>
|
||||
<h2>Last upgrade run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}</h2>
|
||||
<pre class="log">{{$g.Run.Log}}</pre>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
+3
-125
@@ -14,7 +14,6 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Updates arrive as a tar of a signed binary cache (see lib.mkRelease):
|
||||
@@ -143,66 +142,9 @@ func (s System) installedRelease() Release {
|
||||
}
|
||||
|
||||
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) 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 // router.update.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,13 +221,7 @@ 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),
|
||||
}
|
||||
if s, err := loadSettings(a.sys.settingsPath()); err == nil {
|
||||
d.Repository = s.repository()
|
||||
d.Git = a.gitCheck(d.Repository)
|
||||
}
|
||||
d.Progress, d.Step = updateProgress(d.Status.Log)
|
||||
return d
|
||||
@@ -313,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)
|
||||
@@ -333,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.
|
||||
|
||||
@@ -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"))
|
||||
// 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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,6 +179,8 @@ var upgradeTitles = map[string]string{
|
||||
type channelChoice struct{ Value, Label string }
|
||||
|
||||
type upgradeData struct {
|
||||
Router Release // the installed nixos-router
|
||||
Repository string // where its releases come from
|
||||
Version string // the running NixOS version
|
||||
Channel string
|
||||
Choices []channelChoice
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
+36
-2
@@ -1,16 +1,23 @@
|
||||
# Signs $release (a store path) as a binary cache and writes, into --out:
|
||||
# router-update-<version>.bundle one file to upload in the web UI
|
||||
# latest, cache/ the same, laid out for `router pulls from a URL`
|
||||
# usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none]
|
||||
#
|
||||
# Run in a git checkout it also tags the commit that was released (vX.Y.Z, the
|
||||
# tags routers that update from the repository look for). The tag is local: it
|
||||
# has to be pushed with the branch. It is made last, so a release that fails
|
||||
# leaves no tag.
|
||||
# usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none] [--no-tag]
|
||||
key=""
|
||||
out=dist
|
||||
compression=zstd
|
||||
tag=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--key) key=$2; shift ;;
|
||||
--out) out=$2; shift ;;
|
||||
--compression) compression=$2; shift ;;
|
||||
*) echo "usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none]" >&2; exit 2 ;;
|
||||
--no-tag) tag=0 ;;
|
||||
*) echo "usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none] [--no-tag]" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
@@ -28,3 +35,30 @@ tar -C "$out" -cf "$out/router-update-$version.bundle" latest cache
|
||||
echo "release $version ($(du -h "$out/router-update-$version.bundle" | cut -f1)):"
|
||||
echo " upload $out/router-update-$version.bundle in the router's web UI (Update)"
|
||||
echo " or serve $out over HTTP(S) and give the router that URL"
|
||||
|
||||
if [ "$tag" -eq 1 ]; then
|
||||
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo " tag none: not in a git repository"
|
||||
else
|
||||
head_version=$(git show HEAD:VERSION 2>/dev/null | tr -d '\n' || true)
|
||||
if [ "$head_version" != "$version" ]; then
|
||||
echo "router-release: the commit at HEAD is version '$head_version', not $version: not tagged" >&2
|
||||
echo " (commit the version, then: git tag -a v$version -m 'Release $version')" >&2
|
||||
exit 1
|
||||
fi
|
||||
head=$(git rev-parse HEAD)
|
||||
if git rev-parse -q --verify "refs/tags/v$version" >/dev/null; then
|
||||
if [ "$(git rev-parse "v$version^{commit}")" != "$head" ]; then
|
||||
echo "router-release: v$version is already a tag of another commit" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo " tag v$version exists"
|
||||
else
|
||||
git tag -a "v$version" -m "Release $version"
|
||||
echo " tag v$version on ${head:0:7}: push it with the branch (git push origin v$version)"
|
||||
fi
|
||||
if [ "$(cat "$release/rev")" != "$head" ]; then
|
||||
echo " note the release was built from a tree that differs from HEAD (uncommitted changes)"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
+5
-3
@@ -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")
|
||||
'';
|
||||
}
|
||||
|
||||
@@ -61,6 +61,31 @@ let
|
||||
};
|
||||
} overrides;
|
||||
|
||||
# A LAN with two reserved hosts, and a service on them.
|
||||
lbLan = lan {
|
||||
dhcp.reservations = {
|
||||
hv1 = {
|
||||
mac = "02:00:00:00:00:21";
|
||||
address = "192.168.10.21";
|
||||
};
|
||||
hv2 = {
|
||||
mac = "02:00:00:00:00:22";
|
||||
address = "192.168.10.22";
|
||||
};
|
||||
};
|
||||
};
|
||||
lb =
|
||||
overrides:
|
||||
lib.recursiveUpdate {
|
||||
listen.port = 8443;
|
||||
certificate = "/var/lib/router/lb.pem";
|
||||
backends = [
|
||||
"hv1"
|
||||
"hv2"
|
||||
];
|
||||
backendTls.enable = true;
|
||||
} overrides;
|
||||
|
||||
failed = router: map (a: a.message) (lib.filter (a: !a.assertion) (evalRouter router).assertions);
|
||||
|
||||
cases = {
|
||||
@@ -704,6 +729,121 @@ let
|
||||
};
|
||||
expect = [ ];
|
||||
};
|
||||
lbValid = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { };
|
||||
# Two services share a port when the host name tells them apart.
|
||||
loadBalancers.a = lb {
|
||||
listen.port = 9443;
|
||||
hosts = [ "a.example.org" ];
|
||||
};
|
||||
loadBalancers.b = lb {
|
||||
listen.port = 9443;
|
||||
hosts = [ "b.example.org" ];
|
||||
};
|
||||
};
|
||||
expect = [ ];
|
||||
};
|
||||
lbUnknownBackend = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { backends = [ "hv1" "nothere" ]; };
|
||||
};
|
||||
expect = [ "`nothere` is neither a DHCP reservation nor an IPv4 address" ];
|
||||
};
|
||||
lbNoBackends = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { backends = lib.mkForce [ ]; };
|
||||
};
|
||||
expect = [ "at least one backend" ];
|
||||
};
|
||||
lbUnknownZone = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { listen.zones = [ "dmz" ]; };
|
||||
};
|
||||
expect = [ "listen.zones: unknown zone" ];
|
||||
};
|
||||
lbPortOfTheRouter = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { listen.port = 22; };
|
||||
};
|
||||
expect = [ "is used by the router itself" ];
|
||||
};
|
||||
lbPortForwarded = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { listen.port = 8443; };
|
||||
firewall.nat = [
|
||||
{
|
||||
type = "dnat";
|
||||
from = "wan";
|
||||
to = "main";
|
||||
protocol = "tcp";
|
||||
ports = [ 8443 ];
|
||||
toAddress = "192.168.10.50";
|
||||
}
|
||||
];
|
||||
};
|
||||
expect = [ "is also forwarded by router.firewall.nat" ];
|
||||
};
|
||||
lbSharedPortWithoutHosts = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.a = lb { };
|
||||
loadBalancers.b = lb { hosts = [ "b.example.org" ]; };
|
||||
};
|
||||
expect = [
|
||||
"port 8443 is shared with b: every service on it needs `hosts`"
|
||||
"port 8443 is shared with a: every service on it needs `hosts`"
|
||||
];
|
||||
};
|
||||
lbSharedPortDisagrees = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.a = lb { hosts = [ "a.example.org" ]; };
|
||||
loadBalancers.b = lb {
|
||||
hosts = [ "b.example.org" ];
|
||||
tls = "none";
|
||||
certificate = lib.mkForce null;
|
||||
};
|
||||
};
|
||||
expect = [
|
||||
"must agree on tls and protocol"
|
||||
"must agree on tls and protocol"
|
||||
];
|
||||
};
|
||||
lbPassthroughNeedsTcp = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb {
|
||||
tls = "passthrough";
|
||||
protocol = "http";
|
||||
certificate = lib.mkForce null;
|
||||
};
|
||||
};
|
||||
expect = [ "passthrough only forwards bytes" ];
|
||||
};
|
||||
lbTerminateWithoutCertificate = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb { certificate = lib.mkForce null; };
|
||||
};
|
||||
expect = [ "has no `certificate` and router.acme is not enabled" ];
|
||||
};
|
||||
lbVerifyNeedsTls = {
|
||||
router = {
|
||||
lans.main = lbLan;
|
||||
loadBalancers.api = lb {
|
||||
backendTls.enable = lib.mkForce false;
|
||||
backendTls.verify = true;
|
||||
};
|
||||
};
|
||||
expect = [ "backendTls.verify needs backendTls.enable" ];
|
||||
};
|
||||
wgNoPeers = {
|
||||
router = {
|
||||
lans.main = lan { };
|
||||
@@ -1589,6 +1729,7 @@ let
|
||||
"ulaValid"
|
||||
"wgSourceOk"
|
||||
"dnsValid"
|
||||
"lbValid"
|
||||
];
|
||||
|
||||
subnet =
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
rollback = import ./rollback.nix { inherit self pkgs; };
|
||||
dns = import ./dns.nix { inherit self pkgs; };
|
||||
ddns = import ./ddns.nix { inherit self pkgs; };
|
||||
loadbalancer = import ./loadbalancer.nix { inherit self pkgs; };
|
||||
installer = import ./installer.nix { inherit self pkgs; };
|
||||
apply = import ./apply.nix { inherit self pkgs; };
|
||||
webui = import ./webui.nix { inherit self pkgs; };
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
# Load balancers: a service on two backends, reachable from outside and inside.
|
||||
#
|
||||
# upstream (ISP, and the client from outside) -- router -- client
|
||||
# |
|
||||
# hv1, hv2 (HTTPS API)
|
||||
#
|
||||
# `api` decrypts TLS on the router (re-encrypting toward the backends) and
|
||||
# tells them the client in X-Forwarded-For; `raw` passes TLS through. Both
|
||||
# check /healthz, so a backend that fails it gets no connections.
|
||||
{ self, pkgs }:
|
||||
let
|
||||
common = import ./common.nix;
|
||||
macs = {
|
||||
hv1 = "02:00:00:00:00:21";
|
||||
hv2 = "02:00:00:00:00:22";
|
||||
};
|
||||
|
||||
settings = pkgs.writeText "settings.json" (
|
||||
builtins.toJSON {
|
||||
system = {
|
||||
hostName = "router";
|
||||
stateVersion = "26.11";
|
||||
};
|
||||
router = { };
|
||||
}
|
||||
);
|
||||
|
||||
# One certificate for everything: the router's (api.lb.test) and the backends'.
|
||||
cert =
|
||||
pkgs.runCommand "lb-cert" { nativeBuildInputs = [ pkgs.openssl ]; } ''
|
||||
mkdir $out
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=api.lb.test \
|
||||
-addext subjectAltName=DNS:api.lb.test -keyout $out/key.pem -out $out/cert.pem
|
||||
cat $out/cert.pem $out/key.pem > $out/both.pem
|
||||
'';
|
||||
|
||||
# What a backend answers: who it is, who connected, and what the router said.
|
||||
# /healthz fails while /tmp/sick exists.
|
||||
api = pkgs.writeScript "api.py" ''
|
||||
#!${pkgs.python3}/bin/python3
|
||||
import http.server, os, ssl, sys
|
||||
|
||||
name = sys.argv[1]
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/healthz" and os.path.exists("/tmp/sick"):
|
||||
self.send_response(503)
|
||||
self.end_headers()
|
||||
return
|
||||
body = "name=%s peer=%s xff=%s host=%s\n" % (
|
||||
name, self.client_address[0], self.headers.get("X-Forwarded-For", "-"), self.headers.get("Host", "-"))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body.encode())
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("0.0.0.0", 8443), Handler)
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ctx.load_cert_chain("${cert}/cert.pem", "${cert}/key.pem")
|
||||
server.socket = ctx.wrap_socket(server.socket, server_side=True)
|
||||
server.serve_forever()
|
||||
'';
|
||||
|
||||
backend = name: {
|
||||
imports = [ ];
|
||||
virtualisation.vlans = [ 2 ];
|
||||
networking.useNetworkd = true;
|
||||
networking.useDHCP = false;
|
||||
networking.firewall.enable = false;
|
||||
networking.interfaces.eth1.ipv4.addresses = pkgs.lib.mkForce [ ];
|
||||
systemd.network.networks."10-lan" = {
|
||||
matchConfig.Name = "eth1";
|
||||
linkConfig.MACAddress = macs.${name};
|
||||
networkConfig.DHCP = "ipv4";
|
||||
};
|
||||
systemd.services.api = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
serviceConfig.ExecStart = "${api} ${name}";
|
||||
};
|
||||
};
|
||||
in
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "router-loadbalancer";
|
||||
|
||||
defaults.imports = [ common.tools ];
|
||||
interactive.defaults = common.interactiveDefaults;
|
||||
|
||||
nodes = {
|
||||
upstream =
|
||||
{ lib, ... }:
|
||||
{
|
||||
virtualisation.vlans = [ 1 ];
|
||||
networking.useNetworkd = true;
|
||||
networking.useDHCP = false;
|
||||
networking.firewall.enable = false;
|
||||
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
|
||||
systemd.network.networks."10-wan" = {
|
||||
matchConfig.Name = "eth1";
|
||||
address = [ "203.0.113.1/24" ];
|
||||
};
|
||||
services.dnsmasq = {
|
||||
enable = true;
|
||||
settings = {
|
||||
interface = "eth1";
|
||||
bind-interfaces = true;
|
||||
dhcp-range = "203.0.113.100,203.0.113.100,255.255.255.0,1h";
|
||||
dhcp-option = [ "option:router,203.0.113.1" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
router =
|
||||
{ lib, ... }:
|
||||
{
|
||||
imports = [
|
||||
self.nixosModules.router
|
||||
self.nixosModules.settings
|
||||
];
|
||||
routerSettings.file = settings;
|
||||
virtualisation.vlans = [
|
||||
1
|
||||
2
|
||||
];
|
||||
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
|
||||
networking.interfaces.eth2.ipv4.addresses = lib.mkForce [ ];
|
||||
|
||||
router = {
|
||||
enable = true;
|
||||
wan.interface = "eth1";
|
||||
lans.main = {
|
||||
interface = "eth2";
|
||||
internet = true;
|
||||
ipv4.address = "192.168.10.1";
|
||||
dhcp = {
|
||||
pool = {
|
||||
start = "192.168.10.100";
|
||||
end = "192.168.10.199";
|
||||
};
|
||||
reservations = {
|
||||
hv1 = {
|
||||
mac = macs.hv1;
|
||||
address = "192.168.10.21";
|
||||
};
|
||||
hv2 = {
|
||||
mac = macs.hv2;
|
||||
address = "192.168.10.22";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
dns.forwarders = [ "203.0.113.1" ];
|
||||
loadBalancers = {
|
||||
api = {
|
||||
listen.port = 8443;
|
||||
listen.zones = [
|
||||
"wan"
|
||||
"main"
|
||||
];
|
||||
hosts = [ "api.lb.test" ];
|
||||
certificate = "${cert}/both.pem";
|
||||
backends = [
|
||||
"hv1"
|
||||
"hv2"
|
||||
];
|
||||
backendTls.enable = true;
|
||||
check.path = "/healthz";
|
||||
check.interval = "1s";
|
||||
check.fall = 2;
|
||||
check.rise = 2;
|
||||
};
|
||||
raw = {
|
||||
listen.port = 9443;
|
||||
listen.zones = [ "wan" ];
|
||||
tls = "passthrough";
|
||||
backends = [
|
||||
"hv1"
|
||||
"hv2"
|
||||
];
|
||||
backendPort = 8443;
|
||||
check.path = "/healthz";
|
||||
check.interval = "1s";
|
||||
check.fall = 2;
|
||||
check.rise = 2;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
client =
|
||||
{ lib, ... }:
|
||||
{
|
||||
virtualisation.vlans = [ 2 ];
|
||||
networking.useNetworkd = true;
|
||||
networking.useDHCP = false;
|
||||
networking.firewall.enable = false;
|
||||
networking.interfaces.eth1.ipv4.addresses = lib.mkForce [ ];
|
||||
systemd.network.networks."10-lan" = {
|
||||
matchConfig.Name = "eth1";
|
||||
networkConfig.DHCP = "ipv4";
|
||||
};
|
||||
};
|
||||
|
||||
hv1 = backend "hv1";
|
||||
hv2 = backend "hv2";
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
start_all()
|
||||
upstream.wait_for_unit("dnsmasq.service")
|
||||
router.wait_for_unit("network-online.target")
|
||||
router.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 203.0.113.100")
|
||||
router.wait_for_unit("kea-dhcp4-server.service")
|
||||
router.wait_for_unit("haproxy.service")
|
||||
for n in ["hv1", "hv2"]:
|
||||
globals()[n].wait_for_unit("api.service")
|
||||
hv1.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.21")
|
||||
hv2.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.22")
|
||||
client.wait_until_succeeds("ip -4 addr show dev eth1 | grep -q 192.168.10.1[0-9][0-9]")
|
||||
|
||||
outside = "curl -sk --max-time 5 --resolve api.lb.test:8443:203.0.113.100 https://api.lb.test:8443"
|
||||
inside = "curl -sk --max-time 5 --resolve api.lb.test:8443:192.168.10.1 https://api.lb.test:8443"
|
||||
|
||||
def answers(node, cmd, path="/", n=8):
|
||||
return [node.succeed(f"{cmd}{path}").strip() for _ in range(n)]
|
||||
|
||||
def names(lines):
|
||||
return {l.split()[0] for l in lines}
|
||||
|
||||
# Two servers and the backend itself, for each of the two services.
|
||||
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep -c ',UP,' | grep -qx 6", timeout=60)
|
||||
|
||||
with subtest("the statistics have the columns the web UI's page reads"):
|
||||
header = router.succeed("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | head -1")
|
||||
cols = header.lstrip("# ").strip().split(",")
|
||||
for c in ["pxname", "svname", "status", "scur", "stot", "lastchg", "check_status", "check_code"]:
|
||||
assert c in cols, (c, cols)
|
||||
# (The CSV's own `addr` column is empty: the address is in the servers' state.)
|
||||
state = router.succeed("echo 'show servers state' | nc -U -N /run/haproxy/haproxy.sock")
|
||||
head = [l for l in state.splitlines() if l.startswith("#")][0].split()[1:]
|
||||
for c in ["be_name", "srv_name", "srv_addr", "srv_port"]:
|
||||
assert c in head, (c, head)
|
||||
rows = [l.split() for l in state.splitlines() if l and l[0] != "#" and len(l.split()) == len(head)]
|
||||
got = {(r[head.index("be_name")], r[head.index("srv_name")]): r[head.index("srv_addr")] + ":" + r[head.index("srv_port")] for r in rows}
|
||||
assert got[("be_api", "hv1")] == "192.168.10.21:8443" and got[("be_api", "hv2")] == "192.168.10.22:8443", got
|
||||
|
||||
with subtest("from outside, both backends are used"):
|
||||
got = answers(upstream, outside)
|
||||
assert names(got) == {"name=hv1", "name=hv2"}, got
|
||||
|
||||
with subtest("the backends see the router, and the client in X-Forwarded-For"):
|
||||
line = upstream.succeed(f"{outside}/").strip()
|
||||
assert "peer=192.168.10.1" in line and "xff=203.0.113.1" in line, line
|
||||
assert "host=api.lb.test:8443" in line, line
|
||||
|
||||
with subtest("from inside, through the router's address"):
|
||||
got = answers(client, inside)
|
||||
assert names(got) == {"name=hv1", "name=hv2"}, got
|
||||
# The client's own (pool) address, not the router's.
|
||||
import re
|
||||
assert re.search(r"xff=192\.168\.10\.1[0-9][0-9] ", got[0]), got[0]
|
||||
|
||||
with subtest("the service's name is published for the LAN"):
|
||||
assert client.succeed("dig +short @192.168.10.1 api.lb.test").strip() == "192.168.10.1"
|
||||
|
||||
with subtest("a name that is not the service's is refused"):
|
||||
code = upstream.succeed("curl -sk -o /dev/null -w '%{http_code}' --max-time 5 --resolve other.lb.test:8443:203.0.113.100 https://other.lb.test:8443/").strip()
|
||||
assert code in ("503", "000"), code
|
||||
|
||||
with subtest("passthrough: the backend's own certificate and the router as the peer"):
|
||||
out = upstream.succeed("curl -sk --max-time 5 https://203.0.113.100:9443/").strip()
|
||||
assert out.startswith("name=hv") and "peer=203.0.113.1" not in out and "peer=192.168.10.1" in out, out
|
||||
assert names(answers(upstream, "curl -sk --max-time 5 https://203.0.113.100:9443", n=8)) == {"name=hv1", "name=hv2"}
|
||||
|
||||
with subtest("the port is closed where the service does not listen"):
|
||||
client.fail("curl -sk --max-time 3 https://192.168.10.1:9443/")
|
||||
|
||||
with subtest("a backend that fails its check gets no connections, and returns when it passes"):
|
||||
hv1.succeed("touch /tmp/sick")
|
||||
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv1' | grep -q ',DOWN,'", timeout=60)
|
||||
got = answers(upstream, outside, n=8)
|
||||
assert names(got) == {"name=hv2"}, got
|
||||
assert names(answers(client, inside, n=8)) == {"name=hv2"}
|
||||
assert names(answers(upstream, "curl -sk --max-time 5 https://203.0.113.100:9443", n=8)) == {"name=hv2"}
|
||||
hv1.succeed("rm /tmp/sick")
|
||||
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv1' | grep -q ',UP,'", timeout=60)
|
||||
assert names(answers(upstream, outside)) == {"name=hv1", "name=hv2"}
|
||||
|
||||
with subtest("a backend that is down is out too"):
|
||||
hv2.systemctl("stop api.service")
|
||||
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,hv2' | grep -q ',DOWN,'", timeout=60)
|
||||
assert names(answers(upstream, outside)) == {"name=hv1"}
|
||||
|
||||
with subtest("with no backend left the service answers 503"):
|
||||
hv1.succeed("touch /tmp/sick")
|
||||
router.wait_until_succeeds("echo 'show stat' | nc -U -N /run/haproxy/haproxy.sock | grep '^be_api,BACKEND' | grep -q ',DOWN,'", timeout=60)
|
||||
code = upstream.succeed(f"{outside}/ -o /dev/null -w '%{{http_code}}'").strip()
|
||||
assert code == "503", code
|
||||
'';
|
||||
}
|
||||
+49
-35
@@ -125,6 +125,8 @@ let
|
||||
{
|
||||
imports = [ (modulesPath + "/testing/test-instrumentation.nix") ];
|
||||
router.rollback.timeout = "90s";
|
||||
# Releases from git: the builder's repository, not the real one.
|
||||
routerUpdate.repository = "http://${builderIp}:8005/router.git";
|
||||
routerSettings.upgrade = {
|
||||
channelsUrl = "http://192.168.10.60:8080";
|
||||
nixpkgsRef = "path:/var/lib/newer-nixpkgs?lastModified=${toString self.inputs.nixpkgs.lastModified}&rev=%rev%";
|
||||
@@ -349,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: <strong>2.0.0</strong>" 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")
|
||||
@@ -380,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"
|
||||
@@ -390,37 +400,42 @@ pkgs.testers.runNixOSTest {
|
||||
builder.succeed("systemd-run --unit=git-server /etc/git-server.py /srv/git 8005")
|
||||
builder.wait_for_open_port(8005, "${builderIp}")
|
||||
|
||||
# Nothing to look at until a repository is named.
|
||||
assert "no repository" in target.succeed("router-update check 2>&1")
|
||||
# The repository is part of the installed version; the page names it and has no field for it.
|
||||
assert target.succeed("cat /etc/router-update-repository").strip() == repo
|
||||
login()
|
||||
token = csrf("/update")
|
||||
page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
|
||||
assert repo in page and 'name="repository"' not in page, page
|
||||
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}/") == "303"
|
||||
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/repository", f"--data-urlencode repository={repo}") in ("404", "405")
|
||||
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 "<strong>3.0.0</strong>" 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 "<td>nixos-router</td>" 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
|
||||
@@ -429,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()
|
||||
@@ -445,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
|
||||
'';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user