networkmanager opens a network's sign-in page on its own machine (design 08 sign-in-page) #755
@@ -0,0 +1,91 @@
|
||||
# networkmanager
|
||||
|
||||
The machine's network, managed by NetworkManager: this module holds the node seat `node-uplink` (novox/hq ADR 0241),
|
||||
answering its verbs `resolvers` and `links`, writes the machine's resolver file from the mesh's resolvers (ADR 0117,
|
||||
ADR 0223), and reacts when the network asks the person to sign in on its **sign-in page** (ADR 0687, ADR 0689; design
|
||||
08 sign-in-page §11 to §27).
|
||||
|
||||
## Two parts and the folder they share
|
||||
|
||||
Behind a sign-in page the private network's tunnel, and with it the bus, is out of reach, and the tool runner starts
|
||||
no bundle before it has reached the bus. So the reaction runs in two parts:
|
||||
|
||||
- **the watcher**, the process `networkmanager-sign-in` (`uplink-tools watch`), started by the machine's service
|
||||
manager at boot as the machine's account and kept running, needing no bus. It hears NetworkManager's rating of the
|
||||
network, opens the sign-in page, tells the person, and keeps the events.
|
||||
- **the bundle** `uplink-tools`, in the tool runner once it has reached the bus: it answers `resolvers` and `links`,
|
||||
serves the tools below, publishes the kept events and calls `uplink-names`.
|
||||
|
||||
They share only the module's own folder, `~/.local/state/mesh/networkmanager` (the account's, mode 0700), every file
|
||||
written whole (beside, then renamed over):
|
||||
|
||||
| file | what |
|
||||
|---|---|
|
||||
| `watch.sock` | the watcher's socket: one JSON line asked, one answered; `state` answers its state, `rating-again` makes it subscribe again and act on the rating read now |
|
||||
| `check-address` | NetworkManager's check address, written by the watcher at its start and at each change |
|
||||
| `pending/` | the kept events, one `<sequence>.json` each, written by the watcher and deleted by the bundle once the bus acknowledged it |
|
||||
| `names.json` | the bundle's last `uplink-names` call: the names, its result (`ok`, `no holder` or the failure) and when |
|
||||
| `sequence` | the next sequence of the watcher's message ids, never reset while the folder lives |
|
||||
|
||||
The folder's `unknown` is `module`: the node-engine does nothing inside it, and the watcher leaves any other path it
|
||||
finds there as it is and writes it to its journal once per path. When the module leaves, the node-engine keeps the
|
||||
folder while it holds files, and nothing reads it then.
|
||||
|
||||
## The watcher opens the page on its own machine, without the bus
|
||||
|
||||
It hears NetworkManager's `PropertiesChanged` on the system bus for the rating (`Connectivity`), the active connection
|
||||
and the check (`ConnectivityCheckEnabled`, `ConnectivityCheckAvailable`, `ConnectivityCheckUri`); nothing runs on a
|
||||
timer, and the check itself stays NetworkManager's. When its system bus connection drops it subscribes again as the
|
||||
bus's socket comes back.
|
||||
|
||||
With the check on, it opens the check address in the person's default browser and shows a notification saying why at
|
||||
three moments: when the rating becomes PORTAL on the active connection, at its own start while the rating is PORTAL,
|
||||
and when the person's graphical session starts while it is. It acts once per ask: again only after the rating left
|
||||
PORTAL, a session's start and its own restart excepted. When the rating leaves PORTAL for FULL it says the network is
|
||||
open. An open that failed gives a critical notification naming the reason and the address.
|
||||
|
||||
It opens with `systemd-run --user --collect --quiet --wait -- xdg-open <address>`, the address one argument and never
|
||||
through a shell, after asking `xdg-mime query default x-scheme-handler/<scheme>` for the program: the browser runs
|
||||
under the person's user manager and outlives the watcher. An open still running after 10 s is said as opening.
|
||||
|
||||
**How it finds the person's session.** Over the system bus it asks logind for its account's sessions: the one of type
|
||||
`x11` or `wayland`, not remote, active or online. Its session bus is `<RuntimePath>/bus`, and its display is in the user
|
||||
manager's environment (`DISPLAY` and `XAUTHORITY`, which the X11 start block imports; `WAYLAND_DISPLAY` for a Wayland
|
||||
start block). No such session, or no display named there, is no session: then it opens and shows nothing, and still
|
||||
keeps the events. **How it hears a session start:** logind's `SessionNew`; for a graphical session of its account it
|
||||
reads the user manager's environment again at each file event in `/tmp/.X11-unix` (an X server's socket) and in the
|
||||
session's runtime directory (a Wayland socket), for at most 60 s, since the user manager says no change of its
|
||||
`Environment`; past that it writes that the start was not acted on.
|
||||
|
||||
## The events: kept by the watcher, published by the bundle
|
||||
|
||||
From NetworkManager's own rating the watcher keeps `node-uplink`'s two events, `sign-in-asked` (node, link, network,
|
||||
the address opened, when) and `sign-in-ended` (node, link, network, when, and why: `signed-in`, `left` or
|
||||
`no-longer-asked`), at most 256 of them, the oldest dropped past that with a journal line. With the check switched
|
||||
off (not enabled, or not available) it neither opens nor keeps anything. The bundle publishes them in order on the
|
||||
seat's subject `mesh.seat.node-uplink.event.<event>.<node>`, each under its own message id, awaiting the stream's
|
||||
acknowledgement, at its start, at each new kept event and when its bus connection comes back; a refused one waits for
|
||||
the next moment. Nothing in the mesh consumes them: they are its record, read with `nats.nats_stream_messages`
|
||||
filtered to `mesh.seat.node-uplink.event.*.<node>`, their time in `at`.
|
||||
|
||||
## The bundle gives the resolver the check's host name
|
||||
|
||||
Where a module holds `node-resolver` on this node (the assignments say which), the bundle calls its `uplink-names`
|
||||
with the check address's host name, so NetworkManager's own check resolves through the network it tests: at its start,
|
||||
when `check-address` changes, when its bus connection comes back and when the node-engine says that holder runs. With no holder it calls nothing, and that is no failure.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | what |
|
||||
|---|---|
|
||||
| `uplink_sign_in` | the reaction as it stands: the watcher's state, the events waiting and the publishes refused, the last `uplink-names` call, the resolver's refusal of the names |
|
||||
| `uplink_names_again` | call `uplink-names` now |
|
||||
| `uplink_rating_again` | make the watcher subscribe again and act on the rating now |
|
||||
| `uplink_publish_again` | publish the kept events now |
|
||||
| `uplink_health` | whether the reaction works: unhealthy while the watcher's socket does not answer, while it is not subscribed, or while the last `uplink-names` call stands failed; a tool to read, not a health check |
|
||||
|
||||
**The watcher's health is its unit's state** (`networkmanager-sign-in` active), judged on the machine without the bus,
|
||||
so it holds behind a sign-in page. When the system bus comes back and the watcher cannot subscribe on it again, it
|
||||
writes the reason to its journal and exits non-zero, so its unit shows failing and the service manager restarts it.
|
||||
`uplink_health` is a tool, not a health check; the watcher not subscribed and a failed `uplink-names` call are also
|
||||
shown by `uplink_sign_in` and written to the journal.
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
// The bundle's own work beside the seat's verbs (design 08 sign-in-page §11, §13, §20): started by the tool runner
|
||||
// once it reached the bus. It acts at its start, at file events of the kernel in the module's folder, and when its bus
|
||||
// connection comes back: the first heartbeat of its consumer answered after a missed one (DMC-4).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
type bundle struct {
|
||||
folder Folder
|
||||
pub *publisher
|
||||
names *namer
|
||||
|
||||
mu sync.Mutex
|
||||
missed bool
|
||||
lastAt time.Time
|
||||
}
|
||||
|
||||
// bundleRuns is what the bundle hears through: file events of the kernel, its consumer's heartbeat and its
|
||||
// subscription.
|
||||
type bundleRuns struct {
|
||||
files func(dirs []string, stop <-chan struct{}) <-chan struct{}
|
||||
fileMade func(dir, name string, stop <-chan struct{}) <-chan struct{}
|
||||
onHeartbeat func(func(stdio.Heartbeat)) error
|
||||
subscribe func(pattern string, handle func(stdio.Envelope) error) error
|
||||
}
|
||||
|
||||
func newBundle(f Folder) *bundle {
|
||||
return &bundle{folder: f, pub: &publisher{folder: f, publish: seatPublish},
|
||||
names: &namer{folder: f, ask: stdio.Ask, now: time.Now}}
|
||||
}
|
||||
|
||||
// seatPublish says a kept event through the runtime, which awaits the stream's acknowledgement.
|
||||
func seatPublish(subject string, body json.RawMessage, id string) error {
|
||||
return stdio.SeatPublish(subject, body, id)
|
||||
}
|
||||
|
||||
// start publishes what is kept and gives the resolver the check's host name, then does each again at its moments: a
|
||||
// file event on pending/ publishes, a changed check-address gives the names, node-resolver's holder running gives the
|
||||
// names, and the bus connection's return does both (§13, §20).
|
||||
func (b *bundle) start(runs bundleRuns) {
|
||||
pending := filepath.Join(b.folder.Dir, pendingName)
|
||||
if err := os.MkdirAll(pending, 0o700); err != nil {
|
||||
journal("making %s failed: %v", pending, err)
|
||||
}
|
||||
kept := runs.files([]string{pending}, nil)
|
||||
check := runs.fileMade(b.folder.Dir, checkName, nil)
|
||||
b.pub.publishKept("the bundle's start")
|
||||
b.names.give("the bundle's start")
|
||||
if err := runs.subscribe(runningPattern, b.names.running); err != nil {
|
||||
journal("subscribing to %s failed: %v", runningPattern, err)
|
||||
}
|
||||
if err := runs.onHeartbeat(b.heartbeat); err != nil {
|
||||
journal("hearing the bus connection's heartbeat failed: %v", err)
|
||||
}
|
||||
for kept != nil || check != nil {
|
||||
select {
|
||||
case _, ok := <-kept:
|
||||
if !ok {
|
||||
kept = nil
|
||||
continue
|
||||
}
|
||||
b.pub.publishKept("a kept event")
|
||||
case _, ok := <-check:
|
||||
if !ok {
|
||||
check = nil
|
||||
continue
|
||||
}
|
||||
b.names.give("a changed check address")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// heartbeat hears the consumer's heartbeat: the first one answered after a missed one is the connection come back.
|
||||
func (b *bundle) heartbeat(hb stdio.Heartbeat) {
|
||||
b.mu.Lock()
|
||||
if !hb.At.IsZero() && hb.At.Before(b.lastAt) {
|
||||
b.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if !hb.At.IsZero() {
|
||||
b.lastAt = hb.At
|
||||
}
|
||||
back := !hb.Missed && b.missed
|
||||
b.missed = hb.Missed
|
||||
b.mu.Unlock()
|
||||
if hb.Missed {
|
||||
journal("the bus connection's heartbeat was missed: %s", hb.Why)
|
||||
}
|
||||
if back {
|
||||
journal("the bus connection came back")
|
||||
b.reconnected()
|
||||
}
|
||||
}
|
||||
|
||||
// reconnected is the work at the bus connection's return.
|
||||
func (b *bundle) reconnected() {
|
||||
b.pub.publishKept("the bus connection's return")
|
||||
b.names.give("the bus connection's return")
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package main
|
||||
|
||||
// The watcher's system bus, through godbus: the network manager's properties and its PropertiesChanged, logind's
|
||||
// SessionNew, and the system bus's socket coming back, heard as a file event of the kernel on its folder.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unsafe"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
nmName = "org.freedesktop.NetworkManager"
|
||||
nmPath = dbus.ObjectPath("/org/freedesktop/NetworkManager")
|
||||
nmActive = "org.freedesktop.NetworkManager.Connection.Active"
|
||||
nmDevice = "org.freedesktop.NetworkManager.Device"
|
||||
propsIface = "org.freedesktop.DBus.Properties"
|
||||
login1Name = "org.freedesktop.login1"
|
||||
login1Path = dbus.ObjectPath("/org/freedesktop/login1")
|
||||
login1Iface = "org.freedesktop.login1.Manager"
|
||||
)
|
||||
|
||||
// systemSocket is the system bus's socket, whose folder the watcher watches when its connection dropped.
|
||||
var systemSocket = "/run/dbus/system_bus_socket"
|
||||
|
||||
// ratingProperties are the network manager's properties whose change the watcher acts on (§14).
|
||||
var ratingProperties = map[string]bool{"Connectivity": true, "PrimaryConnection": true,
|
||||
"ConnectivityCheckEnabled": true, "ConnectivityCheckAvailable": true, "ConnectivityCheckUri": true}
|
||||
|
||||
type dbusSystem struct {
|
||||
conn *dbus.Conn
|
||||
}
|
||||
|
||||
func dialSystemBus() (systemBus, error) {
|
||||
conn, err := dbus.ConnectSystemBus()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dbusSystem{conn: conn}, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) close() { d.conn.Close() }
|
||||
|
||||
func (d *dbusSystem) listen() (<-chan signal, error) {
|
||||
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(nmPath), dbus.WithMatchInterface(propsIface),
|
||||
dbus.WithMatchMember("PropertiesChanged")); err != nil {
|
||||
return nil, fmt.Errorf("hearing the network manager: %w", err)
|
||||
}
|
||||
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(login1Path), dbus.WithMatchInterface(login1Iface),
|
||||
dbus.WithMatchMember("SessionNew")); err != nil {
|
||||
return nil, fmt.Errorf("hearing logind: %w", err)
|
||||
}
|
||||
in := make(chan *dbus.Signal, 64)
|
||||
d.conn.Signal(in)
|
||||
out := make(chan signal)
|
||||
go func() {
|
||||
// godbus closes in when the connection drops.
|
||||
for s := range in {
|
||||
if heard, ok := readSignal(s); ok {
|
||||
out <- heard
|
||||
}
|
||||
}
|
||||
close(out)
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// readSignal is what the watcher hears in a signal of the system bus: the network manager's PropertiesChanged naming
|
||||
// a property of the rating, or logind's SessionNew with the new session's object.
|
||||
func readSignal(s *dbus.Signal) (signal, bool) {
|
||||
switch {
|
||||
case s.Path == nmPath && s.Name == propsIface+".PropertiesChanged" && len(s.Body) >= 3:
|
||||
if iface, _ := s.Body[0].(string); iface != nmName {
|
||||
return signal{}, false
|
||||
}
|
||||
changed, _ := s.Body[1].(map[string]dbus.Variant)
|
||||
for name := range changed {
|
||||
if ratingProperties[name] {
|
||||
return signal{Rating: true}, true
|
||||
}
|
||||
}
|
||||
invalidated, _ := s.Body[2].([]string)
|
||||
for _, name := range invalidated {
|
||||
if ratingProperties[name] {
|
||||
return signal{Rating: true}, true
|
||||
}
|
||||
}
|
||||
case s.Path == login1Path && s.Name == login1Iface+".SessionNew" && len(s.Body) >= 2:
|
||||
if path, ok := s.Body[1].(dbus.ObjectPath); ok {
|
||||
return signal{Session: string(path)}, true
|
||||
}
|
||||
}
|
||||
return signal{}, false
|
||||
}
|
||||
|
||||
func (d *dbusSystem) rating() (Rating, error) {
|
||||
nm := d.conn.Object(nmName, nmPath)
|
||||
var r Rating
|
||||
for name, into := range map[string]any{"Connectivity": &r.Connectivity, "ConnectivityCheckEnabled": &r.CheckEnabled,
|
||||
"ConnectivityCheckAvailable": &r.CheckAvailable, "ConnectivityCheckUri": &r.CheckURI} {
|
||||
v, err := nm.GetProperty(nmName + "." + name)
|
||||
if err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
|
||||
}
|
||||
if err := v.Store(into); err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
v, err := nm.GetProperty(nmName + ".PrimaryConnection")
|
||||
if err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's PrimaryConnection: %w", err)
|
||||
}
|
||||
path, _ := v.Value().(dbus.ObjectPath)
|
||||
r.Connection = string(path)
|
||||
if !r.active() {
|
||||
return r, nil
|
||||
}
|
||||
// A connection that went between the two reads is read as it is said: its name and link empty.
|
||||
active := d.conn.Object(nmName, path)
|
||||
if v, err := active.GetProperty(nmActive + ".Id"); err == nil {
|
||||
r.Network, _ = v.Value().(string)
|
||||
}
|
||||
if v, err := active.GetProperty(nmActive + ".Devices"); err == nil {
|
||||
if devices, _ := v.Value().([]dbus.ObjectPath); len(devices) > 0 {
|
||||
if v, err := d.conn.Object(nmName, devices[0]).GetProperty(nmDevice + ".Interface"); err == nil {
|
||||
r.Link, _ = v.Value().(string)
|
||||
}
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// systemSocketExists says whether the system bus's socket is there now.
|
||||
func systemSocketExists() bool {
|
||||
_, err := os.Stat(systemSocket)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// systemSocketThere fires at each file event of the kernel that makes the system bus's socket in its folder, until stop
|
||||
// closes: the one moment, beside rating-again, the watcher dials the system bus again (§14; note d). It never fires
|
||||
// for a socket that is merely there, so a bus that refuses the watcher is not dialled again in a loop.
|
||||
func systemSocketThere(stop <-chan struct{}) <-chan struct{} {
|
||||
return fileMade(filepath.Dir(systemSocket), filepath.Base(systemSocket), stop)
|
||||
}
|
||||
|
||||
// readInotify reads the names of one read's file events; an error once the descriptor is closed.
|
||||
func readInotify(f *os.File) ([]string, error) {
|
||||
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
|
||||
n, err := f.Read(buf)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrClosed) {
|
||||
journal("a watch of file events failed: %v", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for off := 0; off+unix.SizeofInotifyEvent <= n; {
|
||||
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
|
||||
nameAt := off + unix.SizeofInotifyEvent
|
||||
end := nameAt + int(ev.Len)
|
||||
if end > n {
|
||||
break
|
||||
}
|
||||
name := buf[nameAt:end]
|
||||
for i, b := range name {
|
||||
if b == 0 {
|
||||
name = name[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
names = append(names, string(name))
|
||||
off = end
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) sessions(uid uint32) ([]loginSession, error) {
|
||||
var listed []struct {
|
||||
ID string
|
||||
UID uint32
|
||||
User string
|
||||
Seat string
|
||||
Path dbus.ObjectPath
|
||||
}
|
||||
if err := d.conn.Object(login1Name, login1Path).Call(login1Iface+".ListSessions", 0).Store(&listed); err != nil {
|
||||
return nil, fmt.Errorf("logind's sessions: %w", err)
|
||||
}
|
||||
var out []loginSession
|
||||
for _, l := range listed {
|
||||
if l.UID != uid {
|
||||
continue
|
||||
}
|
||||
s, err := d.session(string(l.Path))
|
||||
if err != nil {
|
||||
journal("reading session %s failed: %v", l.ID, err)
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) session(path string) (loginSession, error) {
|
||||
o := d.conn.Object(login1Name, dbus.ObjectPath(path))
|
||||
s := loginSession{Path: path}
|
||||
var user struct {
|
||||
UID uint32
|
||||
Path dbus.ObjectPath
|
||||
}
|
||||
for name, into := range map[string]any{"Id": &s.ID, "Type": &s.Type, "Remote": &s.Remote, "State": &s.State,
|
||||
"User": &user} {
|
||||
v, err := o.GetProperty("org.freedesktop.login1.Session." + name)
|
||||
if err != nil {
|
||||
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
|
||||
}
|
||||
if err := dbus.Store([]any{v.Value()}, into); err != nil {
|
||||
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
|
||||
}
|
||||
}
|
||||
s.UID = user.UID
|
||||
v, err := d.conn.Object(login1Name, user.Path).GetProperty("org.freedesktop.login1.User.RuntimePath")
|
||||
if err != nil {
|
||||
return s, fmt.Errorf("the user %d's RuntimePath: %w", user.UID, err)
|
||||
}
|
||||
s.RuntimePath, _ = v.Value().(string)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// userEnvironment is the user manager's Environment, read over the session bus at bus.
|
||||
func userEnvironment(bus string) ([]string, error) {
|
||||
conn, err := dbus.Connect(bus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
v, err := conn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1").
|
||||
GetProperty("org.freedesktop.systemd1.Manager.Environment")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env, _ := v.Value().([]string)
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// fileEvents fires at each file event of the kernel that makes a file in one of dirs (a burst is one), until stop
|
||||
// closes. A folder that is not there is not watched, and said.
|
||||
func fileEvents(dirs []string, stop <-chan struct{}) <-chan struct{} {
|
||||
return watchFiles(dirs, nil, stop)
|
||||
}
|
||||
|
||||
// fileMade fires at each file event of the kernel that makes name in dir, until stop closes.
|
||||
func fileMade(dir, name string, stop <-chan struct{}) <-chan struct{} {
|
||||
return watchFiles([]string{dir}, func(made string) bool { return made == name }, stop)
|
||||
}
|
||||
|
||||
// watchFiles fires at each file event that makes a file in dirs whose name match takes (any, when nil).
|
||||
func watchFiles(dirs []string, match func(string) bool, stop <-chan struct{}) <-chan struct{} {
|
||||
out := make(chan struct{}, 1)
|
||||
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
|
||||
if err != nil {
|
||||
journal("watching %v failed: %v", dirs, err)
|
||||
return out
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
if _, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO); err != nil {
|
||||
journal("watching %s failed: %v", dir, err)
|
||||
}
|
||||
}
|
||||
f := os.NewFile(uintptr(fd), "inotify")
|
||||
go func() {
|
||||
<-stop
|
||||
f.Close()
|
||||
}()
|
||||
go func() {
|
||||
defer f.Close()
|
||||
for {
|
||||
names, err := readInotify(f)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
matched := match == nil
|
||||
for _, name := range names {
|
||||
matched = matched || match(name)
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case out <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// pathsMade hands each path a file event of the kernel makes in one of dirs, until stop closes; a folder that is not
|
||||
// there is not watched, and said.
|
||||
func pathsMade(dirs []string, stop <-chan struct{}) <-chan string {
|
||||
out := make(chan string, 16)
|
||||
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
|
||||
if err != nil {
|
||||
journal("watching %v failed: %v", dirs, err)
|
||||
return out
|
||||
}
|
||||
wds := map[int32]string{}
|
||||
for _, dir := range dirs {
|
||||
wd, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO)
|
||||
if err != nil {
|
||||
journal("watching %s failed: %v", dir, err)
|
||||
continue
|
||||
}
|
||||
wds[int32(wd)] = dir
|
||||
}
|
||||
f := os.NewFile(uintptr(fd), "inotify")
|
||||
go func() {
|
||||
<-stop
|
||||
f.Close()
|
||||
}()
|
||||
go func() {
|
||||
defer f.Close()
|
||||
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
|
||||
for {
|
||||
n, err := f.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for off := 0; off+unix.SizeofInotifyEvent <= n; {
|
||||
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
|
||||
nameAt := off + unix.SizeofInotifyEvent
|
||||
end := nameAt + int(ev.Len)
|
||||
if end > n {
|
||||
break
|
||||
}
|
||||
name := string(bytes.TrimRight(buf[nameAt:end], "\x00"))
|
||||
off = end
|
||||
if dir, ok := wds[ev.Wd]; ok && name != "" {
|
||||
select {
|
||||
case out <- filepath.Join(dir, name):
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// The uplink holder's tools bundle: the node-uplink seat's verbs (novox/hq ADR 0241), served by the node's
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own. stdout is
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own, and gives the
|
||||
// holder's own subcommands, tools and the work its bundle starts beside them (design 08 sign-in-page §11). stdout is
|
||||
// the MCP channel; this says nothing else.
|
||||
package main
|
||||
|
||||
@@ -11,8 +12,16 @@ import (
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func tools(m Machine) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
// holderOwn is what a holder adds to the seat's verbs, from its manager.go: its subcommands (a process of the module
|
||||
// runs one, as `uplink-tools <name>`), its own tools and the work its bundle starts once it serves.
|
||||
type holderOwn struct {
|
||||
Commands map[string]func(args []string) error
|
||||
Tools []stdio.Tool
|
||||
Start func()
|
||||
}
|
||||
|
||||
func tools(m Machine, own holderOwn) []stdio.Tool {
|
||||
return append([]stdio.Tool{
|
||||
{Name: seat + ".resolvers",
|
||||
Description: "The machine's resolver file as it is now: the resolvers, search domains and options it lists, " +
|
||||
"whether it is the file the mesh declares, and when it is not, who wrote it as far as the machine shows " +
|
||||
@@ -23,12 +32,40 @@ func tools(m Machine) []stdio.Tool {
|
||||
"leaves through it, and the resolvers and search domains the network manager knows for it — a VPN's " +
|
||||
"tunnel included. (r)",
|
||||
Run: func(map[string]any) (any, error) { return m.Links(context.Background()) }},
|
||||
}, own.Tools...)
|
||||
}
|
||||
|
||||
// command is the holder's subcommand args name, or an error naming it when the holder has none such; nil with no args,
|
||||
// which is the bundle.
|
||||
func command(own holderOwn, args []string) (func(args []string) error, error) {
|
||||
if len(args) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if run, ok := own.Commands[args[0]]; ok {
|
||||
return run, nil
|
||||
}
|
||||
return nil, fmt.Errorf("uplink-tools has no subcommand %q", args[0])
|
||||
}
|
||||
|
||||
func main() {
|
||||
m := Machine{ResolvPath: ResolvConf, Run: execRunner, Running: running, LinkDNS: managerDNS}
|
||||
if err := stdio.Serve("", tools(m)); err != nil {
|
||||
own := holder(m)
|
||||
run, err := command(own, os.Args[1:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if run != nil {
|
||||
if err := run(os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if own.Start != nil {
|
||||
go own.Start()
|
||||
}
|
||||
if err := stdio.Serve("", tools(m, own)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func managerDNS(ctx context.Context) (map[string]LinkDNS, error) {
|
||||
@@ -50,3 +52,20 @@ func parseNmcli(out string) map[string]LinkDNS {
|
||||
flush()
|
||||
return links
|
||||
}
|
||||
|
||||
// holder is what networkmanager adds to the seat's verbs (design 08 sign-in-page §11): the watcher, `uplink-tools
|
||||
// watch`.
|
||||
func holder(m Machine) holderOwn {
|
||||
own := holderOwn{Commands: map[string]func([]string) error{"watch": watch}}
|
||||
f, err := theFolder()
|
||||
if err != nil {
|
||||
journal("the module's folder: %v", err)
|
||||
return own
|
||||
}
|
||||
b := newBundle(f)
|
||||
own.Tools = b.tools()
|
||||
own.Start = func() {
|
||||
b.start(bundleRuns{files: fileEvents, fileMade: fileMade, onHeartbeat: stdio.OnHeartbeat, subscribe: stdio.Subscribe})
|
||||
}
|
||||
return own
|
||||
}
|
||||
|
||||
@@ -16,3 +16,10 @@ func TestNmcliIsReadPerDevice(t *testing.T) {
|
||||
t.Fatal("a link with no names was said")
|
||||
}
|
||||
}
|
||||
|
||||
// networkmanager's own part: the watcher's subcommand (design 08 sign-in-page §11).
|
||||
func TestNetworkManagerRunsItsWatcherAsASubcommand(t *testing.T) {
|
||||
if run, err := command(holder(Machine{}), []string{"watch"}); err != nil || run == nil {
|
||||
t.Fatalf("uplink-tools watch is not the watcher: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package main
|
||||
|
||||
// The bundle gives the resolver the check's host name (design 08 sign-in-page §13): it calls
|
||||
// `<node>/node-resolver.uplink-names` with the check address's host name, or an empty list when there is no address,
|
||||
// and writes the call to names.json. Which module holds node-resolver on its node it reads from the seat
|
||||
// mesh-module-assigner's assignments; none is `no holder`, which is no failure (DQ-8). A failed call is written to the
|
||||
// journal, stands failed in names.json and is asked again at the next moment, never on a timer.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
const (
|
||||
// runningPattern is node-engine's running event, as the manifest consumes it: node-engine.running.<node>.<module>.
|
||||
runningPattern = "node-engine.running.*.*"
|
||||
assignmentsKey = "seat:mesh-module-assigner.assignments"
|
||||
)
|
||||
|
||||
// namer calls uplink-names, one call at a time.
|
||||
type namer struct {
|
||||
folder Folder
|
||||
// ask calls a verb on the mesh as the module, through the runtime.
|
||||
ask func(key string, body any) (json.RawMessage, error)
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// hostOf is the check address's host name, lower-cased, as uplink-names takes it: none for an empty address.
|
||||
func hostOf(address string) ([]string, error) {
|
||||
if address == "" {
|
||||
return []string{}, nil
|
||||
}
|
||||
u, err := url.Parse(address)
|
||||
if err != nil || u.Hostname() == "" {
|
||||
return nil, fmt.Errorf("the check address %q names no host", address)
|
||||
}
|
||||
return []string{strings.ToLower(u.Hostname())}, nil
|
||||
}
|
||||
|
||||
// resolverHolder is the module that holds node-resolver on this node, "" when none does (DQ-8).
|
||||
func (n *namer) resolverHolder() (string, error) {
|
||||
raw, err := n.ask(assignmentsKey, map[string]string{"node": n.folder.Node, "seats": "true"})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reading the assignments: %w", err)
|
||||
}
|
||||
var answer struct {
|
||||
Seats []struct {
|
||||
Seat string `json:"seat"`
|
||||
Holders []struct {
|
||||
Module string `json:"module"`
|
||||
Node string `json:"node"`
|
||||
} `json:"holders"`
|
||||
} `json:"seats"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &answer); err != nil {
|
||||
return "", fmt.Errorf("the assignments answered in no form this reads: %w", err)
|
||||
}
|
||||
for _, s := range answer.Seats {
|
||||
if s.Seat != noderesolver.Seat {
|
||||
continue
|
||||
}
|
||||
for _, h := range s.Holders {
|
||||
if h.Node == n.folder.Node {
|
||||
return h.Module, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// give calls uplink-names now with the check address's host name and writes the call to names.json.
|
||||
func (n *namer) give(moment string) NamesCall {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
call := NamesCall{Names: []string{}, At: n.now()}
|
||||
address, err := n.folder.checkAddress()
|
||||
if err == nil {
|
||||
call.Names, err = hostOf(address)
|
||||
}
|
||||
if err == nil {
|
||||
call.Result, err = n.call(call.Names)
|
||||
}
|
||||
if err != nil {
|
||||
call.Result = err.Error()
|
||||
}
|
||||
if call.Names == nil {
|
||||
call.Names = []string{}
|
||||
}
|
||||
if err := n.folder.writeNames(call); err != nil {
|
||||
journal("writing names.json failed: %v", err)
|
||||
}
|
||||
journal("uplink-names %v at %s: %s", call.Names, moment, call.Result)
|
||||
return call
|
||||
}
|
||||
|
||||
func (n *namer) call(names []string) (string, error) {
|
||||
holder, err := n.resolverHolder()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if holder == "" {
|
||||
return resultNoHolder, nil
|
||||
}
|
||||
raw, err := n.ask(uplinkNamesKey(n.folder.Node), noderesolver.UplinkNamesInput{Names: names})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s/%s.%s: %w", n.folder.Node, noderesolver.Seat, noderesolver.VerbUplinkNames, err)
|
||||
}
|
||||
if _, _, err := noderesolver.DecodeUplinkNamesAnswer(raw); err != nil {
|
||||
return "", fmt.Errorf("uplink-names answered in no form this reads: %w", err)
|
||||
}
|
||||
return resultOK, nil
|
||||
}
|
||||
|
||||
func uplinkNamesKey(node string) string {
|
||||
return "seat:" + noderesolver.Seat + "." + noderesolver.VerbUplinkNames + "@" + node
|
||||
}
|
||||
|
||||
// running hears node-engine's running: one for this node's holder of node-resolver, running, is a moment to call
|
||||
// uplink-names; every other is dropped, another node's first (§13).
|
||||
func (n *namer) running(e stdio.Envelope) error {
|
||||
parts := strings.Split(e.Key, ".")
|
||||
if len(parts) != 4 || parts[2] != n.folder.Node {
|
||||
return nil
|
||||
}
|
||||
var body struct {
|
||||
Module string `json:"module"`
|
||||
Stopped bool `json:"stopped"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Body, &body); err != nil || body.Stopped {
|
||||
return nil
|
||||
}
|
||||
holder, err := n.resolverHolder()
|
||||
if err != nil {
|
||||
journal("hearing %s: %v", e.Key, err)
|
||||
return nil
|
||||
}
|
||||
if holder != "" && holder == parts[3] {
|
||||
n.give(holder + " running")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The mesh stood in for the bundle's asks: the assignments naming this node's holder of node-resolver (none when
|
||||
// holder is empty), and node-resolver's uplink-names, failing while fail is set.
|
||||
type fakeMesh struct {
|
||||
mu sync.Mutex
|
||||
holder string
|
||||
fail error
|
||||
calls []string
|
||||
routes string
|
||||
}
|
||||
|
||||
func (m *fakeMesh) ask(key string, body any) (json.RawMessage, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
switch key {
|
||||
case assignmentsKey:
|
||||
in := body.(map[string]string)
|
||||
if in["node"] != "laptop" || in["seats"] != "true" {
|
||||
return nil, errors.New("asked the assignments of another node")
|
||||
}
|
||||
seats := `{"seats":[{"seat":"node-uplink","holders":[{"module":"networkmanager","node":"laptop"}]}`
|
||||
if m.holder != "" {
|
||||
seats += `,{"seat":"node-resolver","holders":[{"module":"` + m.holder + `","node":"laptop"}]}`
|
||||
}
|
||||
return json.RawMessage(seats + `]}`), nil
|
||||
case "seat:node-resolver.uplink-names@laptop":
|
||||
raw, _ := json.Marshal(body)
|
||||
m.calls = append(m.calls, string(raw))
|
||||
if m.fail != nil {
|
||||
return nil, m.fail
|
||||
}
|
||||
return json.RawMessage(`{"names":["check.example.net"],"link":"wlan0","set_at":"2026-11-24T19:00:00Z"}`), nil
|
||||
case "seat:node-resolver.routes@laptop":
|
||||
if m.routes == "" {
|
||||
return nil, errors.New("no routes")
|
||||
}
|
||||
return json.RawMessage(m.routes), nil
|
||||
}
|
||||
return nil, errors.New("no such verb " + key)
|
||||
}
|
||||
|
||||
func (m *fakeMesh) called() []string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return append([]string(nil), m.calls...)
|
||||
}
|
||||
|
||||
// uplink-names is called at the bundle's start, on a changed check-address, when the bus connection comes back and on
|
||||
// a running holder of node-resolver on its own node; every other running is dropped; no holder is recorded and is
|
||||
// healthy, a failed call stands failed (design 08 sign-in-page §13, §25).
|
||||
func TestUplinkNamesIsCalledAtEachMoment(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
f := aFolder(t)
|
||||
if err := f.writeCheckAddress("http://Check.Example.net/connecttest"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mesh := &fakeMesh{holder: "systemd-resolved"}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: (&fakeStream{}).publish},
|
||||
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
|
||||
check := make(chan struct{})
|
||||
var running func(stdio.Envelope) error
|
||||
var hook func(stdio.Heartbeat)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
b.start(bundleRuns{files: func([]string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
fileMade: func(dir, name string, _ <-chan struct{}) <-chan struct{} {
|
||||
if dir != f.Dir || name != "check-address" {
|
||||
t.Errorf("watched %s in %s", name, dir)
|
||||
}
|
||||
return check
|
||||
},
|
||||
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
|
||||
subscribe: func(pattern string, h func(stdio.Envelope) error) error {
|
||||
if pattern != "node-engine.running.*.*" {
|
||||
t.Errorf("subscribed to %s", pattern)
|
||||
}
|
||||
running = h
|
||||
return nil
|
||||
}})
|
||||
close(done)
|
||||
}()
|
||||
if err := f.writeCheckAddress(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check <- struct{}{}
|
||||
f.writeCheckAddress("https://other.example.net/")
|
||||
close(check)
|
||||
<-done
|
||||
want := []string{`{"names":["check.example.net"]}`, `{"names":[]}`}
|
||||
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("at the start and a changed check address: called %q", got)
|
||||
}
|
||||
hook(stdio.Heartbeat{Missed: true})
|
||||
hook(stdio.Heartbeat{})
|
||||
for _, e := range []stdio.Envelope{
|
||||
{Key: "node-engine.running.other.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved"}`)},
|
||||
{Key: "node-engine.running.laptop.i3", Body: json.RawMessage(`{"module":"i3"}`)},
|
||||
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","stopped":true}`)},
|
||||
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","healthy":true}`)},
|
||||
} {
|
||||
if err := running(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want = append(want, `{"names":["other.example.net"]}`, `{"names":["other.example.net"]}`)
|
||||
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("at the connection's return and a running holder: called %q", got)
|
||||
}
|
||||
if c, _ := f.names(); c == nil || c.Result != resultOK || strings.Join(c.Names, " ") != "other.example.net" {
|
||||
t.Fatalf("names.json holds %+v", c)
|
||||
}
|
||||
|
||||
mesh.holder = ""
|
||||
if c := b.names.give("a test"); c.Result != resultNoHolder || c.Failed() || len(mesh.called()) != 4 {
|
||||
t.Fatalf("no holder gave %+v after %d calls", c, len(mesh.called()))
|
||||
}
|
||||
mesh.holder, mesh.fail = "systemd-resolved", errors.New("no answer within its bound")
|
||||
if c := b.names.give("a test"); !c.Failed() || !strings.Contains(c.Result, "no answer within its bound") {
|
||||
t.Fatalf("a failed call gave %+v", c)
|
||||
}
|
||||
if c, _ := f.names(); c == nil || !c.Failed() {
|
||||
t.Fatalf("names.json holds %+v", c)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "uplink-names [other.example.net] at a test: laptop/node-resolver.uplink-names: no answer") {
|
||||
t.Fatalf("the failed call is not in the journal: %q", lines())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
// Telling the person (design 08 sign-in-page §19): org.freedesktop.Notifications.Notify on the session's bus, the
|
||||
// desktop notification service, app_name mesh.
|
||||
|
||||
import "github.com/godbus/dbus/v5"
|
||||
|
||||
func notifyOn(bus string, n note) error {
|
||||
conn, err := dbus.Connect(bus)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
hints := map[string]dbus.Variant{}
|
||||
if n.Critical {
|
||||
hints["urgency"] = dbus.MakeVariant(byte(2))
|
||||
}
|
||||
return conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").
|
||||
Call("org.freedesktop.Notifications.Notify", 0, "mesh", uint32(0), "", n.Summary, n.Body, []string{}, hints,
|
||||
int32(-1)).Err
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package main
|
||||
|
||||
// Opening the page and telling the person (design 08 sign-in-page §15, §18, §19): at the three moments, once per ask,
|
||||
// in the person's session. The open runs beside the watch; rating changes heard meanwhile are handled after it, in the
|
||||
// order they came.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// openBound is how long the watcher waits for the opener: ended within it, its status decides; still running at it,
|
||||
// the page is opening and the run is left to go on (§18).
|
||||
const openBound = 10 * time.Second
|
||||
|
||||
// desk is the person's desktop as the watcher reaches it: an address opened in their session, a notification shown.
|
||||
type desk interface {
|
||||
open(s Session, address string) openOutcome
|
||||
notify(s Session, n note) error
|
||||
}
|
||||
|
||||
// openOutcome is how an open ended: opened, opening (still running at its bound) or failed, with the program and the
|
||||
// reason of a failure.
|
||||
type openOutcome struct {
|
||||
Address string `json:"address"`
|
||||
Program string `json:"program,omitempty"`
|
||||
Outcome string `json:"outcome"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// The outcomes of an open.
|
||||
const (
|
||||
outcomeOpened = "opened"
|
||||
outcomeOpening = "opening"
|
||||
outcomeFailed = "failed"
|
||||
)
|
||||
|
||||
// note is one notification: its summary and body, critical or not, and, once shown, when and whether it failed.
|
||||
type note struct {
|
||||
Summary string `json:"summary"`
|
||||
Body string `json:"body"`
|
||||
Critical bool `json:"critical,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
const askedSummary = "This network asks you to sign in"
|
||||
|
||||
// signInNote is what the person is told after an open, by its outcome (§19).
|
||||
func signInNote(network, address string, o openOutcome) note {
|
||||
switch o.Outcome {
|
||||
case outcomeOpened:
|
||||
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is open in %s.", network, o.Program)}
|
||||
case outcomeOpening:
|
||||
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is opening in %s.", network, o.Program)}
|
||||
}
|
||||
return note{Summary: askedSummary, Critical: true,
|
||||
Body: fmt.Sprintf("%s: the page did not open (%s); open %s in a browser.", network, o.Reason, address)}
|
||||
}
|
||||
|
||||
// signedInNote is what the person is told when the rating leaves PORTAL for FULL (§19).
|
||||
func signedInNote(network string) note {
|
||||
return note{Summary: "The network is open", Body: network + ": signed in."}
|
||||
}
|
||||
|
||||
// present opens the address in the person's session, s or the one found now, and then tells them (§15, §18, §19),
|
||||
// beside the watch; with no session found it opens and shows nothing, and the events are kept all the same (§15,
|
||||
// §16).
|
||||
func (w *Watcher) present(s *Session, network, address string) {
|
||||
if w.opening {
|
||||
w.later = append(w.later, func() { w.present(s, network, address) })
|
||||
return
|
||||
}
|
||||
if s = w.sessionNow(s, "the sign-in page of "+network+" is not opened"); s == nil {
|
||||
return
|
||||
}
|
||||
session := *s
|
||||
w.opening = true
|
||||
w.Beside(func() func() {
|
||||
o := w.Desk.open(session, address)
|
||||
n := signInNote(network, address, o)
|
||||
err := w.Desk.notify(session, n)
|
||||
return func() {
|
||||
o.At = w.Now()
|
||||
w.state.LastOpen = &o
|
||||
if o.Outcome == outcomeFailed {
|
||||
journal("opening %s in session %s failed: %s", address, session.ID, o.Reason)
|
||||
} else {
|
||||
journal("the sign-in page %s is %s in %s", address, o.Outcome, o.Program)
|
||||
}
|
||||
w.shown(n, err)
|
||||
w.opening = false
|
||||
w.drain()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// tellSignedIn tells the person the network is open, in their session; with none, nothing (§19).
|
||||
func (w *Watcher) tellSignedIn(network string) {
|
||||
s := w.sessionNow(nil, "the network being open is not shown")
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
session, n := *s, signedInNote(network)
|
||||
w.Beside(func() func() {
|
||||
err := w.Desk.notify(session, n)
|
||||
return func() { w.shown(n, err) }
|
||||
})
|
||||
}
|
||||
|
||||
// sessionNow is s, or the person's session found now; nil with a journal line saying what is not done.
|
||||
func (w *Watcher) sessionNow(s *Session, notDone string) *Session {
|
||||
if s != nil {
|
||||
return s
|
||||
}
|
||||
found, err := w.findSession()
|
||||
if err != nil {
|
||||
journal("finding the person's session failed: %v; %s", err, notDone)
|
||||
return nil
|
||||
}
|
||||
if found == nil {
|
||||
journal("no graphical session: %s", notDone)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (w *Watcher) shown(n note, err error) {
|
||||
n.At = w.Now()
|
||||
if err != nil {
|
||||
n.Error = err.Error()
|
||||
journal("showing the notification %q failed: %v", n.Summary, err)
|
||||
} else {
|
||||
journal("showed the notification %q: %s", n.Summary, n.Body)
|
||||
}
|
||||
w.state.LastNotification = &n
|
||||
}
|
||||
|
||||
// drain handles, in the order they came, what was heard during an open, until one starts another open.
|
||||
func (w *Watcher) drain() {
|
||||
for len(w.later) > 0 && !w.opening {
|
||||
next := w.later[0]
|
||||
w.later = w.later[1:]
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
// besideLoop runs work beside the loop and hands its end back to the loop, which runs it.
|
||||
func (w *Watcher) besideLoop(work func() func()) {
|
||||
go func() { w.ends <- work() }()
|
||||
}
|
||||
|
||||
// sessionDesk opens and tells in the person's session: the programs run with the session's bus and runtime directory
|
||||
// in their environment.
|
||||
type sessionDesk struct {
|
||||
// query runs a program to its end, within openBound, and answers its output.
|
||||
query func(env []string, name string, args ...string) (string, error)
|
||||
// start starts a program; its end, with its status, comes on the channel.
|
||||
start func(env []string, name string, args ...string) (<-chan error, error)
|
||||
after func(time.Duration) <-chan time.Time
|
||||
show func(bus string, n note) error
|
||||
}
|
||||
|
||||
func newSessionDesk() sessionDesk {
|
||||
return sessionDesk{query: queryProgram, start: startProgram, after: time.After, show: notifyOn}
|
||||
}
|
||||
|
||||
// open asks xdg-mime for the scheme's program, then runs `systemd-run --user --collect --quiet --wait -- xdg-open
|
||||
// <address>`, the address one argument and no shell, so the browser runs under the person's user manager and outlives
|
||||
// the watcher (§18).
|
||||
func (d sessionDesk) open(s Session, address string) openOutcome {
|
||||
o := openOutcome{Address: address, Outcome: outcomeFailed}
|
||||
u, err := url.Parse(address)
|
||||
if err != nil {
|
||||
o.Reason = err.Error()
|
||||
return o
|
||||
}
|
||||
program, err := d.query(s.Env(), "xdg-mime", "query", "default", "x-scheme-handler/"+u.Scheme)
|
||||
if err != nil {
|
||||
o.Reason = "xdg-mime: " + err.Error()
|
||||
return o
|
||||
}
|
||||
if program = strings.TrimSpace(program); program == "" {
|
||||
o.Reason = "no default program for " + u.Scheme
|
||||
return o
|
||||
}
|
||||
done, err := d.start(s.Env(), "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", address)
|
||||
if err != nil {
|
||||
o.Reason = "systemd-run: " + err.Error()
|
||||
return o
|
||||
}
|
||||
o.Program = program
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
o.Program, o.Reason = "", "xdg-open "+status(err)
|
||||
return o
|
||||
}
|
||||
o.Outcome = outcomeOpened
|
||||
case <-d.after(openBound):
|
||||
o.Outcome = outcomeOpening
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (d sessionDesk) notify(s Session, n note) error { return d.show(s.Bus(), n) }
|
||||
|
||||
// status names how a program ended: its exit status, or why it did not end with one.
|
||||
func status(err error) string {
|
||||
var exit *exec.ExitError
|
||||
if errors.As(err, &exit) {
|
||||
return fmt.Sprintf("ended with status %d", exit.ExitCode())
|
||||
}
|
||||
return "failed: " + err.Error()
|
||||
}
|
||||
|
||||
func queryProgram(env []string, name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), openBound)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
cmd.Env = env
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", errors.New(status(err))
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
|
||||
func startProgram(env []string, name string, args ...string) (<-chan error, error) {
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Env = env
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
return done, nil
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// aDeskWatcher is a watcher with the person's session found and the desktop stood in; it starts subscribed, the rating
|
||||
// at its start being start.
|
||||
func aDeskWatcher(t *testing.T, start Rating) (*Watcher, *fakeSystem, *fakeDesk) {
|
||||
t.Helper()
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(start)
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil }
|
||||
w.subscribe()
|
||||
return w, sys, w.Desk.(*fakeDesk)
|
||||
}
|
||||
|
||||
const openedNote = "This network asks you to sign in: guest-example: its sign-in page is open in browser.desktop."
|
||||
|
||||
// PORTAL at a join and PORTAL at the watcher's start each open the page and show one notification; a second PORTAL
|
||||
// without a leave does nothing; PORTAL to FULL shows that the network is open, PORTAL to any other rating shows nothing
|
||||
// (design 08 sign-in-page §15, §19, §25).
|
||||
func TestTheRatingOpensThePageAndTellsThePersonOncePerAsk(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
start Rating
|
||||
then []Rating
|
||||
opens int
|
||||
notes []string
|
||||
journal string
|
||||
}{
|
||||
{"PORTAL at a join", guest(ratingFull), []Rating{guest(ratingPortal)}, 1, []string{openedNote},
|
||||
"showed the notification"},
|
||||
{"PORTAL at the start", guest(ratingPortal), nil, 1, []string{openedNote}, "the sign-in page http://check.example.net/ is opened in browser.desktop"},
|
||||
{"a second PORTAL", guest(ratingPortal), []Rating{guest(ratingPortal), guest(ratingPortal)}, 1,
|
||||
[]string{openedNote}, ""},
|
||||
{"PORTAL to FULL", guest(ratingPortal), []Rating{guest(ratingFull)}, 1,
|
||||
[]string{openedNote, "The network is open: guest-example: signed in."}, ""},
|
||||
{"PORTAL to LIMITED", guest(ratingPortal), []Rating{guest(ratingLimited)}, 1, []string{openedNote}, ""},
|
||||
{"PORTAL, left, PORTAL on another", guest(ratingPortal), []Rating{other(ratingPortal)}, 2,
|
||||
[]string{openedNote, "This network asks you to sign in: home-example: its sign-in page is open in browser.desktop."}, ""},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
w, sys, desk := aDeskWatcher(t, c.start)
|
||||
for _, r := range c.then {
|
||||
sys.set(r)
|
||||
w.heardSignal(signal{Rating: true})
|
||||
}
|
||||
if got := desk.opened(); len(got) != c.opens {
|
||||
t.Fatalf("opened %q", got)
|
||||
}
|
||||
if got := desk.shown(); strings.Join(got, "|") != strings.Join(c.notes, "|") {
|
||||
t.Fatalf("showed %q, want %q", got, c.notes)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), c.journal) {
|
||||
t.Fatalf("the journal does not say %q: %q", c.journal, lines())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An opener that fails gives the critical notification naming the reason and the address (§19, §25).
|
||||
func TestAFailingOpenerGivesTheCriticalNotification(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
|
||||
desk := w.Desk.(*fakeDesk)
|
||||
desk.outcome = openOutcome{Address: "http://check.example.net/", Outcome: outcomeFailed, Reason: "xdg-open ended with status 4"}
|
||||
w.subscribe()
|
||||
sys.set(guest(ratingPortal))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
want := "critical This network asks you to sign in: guest-example: the page did not open (xdg-open ended with status 4); " +
|
||||
"open http://check.example.net/ in a browser."
|
||||
if got := desk.shown(); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("showed %q", got)
|
||||
}
|
||||
if w.state.LastOpen == nil || w.state.LastOpen.Outcome != outcomeFailed || w.state.LastNotification == nil {
|
||||
t.Fatalf("the state says %+v", w.state)
|
||||
}
|
||||
}
|
||||
|
||||
// A rating change heard while the page opens is handled after the open, in the order heard (§18, §25).
|
||||
func TestARatingChangeHeardDuringAnOpenIsHandledAfterIt(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
|
||||
var beside []func() func()
|
||||
w.Beside = func(work func() func()) { beside = append(beside, work) }
|
||||
w.subscribe()
|
||||
sys.set(guest(ratingPortal))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
sys.set(guest(ratingLimited))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
sys.set(guest(ratingFull))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
if got := keptSaid(t, w.Folder); len(got) != 2 || len(beside) != 1 {
|
||||
t.Fatalf("during the open: kept %q, %d run beside", got, len(beside))
|
||||
}
|
||||
beside[0]()()
|
||||
got := keptSaid(t, w.Folder)
|
||||
if len(got) != 3 || got[2] != "sign-in-ended no-longer-asked guest-example wlan0" {
|
||||
t.Fatalf("after the open: kept %q", got)
|
||||
}
|
||||
if w.opening || len(w.later) != 0 {
|
||||
t.Fatal("what was heard is still waiting")
|
||||
}
|
||||
}
|
||||
|
||||
// The opener in the person's session: xdg-mime asked for the scheme's program, then systemd-run --user with the address
|
||||
// as one argument, both with the session's bus and runtime directory; its status, or its bound, decides (§18).
|
||||
func TestTheOpenerRunsInThePersonsSession(t *testing.T) {
|
||||
s := Session{ID: "2", Type: "x11", RuntimePath: "/run/user/1000"}
|
||||
address := "http://check.example.net/a'b;c"
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
program string
|
||||
ends error
|
||||
running bool
|
||||
want openOutcome
|
||||
}{
|
||||
{"opened", "browser.desktop\n", nil, false, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened}},
|
||||
{"opening", "browser.desktop\n", nil, true, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpening}},
|
||||
{"failed", "browser.desktop\n", exitStatus(t, 3), false,
|
||||
openOutcome{Address: address, Outcome: outcomeFailed, Reason: "xdg-open ended with status 3"}},
|
||||
{"no program", "\n", nil, false, openOutcome{Address: address, Outcome: outcomeFailed, Reason: "no default program for http"}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var ran []string
|
||||
envOf := func(env []string) string {
|
||||
var out []string
|
||||
for _, kv := range env {
|
||||
if strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") || strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
|
||||
out = append(out, kv)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
bound := make(chan time.Time, 1)
|
||||
d := sessionDesk{
|
||||
query: func(env []string, name string, args ...string) (string, error) {
|
||||
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
|
||||
return c.program, nil
|
||||
},
|
||||
start: func(env []string, name string, args ...string) (<-chan error, error) {
|
||||
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
|
||||
if args[len(args)-1] != address {
|
||||
t.Errorf("the address is not one argument: %q", args)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
if c.running {
|
||||
bound <- time.Now()
|
||||
} else {
|
||||
done <- c.ends
|
||||
}
|
||||
return done, nil
|
||||
},
|
||||
after: func(d time.Duration) <-chan time.Time {
|
||||
if d != 10*time.Second {
|
||||
t.Errorf("the open's bound is %s", d)
|
||||
}
|
||||
return bound
|
||||
},
|
||||
}
|
||||
got := d.open(s, address)
|
||||
if got != c.want {
|
||||
t.Fatalf("answered %+v, want %+v", got, c.want)
|
||||
}
|
||||
env := "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus XDG_RUNTIME_DIR=/run/user/1000 | "
|
||||
want := []string{env + "xdg-mime query default x-scheme-handler/http"}
|
||||
if c.program != "\n" {
|
||||
want = append(want, env+"systemd-run --user --collect --quiet --wait -- xdg-open "+address)
|
||||
}
|
||||
if strings.Join(ran, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("ran\n%s\nwant\n%s", strings.Join(ran, "\n"), strings.Join(want, "\n"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// exitStatus is the error of a program that ended with status n.
|
||||
func exitStatus(t *testing.T, n int) error {
|
||||
t.Helper()
|
||||
err := exec.Command("sh", "-c", "exit "+string(rune('0'+n))).Run()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) {
|
||||
t.Fatalf("no exit status: %v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
// The bundle publishes the kept events (design 08 sign-in-page §20): in sequence order, on the seat's subject, each
|
||||
// with its message id as the bus's message id (the runtime prefixes it with the module), awaiting the stream's
|
||||
// acknowledgement, and deletes each file once acknowledged. A publish refused or unacknowledged stays in pending/, is
|
||||
// written to the journal and counted, and is published again at the next moment: the bundle's start, a file event of
|
||||
// the kernel on pending/, its bus connection coming back, or uplink_publish_again.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// publisher publishes the kept events, one round at a time.
|
||||
type publisher struct {
|
||||
folder Folder
|
||||
// publish says one event on the seat, de-duplicated by id, and answers once the stream acknowledged it.
|
||||
publish func(subject string, body json.RawMessage, id string) error
|
||||
|
||||
mu sync.Mutex
|
||||
refused int
|
||||
}
|
||||
|
||||
// publishResult is one round: how many were published and how many still wait.
|
||||
type publishResult struct {
|
||||
Published int `json:"published"`
|
||||
Waiting int `json:"waiting"`
|
||||
Refused string `json:"refused,omitempty"`
|
||||
}
|
||||
|
||||
// publishKept publishes every kept event in order; the first refused stops the round, so none is published before an
|
||||
// older one.
|
||||
func (p *publisher) publishKept(moment string) publishResult {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
var out publishResult
|
||||
kept, err := p.folder.pending()
|
||||
if err != nil {
|
||||
journal("reading the kept events at %s failed: %v", moment, err)
|
||||
out.Refused = err.Error()
|
||||
return out
|
||||
}
|
||||
for i, k := range kept {
|
||||
if err := p.publish(k.Subject, k.Body, k.MessageID); err != nil {
|
||||
p.refused++
|
||||
out.Waiting, out.Refused = len(kept)-i, err.Error()
|
||||
journal("publishing %s at %s was refused or not acknowledged: %v; %d left waiting", k.MessageID, moment, err,
|
||||
out.Waiting)
|
||||
return out
|
||||
}
|
||||
journal("published %s on %s", k.MessageID, k.Subject)
|
||||
out.Published++
|
||||
if err := p.folder.drop(k); err != nil {
|
||||
journal("deleting the published %s failed: %v", k.MessageID, err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// refusedSince is the publishes refused since the bundle's start.
|
||||
func (p *publisher) refusedSince() int {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.refused
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The bus stood in: every publish asked, the ids it refuses once, as the runtime answers a publish the stream did not
|
||||
// acknowledge.
|
||||
type fakeStream struct {
|
||||
mu sync.Mutex
|
||||
asked []string
|
||||
refuse map[string]bool
|
||||
}
|
||||
|
||||
func (s *fakeStream) publish(subject string, body json.RawMessage, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.asked = append(s.asked, id)
|
||||
if s.refuse[id] {
|
||||
delete(s.refuse, id)
|
||||
return errors.New("no acknowledgement")
|
||||
}
|
||||
if !json.Valid(body) || !strings.HasPrefix(subject, "mesh.seat.node-uplink.event.") {
|
||||
return errors.New("not an event of the seat")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *fakeStream) publishes() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return strings.Join(s.asked, " ")
|
||||
}
|
||||
|
||||
func keepThree(t *testing.T, f Folder) {
|
||||
t.Helper()
|
||||
for _, event := range []string{eventEnded, eventAsked, eventEnded} {
|
||||
if _, err := f.keep(event, eventSubject(event, f.Node), map[string]string{"node": f.Node}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The bundle publishes the kept events in order with their message ids and deletes each once acknowledged; a refused
|
||||
// one stays, with the ones after it, and is published at the next moment under the same id (design 08 sign-in-page
|
||||
// §20, §25).
|
||||
func TestTheBundlePublishesTheKeptEventsInOrder(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
f := aFolder(t)
|
||||
keepThree(t, f)
|
||||
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-asked.2": true}}
|
||||
p := &publisher{folder: f, publish: stream.publish}
|
||||
if r := p.publishKept("the bundle's start"); r.Published != 1 || r.Waiting != 2 || p.refusedSince() != 1 {
|
||||
t.Fatalf("first round %+v, refused %d", r, p.refusedSince())
|
||||
}
|
||||
if kept, _ := f.pending(); len(kept) != 2 || kept[0].MessageID != "laptop.sign-in-asked.2" {
|
||||
t.Fatalf("waiting %+v", kept)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "publishing laptop.sign-in-asked.2 at the bundle's start was refused") {
|
||||
t.Fatalf("the refusal was not written to the journal: %q", lines())
|
||||
}
|
||||
if r := p.publishKept("a kept event"); r.Published != 2 || r.Waiting != 0 {
|
||||
t.Fatalf("second round %+v", r)
|
||||
}
|
||||
if got := stream.publishes(); got != "laptop.sign-in-ended.1 laptop.sign-in-asked.2 laptop.sign-in-asked.2 laptop.sign-in-ended.3" {
|
||||
t.Fatalf("published %s", got)
|
||||
}
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("left %+v", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// The bundle publishes at its start, at each file event on pending/ and when its bus connection comes back: the first
|
||||
// heartbeat answered after a missed one; an older heartbeat arriving late changes nothing (§20, DMC-4).
|
||||
func TestTheBundlePublishesAtEachMoment(t *testing.T) {
|
||||
journalLines(t)
|
||||
f := aFolder(t)
|
||||
keepThree(t, f)
|
||||
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-ended.1": true}}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish}, names: &namer{folder: f, now: time.Now,
|
||||
ask: func(string, any) (json.RawMessage, error) { return json.RawMessage(`{"seats":[]}`), nil }}}
|
||||
files := make(chan struct{})
|
||||
var hook func(stdio.Heartbeat)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
b.start(bundleRuns{files: func(dirs []string, _ <-chan struct{}) <-chan struct{} {
|
||||
if len(dirs) != 1 || !strings.HasSuffix(dirs[0], "/pending") {
|
||||
t.Errorf("watched %v", dirs)
|
||||
}
|
||||
return files
|
||||
}, fileMade: func(string, string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
|
||||
subscribe: func(string, func(stdio.Envelope) error) error { return nil }})
|
||||
close(done)
|
||||
}()
|
||||
files <- struct{}{} // the start's round ran and was refused; this one publishes what waits
|
||||
if _, err := f.keep(eventAsked, eventSubject(eventAsked, "laptop"), map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files <- struct{}{}
|
||||
close(files)
|
||||
<-done
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("a file event published nothing: %+v", kept)
|
||||
}
|
||||
keepThree(t, f)
|
||||
at := time.Date(2026, 11, 24, 20, 0, 0, 0, time.UTC)
|
||||
hook(stdio.Heartbeat{At: at})
|
||||
if kept, _ := f.pending(); len(kept) != 3 {
|
||||
t.Fatal("a heartbeat with none missed published")
|
||||
}
|
||||
hook(stdio.Heartbeat{At: at.Add(time.Second), Missed: true, Why: "no heartbeat"})
|
||||
hook(stdio.Heartbeat{At: at.Add(-time.Second)})
|
||||
if kept, _ := f.pending(); len(kept) != 3 {
|
||||
t.Fatal("an older heartbeat arriving late was taken for the connection's return")
|
||||
}
|
||||
hook(stdio.Heartbeat{At: at.Add(2 * time.Second)})
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("the connection's return published nothing: %+v", kept)
|
||||
}
|
||||
if got := stream.publishes(); !strings.HasPrefix(got, "laptop.sign-in-ended.1 laptop.sign-in-ended.1 laptop.sign-in-asked.2") {
|
||||
t.Fatalf("published %s", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package main
|
||||
|
||||
// The person's graphical session (design 08 sign-in-page §16, §17): found over the system bus from logind, its
|
||||
// session bus at the user's RuntimePath and its display in the user manager's environment; its start heard as
|
||||
// logind's SessionNew, then waited for until the user manager's environment names a display. The user manager sends
|
||||
// no PropertiesChanged for its Environment (EmitsChangedSignal false), so the environment is read again at each file
|
||||
// event of the kernel on the X server's socket folder and on the session's RuntimePath, for at most 60 s (§17).
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sessionWait is the most the watcher waits, after a session started, for the user manager's environment to name a
|
||||
// display (§17).
|
||||
const sessionWait = 60 * time.Second
|
||||
|
||||
// x11Sockets is the folder an X server makes its socket in.
|
||||
var x11Sockets = "/tmp/.X11-unix"
|
||||
|
||||
// loginSession is what logind says of one session: its id and object, its account, type, whether it is remote, its
|
||||
// state, and its user's runtime directory.
|
||||
type loginSession struct {
|
||||
ID string
|
||||
Path string
|
||||
UID uint32
|
||||
Type string
|
||||
Remote bool
|
||||
State string
|
||||
RuntimePath string
|
||||
}
|
||||
|
||||
// graphical says whether the session is one the person sits at: x11 or wayland, not remote, active or online.
|
||||
func (s loginSession) graphical() bool {
|
||||
return (s.Type == "x11" || s.Type == "wayland") && !s.Remote && (s.State == "active" || s.State == "online")
|
||||
}
|
||||
|
||||
// Session is the person's graphical session as the watcher reaches it: its session bus, its runtime directory and the
|
||||
// display its user manager's environment names.
|
||||
type Session struct {
|
||||
ID string
|
||||
Type string
|
||||
RuntimePath string
|
||||
Display []string
|
||||
}
|
||||
|
||||
// Bus is the session's bus address.
|
||||
func (s Session) Bus() string { return "unix:path=" + s.RuntimePath + "/bus" }
|
||||
|
||||
// Env is the environment a program run in the session gets: the watcher's own, with the session's bus and runtime
|
||||
// directory.
|
||||
func (s Session) Env() []string {
|
||||
var env []string
|
||||
for _, kv := range os.Environ() {
|
||||
if !strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") && !strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
|
||||
env = append(env, kv)
|
||||
}
|
||||
}
|
||||
return append(env, "DBUS_SESSION_BUS_ADDRESS="+s.Bus(), "XDG_RUNTIME_DIR="+s.RuntimePath)
|
||||
}
|
||||
|
||||
// displayIn is the display an environment names for a session of its type: DISPLAY and XAUTHORITY for x11,
|
||||
// WAYLAND_DISPLAY for wayland; none when it names none.
|
||||
func displayIn(env []string, sessionType string) []string {
|
||||
want := map[string]bool{"DISPLAY": sessionType == "x11", "XAUTHORITY": sessionType == "x11",
|
||||
"WAYLAND_DISPLAY": sessionType == "wayland"}
|
||||
var out []string
|
||||
named := false
|
||||
for _, kv := range env {
|
||||
name, value, _ := strings.Cut(kv, "=")
|
||||
if want[name] && value != "" {
|
||||
out = append(out, kv)
|
||||
named = named || name == "DISPLAY" || name == "WAYLAND_DISPLAY"
|
||||
}
|
||||
}
|
||||
if !named {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// findSession is the person's graphical session now, or nil: a session of the watcher's account that is graphical,
|
||||
// whose user manager's environment names a display (§16).
|
||||
func (w *Watcher) findSession() (*Session, error) {
|
||||
if w.bus == nil {
|
||||
return nil, fmt.Errorf("not subscribed on the system bus")
|
||||
}
|
||||
sessions, err := w.bus.sessions(w.UID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, s := range sessions {
|
||||
if !s.graphical() {
|
||||
continue
|
||||
}
|
||||
if found := w.sessionWithDisplay(s); found != nil {
|
||||
return found, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// sessionWithDisplay is s reached, when its user manager's environment names a display; else nil.
|
||||
func (w *Watcher) sessionWithDisplay(s loginSession) *Session {
|
||||
found := Session{ID: s.ID, Type: s.Type, RuntimePath: s.RuntimePath}
|
||||
env, err := w.Environment(found.Bus())
|
||||
if err != nil {
|
||||
journal("reading the user manager's environment of session %s failed: %v", s.ID, err)
|
||||
return nil
|
||||
}
|
||||
if found.Display = displayIn(env, s.Type); found.Display == nil {
|
||||
return nil
|
||||
}
|
||||
return &found
|
||||
}
|
||||
|
||||
// sessionStart is the session start being waited for: the session, until when, and the wait's file events.
|
||||
type sessionStart struct {
|
||||
session loginSession
|
||||
files <-chan struct{}
|
||||
bound <-chan time.Time
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
// sessionNew acts on logind's SessionNew: for a graphical session of the watcher's account, it waits for the user
|
||||
// manager's environment to name a display, reading it again at each file event (§17).
|
||||
func (w *Watcher) sessionNew(path string) {
|
||||
s, err := w.bus.session(path)
|
||||
if err != nil {
|
||||
journal("reading the new session %s failed: %v", path, err)
|
||||
return
|
||||
}
|
||||
if s.UID != w.UID || (s.Type != "x11" && s.Type != "wayland") || s.Remote {
|
||||
return
|
||||
}
|
||||
w.endSessionWait()
|
||||
stop := make(chan struct{})
|
||||
w.starting = &sessionStart{session: s, stop: stop, bound: w.After(sessionWait),
|
||||
files: w.FileEvents([]string{x11Sockets, s.RuntimePath}, stop)}
|
||||
journal("session %s (%s) started; waiting for its display", s.ID, s.Type)
|
||||
}
|
||||
|
||||
// sessionFiles acts on a file event during the wait: the environment is read again, and once it names a display the
|
||||
// session's start is acted on (§15's third moment).
|
||||
func (w *Watcher) sessionFiles() {
|
||||
if w.starting == nil {
|
||||
return
|
||||
}
|
||||
found := w.sessionWithDisplay(w.starting.session)
|
||||
if found == nil {
|
||||
return
|
||||
}
|
||||
w.endSessionWait()
|
||||
w.sessionStarted(*found)
|
||||
}
|
||||
|
||||
// sessionBound ends a wait that found no display within its bound.
|
||||
func (w *Watcher) sessionBound() {
|
||||
if w.starting == nil {
|
||||
return
|
||||
}
|
||||
journal("session %s's start was not acted on: its user manager's environment named no display within %s",
|
||||
w.starting.session.ID, sessionWait)
|
||||
w.noteSession("not acted on: no display named within " + sessionWait.String())
|
||||
w.endSessionWait()
|
||||
}
|
||||
|
||||
func (w *Watcher) endSessionWait() {
|
||||
if w.starting != nil {
|
||||
close(w.starting.stop)
|
||||
w.starting = nil
|
||||
}
|
||||
}
|
||||
|
||||
// sessionStarted is §15's third moment: with the present rating PORTAL, the check on and a connection active, the page
|
||||
// is opened and the person told; else nothing. It reads the present rating, never a kept event.
|
||||
func (w *Watcher) sessionStarted(s Session) {
|
||||
if w.bus == nil {
|
||||
journal("session %s started while not subscribed on the system bus: nothing opened", s.ID)
|
||||
w.noteSession("nothing: not subscribed on the system bus")
|
||||
return
|
||||
}
|
||||
r, err := w.bus.rating()
|
||||
if err != nil {
|
||||
journal("session %s started; reading the rating failed: %v", s.ID, err)
|
||||
w.noteSession("nothing: the rating did not read")
|
||||
return
|
||||
}
|
||||
if !r.checkOn() || !webAddress(r.CheckURI) || r.Connectivity != ratingPortal || !r.active() {
|
||||
journal("session %s started with the rating %s: nothing opened", s.ID, ratingName(r.Connectivity))
|
||||
w.noteSession("nothing: the rating is " + ratingName(r.Connectivity))
|
||||
return
|
||||
}
|
||||
journal("session %s started with the rating PORTAL: opening the sign-in page", s.ID)
|
||||
w.noteSession("opened the sign-in page")
|
||||
w.present(&s, r.Network, r.CheckURI)
|
||||
}
|
||||
|
||||
func (w *Watcher) noteSession(did string) {
|
||||
w.state.LastSession = &sessionNote{At: w.Now(), Did: did}
|
||||
}
|
||||
|
||||
// sessionNote is the last session start and what the watcher did.
|
||||
type sessionNote struct {
|
||||
At time.Time `json:"at"`
|
||||
Did string `json:"did"`
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The person's session as logind says it: x11, local, active, of the watcher's account.
|
||||
func personsSession() loginSession {
|
||||
return loginSession{ID: "2", Path: "/org/freedesktop/login1/session/_32", UID: 1000, Type: "x11", State: "active",
|
||||
RuntimePath: "/run/user/1000"}
|
||||
}
|
||||
|
||||
// aSessionWatcher is a subscribed watcher whose stood-in user manager names a display once named is set; the test acts
|
||||
// as its loop, calling what a file event and the bound's end call.
|
||||
func aSessionWatcher(t *testing.T, sys *fakeSystem, named *bool) *Watcher {
|
||||
t.Helper()
|
||||
w := aWatcher(t, sys)
|
||||
files, bound := make(chan struct{}, 1), make(chan time.Time, 1)
|
||||
w.FileEvents = func(dirs []string, stop <-chan struct{}) <-chan struct{} {
|
||||
if strings.Join(dirs, " ") != "/tmp/.X11-unix /run/user/1000" {
|
||||
t.Errorf("the session's start is waited for on %v", dirs)
|
||||
}
|
||||
return files
|
||||
}
|
||||
w.After = func(d time.Duration) <-chan time.Time {
|
||||
if d != 60*time.Second {
|
||||
t.Errorf("the session's start is waited for %s", d)
|
||||
}
|
||||
return bound
|
||||
}
|
||||
w.Environment = func(bus string) ([]string, error) {
|
||||
if bus != "unix:path=/run/user/1000/bus" {
|
||||
t.Errorf("the environment is read over %s", bus)
|
||||
}
|
||||
if *named {
|
||||
return []string{"HOME=/home/person", "DISPLAY=:1", "XAUTHORITY=/home/person/.Xauthority"}, nil
|
||||
}
|
||||
return []string{"HOME=/home/person"}, nil
|
||||
}
|
||||
w.subscribe()
|
||||
return w
|
||||
}
|
||||
|
||||
// A session that starts while the rating is PORTAL opens the page once, when the user manager's environment names its
|
||||
// display; one that starts while it is not opens nothing; one whose display is not named within the bound is not acted
|
||||
// on, and says so (design 08 sign-in-page §15, §16, §17, §25).
|
||||
func TestASessionStartingWhilePortalOpensThePageOnce(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
rating Rating
|
||||
named bool
|
||||
opens int
|
||||
did string
|
||||
}{
|
||||
{"PORTAL", guest(ratingPortal), true, 1, "opened the sign-in page"},
|
||||
{"FULL", guest(ratingFull), true, 0, "nothing: the rating is FULL"},
|
||||
{"no display named", guest(ratingPortal), false, 0, "not acted on: no display named within 1m0s"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
sys.set(guest(ratingFull))
|
||||
named := false
|
||||
w := aSessionWatcher(t, sys, &named)
|
||||
desk := w.Desk.(*fakeDesk)
|
||||
sys.sessions = []loginSession{personsSession(), {ID: "9", Path: "/org/freedesktop/login1/session/_39", UID: 1001,
|
||||
Type: "x11", State: "active", RuntimePath: "/run/user/1001"}}
|
||||
w.heardSignal(signal{Session: "/org/freedesktop/login1/session/_39"})
|
||||
if w.starting != nil {
|
||||
t.Fatal("another account's session is waited for")
|
||||
}
|
||||
sys.set(c.rating)
|
||||
w.heardSignal(signal{Session: personsSession().Path})
|
||||
w.sessionFiles()
|
||||
if len(desk.opened()) != 0 || w.starting == nil {
|
||||
t.Fatal("acted on a session whose display is not named yet")
|
||||
}
|
||||
named = c.named
|
||||
w.sessionFiles()
|
||||
if w.starting != nil {
|
||||
w.sessionBound()
|
||||
}
|
||||
if got := desk.opened(); len(got) != c.opens || (c.opens == 1 && got[0] != "2 http://check.example.net/") {
|
||||
t.Fatalf("opened %q", got)
|
||||
}
|
||||
if w.state.LastSession == nil || w.state.LastSession.Did != c.did {
|
||||
t.Fatalf("the session's start is said as %+v", w.state.LastSession)
|
||||
}
|
||||
if c.named == false && !strings.Contains(strings.Join(lines(), "\n"), "start was not acted on") {
|
||||
t.Fatal("a start not acted on was not written to the journal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With no graphical session found the watcher opens nothing and still keeps the events: a remote session, one in no
|
||||
// graphical type and one whose environment names no display are no session (§15, §16, §25).
|
||||
func TestNoSessionOpensNothingAndStillKeeps(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
named := false
|
||||
w := aSessionWatcher(t, sys, &named)
|
||||
remote, tty := personsSession(), personsSession()
|
||||
remote.Remote, tty.Type = true, "tty"
|
||||
sys.sessions = []loginSession{remote, tty, personsSession()}
|
||||
w.heard(guest(ratingFull), false)
|
||||
w.heard(guest(ratingPortal), false)
|
||||
w.present(nil, "guest-example", "http://check.example.net/")
|
||||
if got := w.Desk.(*fakeDesk).opened(); len(got) != 0 {
|
||||
t.Fatalf("opened %q with no session", got)
|
||||
}
|
||||
if kept := keptSaid(t, w.Folder); len(kept) == 0 || kept[len(kept)-1] != "sign-in-asked guest-example wlan0" {
|
||||
t.Fatalf("kept %q", kept)
|
||||
}
|
||||
named = true
|
||||
if s, err := w.findSession(); err != nil || s == nil || s.ID != "2" || strings.Join(s.Display, " ") != "DISPLAY=:1 XAUTHORITY=/home/person/.Xauthority" {
|
||||
t.Fatalf("found %+v %v", s, err)
|
||||
}
|
||||
if got := displayIn([]string{"WAYLAND_DISPLAY=wayland-0", "DISPLAY=:0"}, "wayland"); strings.Join(got, " ") != "WAYLAND_DISPLAY=wayland-0" {
|
||||
t.Fatalf("a wayland session's display is %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package main
|
||||
|
||||
// The module's own local state, the one folder its two parts share (design 08 sign-in-page §12): the watcher's socket,
|
||||
// the network manager's check address, the kept events in pending/, the bundle's last uplink-names call and the next
|
||||
// sequence of the watcher's message ids. Every file is written whole: beside, then renamed over. Nothing else reads or
|
||||
// writes the folder.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// stateHome is the folder under the account's home, as the manifest declares it: owner the account, mode 0700.
|
||||
const stateHome = ".local/state/mesh/networkmanager"
|
||||
|
||||
// The folder's names.
|
||||
const (
|
||||
socketName = "watch.sock"
|
||||
checkName = "check-address"
|
||||
pendingName = "pending"
|
||||
namesName = "names.json"
|
||||
sequenceName = "sequence"
|
||||
)
|
||||
|
||||
// The watcher's socket's asks.
|
||||
const (
|
||||
askState = "state"
|
||||
askRatingAgain = "rating-again"
|
||||
)
|
||||
|
||||
// socketBound is how long one ask on the watcher's socket may take, a stated constant (design 08 sign-in-page §12;
|
||||
// lead answer C-8): a bundle's ask past it counts as no answer, and the watcher drops a line not asked within it.
|
||||
const socketBound = 5 * time.Second
|
||||
|
||||
// journal writes one line to the part's journal: its standard error, which the service manager keeps.
|
||||
var journal = func(format string, args ...any) {
|
||||
fmt.Fprintf(os.Stderr, "[networkmanager] "+format+"\n", args...)
|
||||
}
|
||||
|
||||
// Folder is the module's own local state, at Dir, on the node named Node.
|
||||
type Folder struct {
|
||||
Dir string
|
||||
Node string
|
||||
}
|
||||
|
||||
// theFolder is the account's folder, on the node the node-engine names (MESH_NODE).
|
||||
func theFolder() (Folder, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return Folder{}, err
|
||||
}
|
||||
return Folder{Dir: filepath.Join(home, stateHome), Node: os.Getenv("MESH_NODE")}, nil
|
||||
}
|
||||
|
||||
func (f Folder) path(name string) string { return filepath.Join(f.Dir, name) }
|
||||
|
||||
// writeWhole writes data to path whole: into a file beside it, synced, then renamed over it, so a reader sees the old
|
||||
// text or the new, never a part.
|
||||
func writeWhole(path string, data []byte, mode os.FileMode) error {
|
||||
beside := path + ".new"
|
||||
out, err := os.OpenFile(beside, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = out.Write(data)
|
||||
if err == nil {
|
||||
err = out.Sync()
|
||||
}
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(beside, path)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(beside)
|
||||
return fmt.Errorf("writing %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// nextSequence is the next sequence of the watcher's message ids and kept files, written whole as one more before it is
|
||||
// used, so no id is used twice while the folder lives, a restart included (R3-1).
|
||||
func (f Folder) nextSequence() (uint64, error) {
|
||||
n := uint64(1)
|
||||
raw, err := os.ReadFile(f.path(sequenceName))
|
||||
switch {
|
||||
case err == nil:
|
||||
if n, err = strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64); err != nil || n == 0 {
|
||||
return 0, fmt.Errorf("%s holds no sequence: %q", f.path(sequenceName), raw)
|
||||
}
|
||||
case !errors.Is(err, os.ErrNotExist):
|
||||
return 0, err
|
||||
}
|
||||
if err := writeWhole(f.path(sequenceName), []byte(strconv.FormatUint(n+1, 10)+"\n"), 0o600); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Kept is one event the watcher kept for the bundle to publish: the seat's subject, the bus's message id and the body.
|
||||
type Kept struct {
|
||||
Sequence uint64 `json:"-"`
|
||||
Subject string `json:"subject"`
|
||||
MessageID string `json:"message_id"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
|
||||
func pendingFile(seq uint64) string { return fmt.Sprintf("%010d.json", seq) }
|
||||
|
||||
// keep writes one event into pending/: its message id `<node>.<event>.<sequence>`, made once (§20).
|
||||
func (f Folder) keep(event, subject string, body any) (Kept, error) {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
if err := os.MkdirAll(f.path(pendingName), 0o700); err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
seq, err := f.nextSequence()
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
k := Kept{Sequence: seq, Subject: subject, MessageID: fmt.Sprintf("%s.%s.%d", f.Node, event, seq), Body: raw}
|
||||
data, err := json.Marshal(k)
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
return k, writeWhole(filepath.Join(f.path(pendingName), pendingFile(seq)), append(data, '\n'), 0o600)
|
||||
}
|
||||
|
||||
// pending is every kept event, in sequence order. A file that is not a kept event (a write beside one) is skipped; one
|
||||
// that does not read is an error naming it.
|
||||
func (f Folder) pending() ([]Kept, error) {
|
||||
entries, err := os.ReadDir(f.path(pendingName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Kept
|
||||
for _, e := range entries {
|
||||
name, ok := strings.CutSuffix(e.Name(), ".json")
|
||||
if !ok || e.IsDir() {
|
||||
continue
|
||||
}
|
||||
seq, err := strconv.ParseUint(name, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(f.path(pendingName), e.Name()))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var k Kept
|
||||
if err := json.Unmarshal(raw, &k); err != nil {
|
||||
return nil, fmt.Errorf("the kept event %s does not read: %w", e.Name(), err)
|
||||
}
|
||||
k.Sequence = seq
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Sequence < out[j].Sequence })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// drop deletes one kept event; one already gone is no error.
|
||||
func (f Folder) drop(k Kept) error {
|
||||
err := os.Remove(filepath.Join(f.path(pendingName), pendingFile(k.Sequence)))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// writeCheckAddress writes the network manager's check address on one line, empty when there is none.
|
||||
func (f Folder) writeCheckAddress(address string) error {
|
||||
return writeWhole(f.path(checkName), []byte(address+"\n"), 0o600)
|
||||
}
|
||||
|
||||
// checkAddress is the check address the watcher wrote; empty when it wrote none or none is set.
|
||||
func (f Folder) checkAddress() (string, error) {
|
||||
raw, err := os.ReadFile(f.path(checkName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", nil
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), err
|
||||
}
|
||||
|
||||
// The results of an uplink-names call besides a failure's text.
|
||||
const (
|
||||
resultOK = "ok"
|
||||
resultNoHolder = "no holder"
|
||||
)
|
||||
|
||||
// NamesCall is the bundle's last uplink-names call: the names given, its result (ok, no holder or the failure) and
|
||||
// when.
|
||||
type NamesCall struct {
|
||||
Names []string `json:"names"`
|
||||
Result string `json:"result"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// Failed says whether the call stands failed: no holder is not a failure.
|
||||
func (c NamesCall) Failed() bool {
|
||||
return c.Result != "" && c.Result != resultOK && c.Result != resultNoHolder
|
||||
}
|
||||
|
||||
func (f Folder) writeNames(c NamesCall) error {
|
||||
if c.Names == nil {
|
||||
c.Names = []string{}
|
||||
}
|
||||
data, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeWhole(f.path(namesName), append(data, '\n'), 0o600)
|
||||
}
|
||||
|
||||
// names is the last uplink-names call, nil when none was written.
|
||||
func (f Folder) names() (*NamesCall, error) {
|
||||
raw, err := os.ReadFile(f.path(namesName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c NamesCall
|
||||
return &c, json.Unmarshal(raw, &c)
|
||||
}
|
||||
|
||||
// socketAsk is the one line asked on the watcher's socket, socketAnswer the one answered.
|
||||
type socketAsk struct {
|
||||
Ask string `json:"ask"`
|
||||
}
|
||||
|
||||
type socketAnswer struct {
|
||||
Answer json.RawMessage `json:"answer,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// listen makes the watcher's socket, mode 0600, in place of one a stopped watcher left.
|
||||
func (f Folder) listen() (net.Listener, error) {
|
||||
path := f.path(socketName)
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
l, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// serveSocket answers each connection's one asked line with handle's answer, until l is closed.
|
||||
func serveSocket(l net.Listener, handle func(ask string) (any, error)) {
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(socketBound))
|
||||
line, err := bufio.NewReader(io.LimitReader(conn, 4096)).ReadBytes('\n')
|
||||
if err != nil && len(line) == 0 {
|
||||
return
|
||||
}
|
||||
var ask socketAsk
|
||||
var out socketAnswer
|
||||
if err := json.Unmarshal(line, &ask); err != nil {
|
||||
out.Error = "the line asked is no JSON: " + err.Error()
|
||||
} else if answer, err := handle(ask.Ask); err != nil {
|
||||
out.Error = err.Error()
|
||||
} else if out.Answer, err = json.Marshal(answer); err != nil {
|
||||
out.Error = err.Error()
|
||||
}
|
||||
data, _ := json.Marshal(out)
|
||||
conn.Write(append(data, '\n'))
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// askWatcher asks the watcher one ask on its socket and reads its answer into into (nil to drop it).
|
||||
func (f Folder) askWatcher(ask string, into any) error {
|
||||
conn, err := net.DialTimeout("unix", f.path(socketName), socketBound)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(socketBound))
|
||||
data, _ := json.Marshal(socketAsk{Ask: ask})
|
||||
if _, err := conn.Write(append(data, '\n')); err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
line, err := bufio.NewReader(conn).ReadBytes('\n')
|
||||
if err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
var out socketAnswer
|
||||
if err := json.Unmarshal(line, &out); err != nil {
|
||||
return fmt.Errorf("the watcher answered no JSON: %w", err)
|
||||
}
|
||||
if out.Error != "" {
|
||||
return fmt.Errorf("the watcher refused %s: %s", ask, out.Error)
|
||||
}
|
||||
if into == nil || len(out.Answer) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(out.Answer, into)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func aFolder(t *testing.T) Folder {
|
||||
t.Helper()
|
||||
return Folder{Dir: t.TempDir(), Node: "laptop"}
|
||||
}
|
||||
|
||||
// A watcher restarted after its events were published and pending/ emptied makes message ids it never used, so the
|
||||
// bus keeps them rather than dropping them as duplicates (design 08 sign-in-page §12, §25; R3-1).
|
||||
func TestARestartedWatcherMakesIdsItNeverUsed(t *testing.T) {
|
||||
f := aFolder(t)
|
||||
used := map[string]bool{}
|
||||
for range 3 {
|
||||
k, err := f.keep("sign-in-asked", "mesh.seat.node-uplink.event.sign-in-asked.laptop", map[string]string{"node": "laptop"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
used[k.MessageID] = true
|
||||
}
|
||||
kept, err := f.pending()
|
||||
if err != nil || len(kept) != 3 || kept[0].MessageID != "laptop.sign-in-asked.1" || kept[2].Sequence != 3 {
|
||||
t.Fatalf("kept %+v %v", kept, err)
|
||||
}
|
||||
for _, k := range kept {
|
||||
if err := f.drop(k); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
restarted := Folder{Dir: f.Dir, Node: "laptop"}
|
||||
k, err := restarted.keep("sign-in-ended", "mesh.seat.node-uplink.event.sign-in-ended.laptop", map[string]string{})
|
||||
if err != nil || used[k.MessageID] || k.MessageID != "laptop.sign-in-ended.4" {
|
||||
t.Fatalf("the restarted watcher made %q (%v), having used %v", k.MessageID, err, used)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(f.Dir, pendingName, "0000000004.json")); err != nil {
|
||||
t.Fatalf("the kept file is not named by its ten-digit sequence: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Every file of the folder is written whole, beside and renamed over: a write that fails leaves the old text and no
|
||||
// part of the new, and a file being written beside a kept event is not read as one (§12).
|
||||
func TestTheFoldersFilesAreWrittenWhole(t *testing.T) {
|
||||
f := aFolder(t)
|
||||
if err := f.writeCheckAddress("http://check.example.net/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(f.path(checkName)+".new", 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.writeCheckAddress("http://other.example.net/"); err == nil {
|
||||
t.Fatal("a write that could not be made beside was taken")
|
||||
}
|
||||
if got, _ := f.checkAddress(); got != "http://check.example.net/" {
|
||||
t.Fatalf("a failed write left %q", got)
|
||||
}
|
||||
os.Remove(f.path(checkName) + ".new")
|
||||
if err := f.writeNames(NamesCall{Result: resultNoHolder}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, err := f.names(); err != nil || c.Result != resultNoHolder || c.Names == nil || c.Failed() {
|
||||
t.Fatalf("names read %+v %v", c, err)
|
||||
}
|
||||
if _, err := f.keep("sign-in-asked", "s", map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(f.Dir, pendingName, "0000000009.json.new"), []byte("{"), 0o600)
|
||||
entries, _ := os.ReadDir(f.Dir)
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".new") {
|
||||
t.Errorf("%s was left beside", e.Name())
|
||||
}
|
||||
}
|
||||
if kept, err := f.pending(); err != nil || len(kept) != 1 {
|
||||
t.Fatalf("pending read %+v %v", kept, err)
|
||||
}
|
||||
if raw, _ := os.ReadFile(f.path(sequenceName)); string(raw) != "2\n" {
|
||||
t.Fatalf("the sequence file holds %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// The watcher's socket answers one JSON line asked with one line, its refusal named (§12).
|
||||
func TestTheWatchersSocketAnswersOneLine(t *testing.T) {
|
||||
f := aFolder(t)
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
go serveSocket(l, func(ask string) (any, error) {
|
||||
if ask == askState {
|
||||
return map[string]bool{"subscribed": true}, nil
|
||||
}
|
||||
return nil, errors.New("no such ask")
|
||||
})
|
||||
if fi, err := os.Stat(f.path(socketName)); err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("the socket is %v %v", fi, err)
|
||||
}
|
||||
var state struct{ Subscribed bool }
|
||||
if err := f.askWatcher(askState, &state); err != nil || !state.Subscribed {
|
||||
t.Fatalf("state answered %+v %v", state, err)
|
||||
}
|
||||
if err := f.askWatcher("other", nil); err == nil || !strings.Contains(err.Error(), "no such ask") {
|
||||
t.Fatalf("a refusal answered %v", err)
|
||||
}
|
||||
l.Close()
|
||||
if err := f.askWatcher(askState, nil); err == nil {
|
||||
t.Fatal("a closed socket answered")
|
||||
}
|
||||
}
|
||||
|
||||
// A path in the folder the watcher does not know is left as it is and written to its journal once per path: what is
|
||||
// there at its start, and what a file event makes after (§12; lead answer L-1).
|
||||
func TestAPathTheWatcherDoesNotKnowIsLeftAndSaidOnce(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
f := w.Folder
|
||||
if _, err := f.keep(eventEnded, "s", map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.writeCheckAddress("http://check.example.net/")
|
||||
for _, p := range []string{filepath.Join(f.Dir, "notes.txt"), filepath.Join(f.Dir, pendingName, "stray")} {
|
||||
if err := os.WriteFile(p, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
made := make(chan string)
|
||||
w.Made = func(dirs []string, stop <-chan struct{}) <-chan string {
|
||||
if len(dirs) != 2 || dirs[0] != f.Dir || dirs[1] != filepath.Join(f.Dir, pendingName) {
|
||||
t.Errorf("watched %v", dirs)
|
||||
}
|
||||
return made
|
||||
}
|
||||
stop, done := make(chan struct{}), make(chan struct{})
|
||||
go func() { _ = w.run(stop); close(done) }()
|
||||
for _, p := range []string{filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "sequence.new"),
|
||||
filepath.Join(f.Dir, pendingName, "0000000002.json")} {
|
||||
made <- p
|
||||
}
|
||||
w.askLoop(askState)
|
||||
close(stop)
|
||||
<-done
|
||||
var said []string
|
||||
for _, l := range lines() {
|
||||
if strings.Contains(l, "is not the module's") {
|
||||
said = append(said, strings.TrimPrefix(l, f.Dir+"/"))
|
||||
}
|
||||
}
|
||||
want := []string{"notes.txt is not the module's: left as it is", "pending/stray is not the module's: left as it is",
|
||||
"other is not the module's: left as it is"}
|
||||
if strings.Join(said, "|") != strings.Join(want, "|") {
|
||||
t.Fatalf("said %q", said)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(f.Dir, "notes.txt")); err != nil {
|
||||
t.Fatal("a path the watcher does not know was not left")
|
||||
}
|
||||
}
|
||||
|
||||
// The bounds the design states, each a constant and none a setting: the socket's 5 s, the open's 10 s, the session
|
||||
// start's 60 s and the 256 kept events (design 08 sign-in-page §12, §17, §18, §20; R2-7, C-8).
|
||||
func TestTheStatedBounds(t *testing.T) {
|
||||
if socketBound != 5*time.Second || openBound != 10*time.Second || sessionWait != 60*time.Second || keptBound != 256 {
|
||||
t.Fatalf("the bounds are %s, %s, %s and %d", socketBound, openBound, sessionWait, keptBound)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -62,3 +63,67 @@ func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
t.Errorf("the build packs files/ into %d archives, not one", packs)
|
||||
}
|
||||
}
|
||||
|
||||
// The manifest declares the watcher's process as the account, its health its unit's state; the folder the two parts
|
||||
// share, the account's alone; the event the bundle consumes and the verbs it invokes; and the five tools. NetworkManager's
|
||||
// unit keeps no state and no health (design 08 sign-in-page §11, §12, §13, §27; lead answer C-2c).
|
||||
func TestTheManifestDeclaresTheSignInParts(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Consumes []string `json:"consumes"`
|
||||
Invokes []string `json:"invokes"`
|
||||
Tools []string `json:"tools"`
|
||||
Claims []map[string]any `json:"claims"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same := func(got []string, want ...string) bool {
|
||||
return strings.Join(got, " ") == strings.Join(want, " ")
|
||||
}
|
||||
if !same(m.Consumes, "node-engine.running") {
|
||||
t.Errorf("consumes %v", m.Consumes)
|
||||
}
|
||||
if !same(m.Invokes, "seat:mesh-module-assigner.assignments", "seat:node-resolver.uplink-names", "seat:node-resolver.routes") {
|
||||
t.Errorf("invokes %v", m.Invokes)
|
||||
}
|
||||
var served []string
|
||||
for _, tool := range (&bundle{}).tools() {
|
||||
served = append(served, tool.Name)
|
||||
}
|
||||
if !same(m.Tools, served...) {
|
||||
t.Errorf("lists the tools %v, serves %v", m.Tools, served)
|
||||
}
|
||||
if len(m.Claims) != 1 || m.Claims[0]["name"] != "node-uplink" {
|
||||
t.Errorf("claims %v", m.Claims)
|
||||
}
|
||||
byID := map[string]map[string]any{}
|
||||
for _, r := range m.Resources {
|
||||
byID[r["id"].(string)] = r
|
||||
}
|
||||
dir := byID["sign-in-state"]
|
||||
if dir["type"] != "directory" || dir["path"] != "${machine:account-home}/"+stateHome ||
|
||||
dir["owner"] != "${machine:account}" || dir["mode"] != "0700" || dir["unknown"] != "module" {
|
||||
t.Errorf("the folder is %v", dir)
|
||||
}
|
||||
p := byID["sign-in"]
|
||||
run, _ := json.Marshal(p["run"])
|
||||
h, _ := json.Marshal(p["health"])
|
||||
if p["type"] != "process" || p["name"] != "networkmanager-sign-in" || p["artifact"] != "tools" ||
|
||||
string(run) != `["./uplink-tools","watch"]` || p["user"] != "${machine:account}" ||
|
||||
string(h) != `{"kind":"unit"}` {
|
||||
t.Errorf("the watcher is %v", p)
|
||||
}
|
||||
if byID["service"]["health"] != nil || byID["service"]["state"] != nil {
|
||||
t.Errorf("NetworkManager's unit carries a state or a health: %v", byID["service"])
|
||||
}
|
||||
for _, id := range []string{"package", "config", "service"} {
|
||||
if byID[id] == nil {
|
||||
t.Errorf("the resource %s is gone", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
// networkmanager's own tools, served by the bundle (design 08 sign-in-page §23): the read of the sign-in reaction, the
|
||||
// three acts that start by hand what the two parts do by themselves, and the health tool of the watcher's process.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
// signInRead is uplink_sign_in's answer.
|
||||
type signInRead struct {
|
||||
Watcher *watcherState `json:"watcher,omitempty"`
|
||||
WatcherError string `json:"watcher_error,omitempty"`
|
||||
Waiting int `json:"waiting"`
|
||||
RefusedSince int `json:"publishes_refused_since_start"`
|
||||
Names *NamesCall `json:"names,omitempty"`
|
||||
ResolverRefused *string `json:"resolver_refused,omitempty"`
|
||||
ResolverError string `json:"resolver_error,omitempty"`
|
||||
}
|
||||
|
||||
func (b *bundle) tools() []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{Name: "uplink_sign_in",
|
||||
Description: "The network's sign-in page as this machine reacts to it: whether the watcher hears the network " +
|
||||
"manager, the last rating it heard and when, the sign-in asked now (network, link, since), the asks opened " +
|
||||
"and ended since its start, the last page opened with its outcome, the last notification, the last session " +
|
||||
"start and what it did, the kept events dropped past the bound of 256, the events waiting to be published " +
|
||||
"and the publishes refused since the bundle's start, the last uplink-names call with its result, and the " +
|
||||
"resolver's refusal of the names where a holder of node-resolver runs here. (r)",
|
||||
Run: func(map[string]any) (any, error) { return b.signIn(), nil }},
|
||||
{Name: "uplink_names_again",
|
||||
Description: "Give this machine's resolver the network manager's check host now, as the bundle does at its " +
|
||||
"moments: calls node-resolver's uplink-names on this node and answers the call as names.json keeps it. (a)",
|
||||
Run: func(map[string]any) (any, error) { return b.names.give("uplink_names_again"), nil }},
|
||||
{Name: "uplink_rating_again",
|
||||
Description: "Make the watcher subscribe on the system bus again, read the network manager's rating now and " +
|
||||
"act on it as on a change; answers the watcher's state after it. (a)",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askRatingAgain, &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}},
|
||||
{Name: "uplink_publish_again",
|
||||
Description: "Publish the kept sign-in events now, in order under their own message ids, as the bundle does at " +
|
||||
"its moments: answers how many were published and how many still wait. (a)",
|
||||
Run: func(map[string]any) (any, error) { return b.pub.publishKept("uplink_publish_again"), nil }},
|
||||
{Name: "uplink_health",
|
||||
Description: "Whether the sign-in reaction works: unhealthy while the watcher's socket does not answer, while " +
|
||||
"the watcher is not subscribed on the system bus, or while the last uplink-names call stands failed, naming " +
|
||||
"which; no holder of node-resolver is healthy. A tool to read, not the watcher's health check, which is its " +
|
||||
"unit's state. (r)",
|
||||
Run: func(map[string]any) (any, error) { return b.health(), nil }},
|
||||
}
|
||||
}
|
||||
|
||||
// signIn reads the watcher's state, the folder and, where a holder of node-resolver runs here, the resolver's refusal.
|
||||
func (b *bundle) signIn() signInRead {
|
||||
var out signInRead
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askState, &s); err != nil {
|
||||
out.WatcherError = err.Error()
|
||||
} else {
|
||||
out.Watcher = &s
|
||||
}
|
||||
if kept, err := b.folder.pending(); err == nil {
|
||||
out.Waiting = len(kept)
|
||||
}
|
||||
out.RefusedSince = b.pub.refusedSince()
|
||||
out.Names, _ = b.folder.names()
|
||||
routes, held, err := b.resolverRoutes()
|
||||
switch {
|
||||
case err != nil:
|
||||
out.ResolverError = err.Error()
|
||||
case held:
|
||||
out.ResolverRefused = &routes.UplinkNames.Refused
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resolverRoutes is node-resolver's routes on this node, held false when no module holds the seat here.
|
||||
func (b *bundle) resolverRoutes() (noderesolver.RoutesAnswer, bool, error) {
|
||||
holder, err := b.names.resolverHolder()
|
||||
if err != nil || holder == "" {
|
||||
return noderesolver.RoutesAnswer{}, false, err
|
||||
}
|
||||
raw, err := b.names.ask("seat:"+noderesolver.Seat+"."+noderesolver.VerbRoutes+"@"+b.folder.Node, struct{}{})
|
||||
if err != nil {
|
||||
return noderesolver.RoutesAnswer{}, true, fmt.Errorf("%s/%s.%s: %w", b.folder.Node, noderesolver.Seat,
|
||||
noderesolver.VerbRoutes, err)
|
||||
}
|
||||
routes, _, err := noderesolver.DecodeRoutesAnswer(raw)
|
||||
return routes, true, err
|
||||
}
|
||||
|
||||
// health is uplink_health's answer, a tool of the bundle and not a node-engine check (§23; lead answer C-2c).
|
||||
func (b *bundle) health() health.Answer {
|
||||
var faults []string
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askState, &s); err != nil {
|
||||
faults = append(faults, err.Error())
|
||||
} else if !s.Subscribed {
|
||||
faults = append(faults, "the watcher is not subscribed on the system bus")
|
||||
}
|
||||
call, err := b.folder.names()
|
||||
if err != nil {
|
||||
faults = append(faults, "names.json does not read: "+err.Error())
|
||||
}
|
||||
if call != nil && call.Failed() {
|
||||
faults = append(faults, "the last uplink-names call failed: "+call.Result)
|
||||
}
|
||||
if len(faults) > 0 {
|
||||
return health.Unhealthy(strings.Join(faults, "; ") + ".")
|
||||
}
|
||||
why := "the watcher hears the network manager"
|
||||
if call != nil {
|
||||
why += "; the last uplink-names call: " + call.Result
|
||||
}
|
||||
return health.Healthy(why + ".")
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
// aToolBundle is a bundle over the stood-in mesh and stream, with a watcher's socket answering state as subscribed
|
||||
// says, and recording the asks it was given.
|
||||
func aToolBundle(t *testing.T, mesh *fakeMesh, subscribed *bool, asked *[]string) (*bundle, *fakeStream) {
|
||||
t.Helper()
|
||||
f := aFolder(t)
|
||||
stream := &fakeStream{refuse: map[string]bool{}}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish},
|
||||
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
|
||||
if subscribed == nil {
|
||||
return b, stream
|
||||
}
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { l.Close() })
|
||||
go serveSocket(l, func(ask string) (any, error) {
|
||||
*asked = append(*asked, ask)
|
||||
return watcherState{Subscribed: *subscribed, Rating: "PORTAL", AsksOpened: 1, DroppedPastBound: 2}, nil
|
||||
})
|
||||
return b, stream
|
||||
}
|
||||
|
||||
func runTool(t *testing.T, b *bundle, name string) any {
|
||||
t.Helper()
|
||||
for _, tool := range b.tools() {
|
||||
if tool.Name == name {
|
||||
out, err := tool.Run(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
t.Fatalf("no tool %s", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The health tool is unhealthy while the watcher's socket does not answer, while the watcher is not subscribed and
|
||||
// while the last uplink-names call stands failed, naming which; no holder is healthy. It is a tool that reads and calls
|
||||
// nothing on the bus: the names are not given again at a look (design 08 sign-in-page §13, §23, §25; C-2c).
|
||||
func TestTheHealthToolSaysWhatIsWrong(t *testing.T) {
|
||||
journalLines(t)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
socket bool
|
||||
subscribed bool
|
||||
holder string
|
||||
fail bool
|
||||
healthy bool
|
||||
why string
|
||||
}{
|
||||
{"no socket", false, false, "", false, false, "the watcher's socket does not answer"},
|
||||
{"not subscribed", true, false, "", false, false, "the watcher is not subscribed on the system bus"},
|
||||
{"a failed call", true, true, "systemd-resolved", true, false, "the last uplink-names call failed"},
|
||||
{"no holder", true, true, "", false, true, "no holder"},
|
||||
{"given", true, true, "systemd-resolved", false, true, "ok"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
mesh := &fakeMesh{holder: c.holder,
|
||||
routes: `{"links":[],"mesh":{"domains":[],"servers":[]},"mesh_resolvers":{"silent":false},"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":""}}`}
|
||||
var asked []string
|
||||
subscribed := c.subscribed
|
||||
var b *bundle
|
||||
if c.socket {
|
||||
b, _ = aToolBundle(t, mesh, &subscribed, &asked)
|
||||
} else {
|
||||
b, _ = aToolBundle(t, mesh, nil, nil)
|
||||
}
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
if c.fail {
|
||||
mesh.fail = errors.New("no answer within its bound")
|
||||
}
|
||||
b.names.give("the bundle's start")
|
||||
mesh.fail = nil
|
||||
got := runTool(t, b, "uplink_health").(health.Answer)
|
||||
if got.Healthy != c.healthy || !strings.Contains(got.Why, c.why) {
|
||||
t.Fatalf("answered %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
mesh := &fakeMesh{holder: "systemd-resolved",
|
||||
routes: `{"uplink_names":{"names":[],"link":"","refused":"resolved refused the domains"}}`}
|
||||
subscribed, asked := true, []string{}
|
||||
b, _ := aToolBundle(t, mesh, &subscribed, &asked)
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
b.names.give("the bundle's start")
|
||||
if got := runTool(t, b, "uplink_health").(health.Answer); !got.Healthy || len(mesh.called()) != 1 {
|
||||
t.Fatalf("the health tool answered %+v and called uplink-names %d times", got, len(mesh.called()))
|
||||
}
|
||||
}
|
||||
|
||||
// Each tool answers: the read of the sign-in reaction, the names given again, the watcher asked rating-again, and the
|
||||
// kept events published again (§23, §25; R3-5).
|
||||
func TestEachToolAnswers(t *testing.T) {
|
||||
journalLines(t)
|
||||
mesh := &fakeMesh{holder: "systemd-resolved",
|
||||
routes: `{"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":"resolved refused the domains"}}`}
|
||||
subscribed, asked := true, []string{}
|
||||
b, stream := aToolBundle(t, mesh, &subscribed, &asked)
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
keepThree(t, b.folder)
|
||||
stream.refuse["laptop.sign-in-ended.1"] = true
|
||||
b.pub.publishKept("the bundle's start")
|
||||
|
||||
read := runTool(t, b, "uplink_sign_in").(signInRead)
|
||||
raw, _ := json.Marshal(read)
|
||||
if read.Watcher == nil || read.Watcher.Rating != "PORTAL" || read.Watcher.DroppedPastBound != 2 || read.Waiting != 3 ||
|
||||
read.RefusedSince != 1 || read.Names != nil || read.ResolverRefused == nil ||
|
||||
*read.ResolverRefused != "resolved refused the domains" {
|
||||
t.Fatalf("uplink_sign_in answered %s", raw)
|
||||
}
|
||||
if c := runTool(t, b, "uplink_names_again").(NamesCall); c.Result != resultOK || len(mesh.called()) != 1 {
|
||||
t.Fatalf("uplink_names_again answered %+v", c)
|
||||
}
|
||||
if s := runTool(t, b, "uplink_rating_again").(watcherState); !s.Subscribed || asked[len(asked)-1] != askRatingAgain {
|
||||
t.Fatalf("uplink_rating_again answered %+v, asked %v", s, asked)
|
||||
}
|
||||
if r := runTool(t, b, "uplink_publish_again").(publishResult); r.Published != 3 || r.Waiting != 0 {
|
||||
t.Fatalf("uplink_publish_again answered %+v", r)
|
||||
}
|
||||
var names []string
|
||||
for _, tool := range b.tools() {
|
||||
names = append(names, tool.Name)
|
||||
}
|
||||
if strings.Join(names, " ") != "uplink_sign_in uplink_names_again uplink_rating_again uplink_publish_again uplink_health" {
|
||||
t.Fatalf("serves %v", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
// A path in the module's folder the watcher does not know (design 08 sign-in-page §12; lead answer L-1): the folder's
|
||||
// `unknown` is `module`, so the node-engine does nothing inside it and the watcher reacts. It leaves such a path as it
|
||||
// is and writes it to its journal once per path: at its start for what is there, and at each file event of the kernel
|
||||
// that makes one.
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// keptFile is a kept event's name in pending/, or one being written beside it.
|
||||
var keptFile = regexp.MustCompile(`^[0-9]{10}\.json(\.new)?$`)
|
||||
|
||||
// knownPath says whether path is one of the folder's own: watch.sock, check-address, pending/ and its files,
|
||||
// names.json, sequence, or a file being written beside one of them.
|
||||
func (f Folder) knownPath(path string) bool {
|
||||
rel, err := filepath.Rel(f.Dir, path)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return false
|
||||
}
|
||||
dir, name := filepath.Split(rel)
|
||||
switch dir {
|
||||
case "":
|
||||
name = strings.TrimSuffix(name, ".new")
|
||||
return name == socketName || name == checkName || name == pendingName || name == namesName || name == sequenceName
|
||||
case pendingName + "/":
|
||||
return keptFile.MatchString(name)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// unknownAtStart is every path in the folder and in pending/ the watcher does not know.
|
||||
func (f Folder) unknownAtStart() []string {
|
||||
var out []string
|
||||
for _, dir := range []string{f.Dir, filepath.Join(f.Dir, pendingName)} {
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, e := range entries {
|
||||
if p := filepath.Join(dir, e.Name()); !f.knownPath(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// strange writes a path the watcher does not know to its journal, once per path, and leaves it as it is.
|
||||
func (w *Watcher) strange(path string) {
|
||||
if w.Folder.knownPath(path) || w.told[path] {
|
||||
return
|
||||
}
|
||||
if w.told == nil {
|
||||
w.told = map[string]bool{}
|
||||
}
|
||||
w.told[path] = true
|
||||
journal("%s is not the module's: left as it is", path)
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The node-uplink seat's verbs (novox/hq ADR 0241), every holder's: the resolver file as it is, the mesh's
|
||||
@@ -148,3 +150,30 @@ func TestTheLinksCarryTheirDefaultRouteAndTheirNames(t *testing.T) {
|
||||
t.Fatalf("a manager that does not answer is not said: %+v", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// main.go serves the seat's two verbs first and the holder's own tools after them, and runs a subcommand only when
|
||||
// the holder's manager.go gives it (design 08 sign-in-page §11).
|
||||
func TestTheHoldersOwnPartComesBesideTheSeatsVerbs(t *testing.T) {
|
||||
ran := ""
|
||||
own := holderOwn{
|
||||
Commands: map[string]func([]string) error{"watch": func(args []string) error { ran = strings.Join(args, " "); return nil }},
|
||||
Tools: []stdio.Tool{{Name: "own_tool"}},
|
||||
}
|
||||
var names []string
|
||||
for _, tool := range tools(Machine{}, own) {
|
||||
names = append(names, tool.Name)
|
||||
}
|
||||
if strings.Join(names, " ") != "node-uplink.resolvers node-uplink.links own_tool" {
|
||||
t.Fatalf("served %v", names)
|
||||
}
|
||||
if run, err := command(own, nil); run != nil || err != nil {
|
||||
t.Fatalf("no arguments is the bundle, got a subcommand or %v", err)
|
||||
}
|
||||
if _, err := command(own, []string{"nothing"}); err == nil || !strings.Contains(err.Error(), `"nothing"`) {
|
||||
t.Fatalf("a subcommand the holder has not was taken: %v", err)
|
||||
}
|
||||
run, err := command(own, []string{"watch", "a"})
|
||||
if err != nil || run([]string{"a"}) != nil || ran != "a" {
|
||||
t.Fatalf("the holder's subcommand did not run: %v %q", err, ran)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
package main
|
||||
|
||||
// The watcher (design 08 sign-in-page §11, §14, §20 to §22): `uplink-tools watch`, a process the machine's service
|
||||
// manager starts at boot as the account and keeps running, needing no bus. It hears the network manager's
|
||||
// PropertiesChanged on the system bus for the rating, the active connection and the check, keeps the events of §21 in
|
||||
// the module's folder for the bundle to publish, and answers its socket. Nothing runs on a timer: it acts on a signal,
|
||||
// on the system bus's socket coming back (a file event of the kernel) and on an ask on its socket.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
|
||||
)
|
||||
|
||||
// keptBound is the most kept events pending/ holds; past it the oldest goes, with a journal line (§20).
|
||||
const keptBound = 256
|
||||
|
||||
// The network manager's ratings of the network (NMConnectivityState).
|
||||
const (
|
||||
ratingUnknown uint32 = 0
|
||||
ratingNone uint32 = 1
|
||||
ratingPortal uint32 = 2
|
||||
ratingLimited uint32 = 3
|
||||
ratingFull uint32 = 4
|
||||
)
|
||||
|
||||
func ratingName(r uint32) string {
|
||||
switch r {
|
||||
case ratingNone:
|
||||
return "NONE"
|
||||
case ratingPortal:
|
||||
return "PORTAL"
|
||||
case ratingLimited:
|
||||
return "LIMITED"
|
||||
case ratingFull:
|
||||
return "FULL"
|
||||
}
|
||||
return "UNKNOWN"
|
||||
}
|
||||
|
||||
// Rating is what the watcher reads of the network manager: its rating, whether its check is on and where it goes, and
|
||||
// the active connection (its object, its name and its first device's interface; "" or "/" when none is active).
|
||||
type Rating struct {
|
||||
Connectivity uint32
|
||||
CheckEnabled bool
|
||||
CheckAvailable bool
|
||||
CheckURI string
|
||||
Connection string
|
||||
Network string
|
||||
Link string
|
||||
}
|
||||
|
||||
func (r Rating) checkOn() bool { return r.CheckEnabled && r.CheckAvailable }
|
||||
func (r Rating) active() bool { return r.Connection != "" && r.Connection != "/" }
|
||||
|
||||
// The events of node-uplink the watcher keeps, and why an ask ended, are the seat's (design 08 sign-in-page §1).
|
||||
const (
|
||||
eventAsked = nodeuplink.EventSignInAsked
|
||||
eventEnded = nodeuplink.EventSignInEnded
|
||||
|
||||
whySignedIn = nodeuplink.SignInEndedWhySignedIn
|
||||
whyLeft = nodeuplink.SignInEndedWhyLeft
|
||||
whyNoLongerAsked = nodeuplink.SignInEndedWhyNoLongerAsked
|
||||
)
|
||||
|
||||
// eventSubject is where a node-uplink event of node is published (§1).
|
||||
func eventSubject(event, node string) string {
|
||||
if event == eventAsked {
|
||||
return nodeuplink.SubjectSignInAsked(node)
|
||||
}
|
||||
return nodeuplink.SubjectSignInEnded(node)
|
||||
}
|
||||
|
||||
// signal is one thing the system bus said that the watcher hears: the network manager's rating changed, or logind
|
||||
// has a new session (its object path).
|
||||
type signal struct {
|
||||
Rating bool
|
||||
Session string
|
||||
}
|
||||
|
||||
// systemBus is the watcher's connection to the machine's system bus: subscribed, it hands every signal it hears on the
|
||||
// channel, which closes when the connection drops.
|
||||
type systemBus interface {
|
||||
listen() (<-chan signal, error)
|
||||
rating() (Rating, error)
|
||||
// sessions is every session of the account uid; session is one, by its object.
|
||||
sessions(uid uint32) ([]loginSession, error)
|
||||
session(path string) (loginSession, error)
|
||||
close()
|
||||
}
|
||||
|
||||
// openAsk is the sign-in asked now: the connection, its network and link, and since when.
|
||||
type openAsk struct {
|
||||
Network string `json:"network"`
|
||||
Link string `json:"link"`
|
||||
Since time.Time `json:"since"`
|
||||
connection string
|
||||
address string
|
||||
}
|
||||
|
||||
// watcherState is the watcher's answer to `state` (§23's read).
|
||||
type watcherState struct {
|
||||
Subscribed bool `json:"subscribed"`
|
||||
Rating string `json:"rating,omitempty"`
|
||||
RatingAt *time.Time `json:"rating_at,omitempty"`
|
||||
Ask *openAsk `json:"ask,omitempty"`
|
||||
AsksOpened int `json:"asks_opened"`
|
||||
AsksEnded int `json:"asks_ended"`
|
||||
DroppedPastBound int `json:"dropped_past_bound"`
|
||||
LastOpen *openOutcome `json:"last_open,omitempty"`
|
||||
LastNotification *note `json:"last_notification,omitempty"`
|
||||
LastSession *sessionNote `json:"last_session,omitempty"`
|
||||
}
|
||||
|
||||
// asked is an ask on the watcher's socket, handed to its loop, and the answer it sends back.
|
||||
type asked struct {
|
||||
ask string
|
||||
reply chan askReply
|
||||
}
|
||||
|
||||
type askReply struct {
|
||||
answer any
|
||||
err error
|
||||
}
|
||||
|
||||
// Watcher is the watch: what it reads through, and the state its loop alone holds.
|
||||
type Watcher struct {
|
||||
Folder Folder
|
||||
// Dial connects to the system bus.
|
||||
Dial func() (systemBus, error)
|
||||
// SocketThere fires at the file event of the kernel that makes the system bus's socket in its folder; closing stop
|
||||
// ends the wait.
|
||||
SocketThere func(stop <-chan struct{}) <-chan struct{}
|
||||
// SocketExists says whether the system bus's socket is there now.
|
||||
SocketExists func() bool
|
||||
Now func() time.Time
|
||||
// UID is the watcher's account, whose sessions are the person's.
|
||||
UID uint32
|
||||
// Environment reads the user manager's environment over a session's bus.
|
||||
Environment func(bus string) ([]string, error)
|
||||
// FileEvents fires at each file event of the kernel that makes a file in one of dirs, until stop closes.
|
||||
FileEvents func(dirs []string, stop <-chan struct{}) <-chan struct{}
|
||||
// After is a stated bound's end.
|
||||
After func(time.Duration) <-chan time.Time
|
||||
Desk desk
|
||||
// Beside runs an open beside the loop; the func it returns is run by the loop at its end.
|
||||
Beside func(work func() func())
|
||||
|
||||
// Made fires with each path a file event of the kernel makes in one of dirs, until stop closes.
|
||||
Made func(dirs []string, stop <-chan struct{}) <-chan string
|
||||
|
||||
told map[string]bool
|
||||
starting *sessionStart
|
||||
opening bool
|
||||
later []func()
|
||||
ends chan func()
|
||||
asks chan asked
|
||||
bus systemBus
|
||||
signals <-chan signal
|
||||
socketAt <-chan struct{}
|
||||
stopWait chan struct{}
|
||||
started bool
|
||||
state watcherState
|
||||
rating *Rating
|
||||
ask *openAsk
|
||||
}
|
||||
|
||||
func newWatcher(f Folder) *Watcher {
|
||||
w := &Watcher{Folder: f, Dial: dialSystemBus, SocketThere: systemSocketThere, Now: time.Now, asks: make(chan asked),
|
||||
UID: uint32(os.Getuid()), SocketExists: systemSocketExists, Environment: userEnvironment, FileEvents: fileEvents, After: time.After,
|
||||
Desk: newSessionDesk(), ends: make(chan func()), Made: pathsMade}
|
||||
w.Beside = w.besideLoop
|
||||
return w
|
||||
}
|
||||
|
||||
// watch is `uplink-tools watch`: the watcher, until its process is stopped.
|
||||
func watch([]string) error {
|
||||
f, err := theFolder()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f.Node == "" {
|
||||
return errors.New("no node named: the node-engine names it in MESH_NODE")
|
||||
}
|
||||
if err := os.MkdirAll(f.Dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the watcher's socket: %w", err)
|
||||
}
|
||||
w := newWatcher(f)
|
||||
go serveSocket(l, w.askLoop)
|
||||
return w.run(nil)
|
||||
}
|
||||
|
||||
// askLoop hands one ask of the socket to the loop and waits for its answer.
|
||||
func (w *Watcher) askLoop(ask string) (any, error) {
|
||||
reply := make(chan askReply, 1)
|
||||
w.asks <- asked{ask: ask, reply: reply}
|
||||
r := <-reply
|
||||
return r.answer, r.err
|
||||
}
|
||||
|
||||
// run is the watcher's loop, until stop closes: it subscribes, then acts on what it hears, one thing at a time. It ends
|
||||
// with an error when it cannot subscribe again once the system bus's socket came back, so the process exits non-zero
|
||||
// and its unit shows failing, the watcher's health (design 08 sign-in-page §11; lead answer C-2c).
|
||||
func (w *Watcher) run(stop <-chan struct{}) error {
|
||||
if w.asks == nil {
|
||||
w.asks = make(chan asked)
|
||||
}
|
||||
var made <-chan string
|
||||
if w.Made != nil {
|
||||
made = w.Made([]string{w.Folder.Dir, filepath.Join(w.Folder.Dir, pendingName)}, stop)
|
||||
}
|
||||
for _, p := range w.Folder.unknownAtStart() {
|
||||
w.strange(p)
|
||||
}
|
||||
w.subscribe()
|
||||
if !w.state.Subscribed && w.SocketExists != nil && w.SocketExists() {
|
||||
// The socket is there and refused the watcher: no file event will make it again, so waiting would leave the
|
||||
// unit active and the watcher deaf (design 08 sign-in-page §14; lead answer C2-1).
|
||||
w.unsubscribe()
|
||||
journal("the system bus's socket is there and the watcher could not subscribe on it at its start")
|
||||
return errors.New("the system bus's socket is there and the watcher could not subscribe on it at its start")
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
w.unsubscribe()
|
||||
return nil
|
||||
case s, ok := <-w.signals:
|
||||
if !ok {
|
||||
journal("the system bus connection dropped; subscribing again when its socket is there")
|
||||
w.unsubscribe()
|
||||
w.waitSocket()
|
||||
continue
|
||||
}
|
||||
w.heardSignal(s)
|
||||
case <-w.startingFiles():
|
||||
w.sessionFiles()
|
||||
case <-w.startingBound():
|
||||
w.sessionBound()
|
||||
case <-w.socketAt:
|
||||
w.socketAt = nil
|
||||
w.subscribe()
|
||||
if !w.state.Subscribed {
|
||||
w.unsubscribe()
|
||||
return errors.New("the system bus came back and the watcher could not subscribe on it")
|
||||
}
|
||||
case p := <-made:
|
||||
w.strange(p)
|
||||
case end := <-w.ends:
|
||||
end()
|
||||
case a := <-w.asks:
|
||||
answer, err := w.answer(a.ask)
|
||||
a.reply <- askReply{answer, err}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// subscribe connects to the system bus, listens, reads the rating and acts on it: at the watcher's start as its start,
|
||||
// after that as on a change (§14). One that fails waits for the system bus's socket.
|
||||
func (w *Watcher) subscribe() {
|
||||
w.unsubscribe()
|
||||
bus, err := w.Dial()
|
||||
if err == nil {
|
||||
var signals <-chan signal
|
||||
if signals, err = bus.listen(); err == nil {
|
||||
w.bus, w.signals, w.state.Subscribed = bus, signals, true
|
||||
} else {
|
||||
bus.close()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
journal("subscribing on the system bus failed: %v; subscribing again when its socket is there", err)
|
||||
w.waitSocket()
|
||||
return
|
||||
}
|
||||
journal("subscribed on the system bus")
|
||||
w.readRating()
|
||||
}
|
||||
|
||||
func (w *Watcher) unsubscribe() {
|
||||
if w.stopWait != nil {
|
||||
close(w.stopWait)
|
||||
w.stopWait, w.socketAt = nil, nil
|
||||
}
|
||||
if w.bus != nil {
|
||||
w.bus.close()
|
||||
}
|
||||
w.bus, w.signals, w.state.Subscribed = nil, nil, false
|
||||
}
|
||||
|
||||
func (w *Watcher) waitSocket() {
|
||||
w.stopWait = make(chan struct{})
|
||||
w.socketAt = w.SocketThere(w.stopWait)
|
||||
}
|
||||
|
||||
func (w *Watcher) heardSignal(s signal) {
|
||||
if s.Rating {
|
||||
w.readRating()
|
||||
}
|
||||
if s.Session != "" {
|
||||
w.sessionNew(s.Session)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Watcher) startingFiles() <-chan struct{} {
|
||||
if w.starting == nil {
|
||||
return nil
|
||||
}
|
||||
return w.starting.files
|
||||
}
|
||||
|
||||
func (w *Watcher) startingBound() <-chan time.Time {
|
||||
if w.starting == nil {
|
||||
return nil
|
||||
}
|
||||
return w.starting.bound
|
||||
}
|
||||
|
||||
// readRating reads the rating now and acts on it: as the watcher's start the first time, as a change after.
|
||||
func (w *Watcher) readRating() {
|
||||
if w.bus == nil {
|
||||
return
|
||||
}
|
||||
r, err := w.bus.rating()
|
||||
if err != nil {
|
||||
journal("reading the network manager's rating failed: %v", err)
|
||||
return
|
||||
}
|
||||
if !w.started {
|
||||
w.started = true
|
||||
w.heard(r, true)
|
||||
return
|
||||
}
|
||||
if w.opening {
|
||||
w.later = append(w.later, func() { w.heard(r, false) })
|
||||
return
|
||||
}
|
||||
w.heard(r, false)
|
||||
}
|
||||
|
||||
// heard acts on a rating read: the check address, a journal line for a change, and the events of §21.
|
||||
func (w *Watcher) heard(r Rating, atStart bool) {
|
||||
old := w.rating
|
||||
now := w.Now()
|
||||
w.rating, w.state.RatingAt = &r, &now
|
||||
w.state.Rating = ratingName(r.Connectivity)
|
||||
if atStart || old == nil || old.Connectivity != r.Connectivity || old.Connection != r.Connection {
|
||||
from := "none"
|
||||
if old != nil {
|
||||
from = ratingName(old.Connectivity)
|
||||
}
|
||||
journal("rating %s -> %s on %q", from, ratingName(r.Connectivity), r.Network)
|
||||
}
|
||||
if atStart || old == nil || old.CheckURI != r.CheckURI {
|
||||
if err := w.Folder.writeCheckAddress(r.CheckURI); err != nil {
|
||||
journal("writing the check address failed: %v", err)
|
||||
}
|
||||
}
|
||||
if r.checkOn() && !webAddress(r.CheckURI) {
|
||||
journal("the check address %q is not http or https: nothing kept, nothing opened", r.CheckURI)
|
||||
return
|
||||
}
|
||||
if atStart {
|
||||
if !r.checkOn() {
|
||||
return
|
||||
}
|
||||
if r.Connectivity == ratingPortal && r.active() {
|
||||
w.asked(r)
|
||||
return
|
||||
}
|
||||
w.ended(r.Link, r.Network, whyNoLongerAsked)
|
||||
return
|
||||
}
|
||||
if w.ask != nil {
|
||||
switch {
|
||||
case r.Connection != w.ask.connection:
|
||||
w.ended(w.ask.Link, w.ask.Network, whyLeft)
|
||||
case !r.checkOn() || (r.Connectivity != ratingPortal && r.Connectivity != ratingFull):
|
||||
w.ended(w.ask.Link, w.ask.Network, whyNoLongerAsked)
|
||||
case r.Connectivity == ratingFull:
|
||||
network := w.ask.Network
|
||||
w.ended(w.ask.Link, network, whySignedIn)
|
||||
w.tellSignedIn(network)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.checkOn() && r.Connectivity == ratingPortal && r.active() {
|
||||
w.asked(r)
|
||||
}
|
||||
}
|
||||
|
||||
// webAddress says whether an address is one the watcher keeps and opens: http or https, with a host.
|
||||
func webAddress(address string) bool {
|
||||
u, err := url.Parse(address)
|
||||
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
|
||||
}
|
||||
|
||||
// asked keeps sign-in-asked for the active connection and holds the ask.
|
||||
func (w *Watcher) asked(r Rating) {
|
||||
now := w.Now()
|
||||
w.ask = &openAsk{Network: r.Network, Link: r.Link, Since: now, connection: r.Connection, address: r.CheckURI}
|
||||
w.state.AsksOpened++
|
||||
w.keep(eventAsked, nodeuplink.SignInAsked{Node: w.Folder.Node, Link: r.Link, Network: r.Network, Address: r.CheckURI,
|
||||
At: stamp(now)})
|
||||
w.present(nil, r.Network, r.CheckURI)
|
||||
}
|
||||
|
||||
// ended keeps sign-in-ended and drops the ask.
|
||||
func (w *Watcher) ended(link, network, why string) {
|
||||
if w.ask != nil {
|
||||
w.state.AsksEnded++
|
||||
}
|
||||
w.ask = nil
|
||||
w.keep(eventEnded, nodeuplink.SignInEnded{Node: w.Folder.Node, Link: link, Network: network, At: stamp(w.Now()), Why: why})
|
||||
}
|
||||
|
||||
// stamp is a time as the events say it: RFC 3339 in UTC, to the second.
|
||||
func stamp(t time.Time) string { return t.UTC().Truncate(time.Second).Format(time.RFC3339) }
|
||||
|
||||
// keep writes one event into pending/ and holds the folder to its bound, the oldest dropped with a journal line.
|
||||
func (w *Watcher) keep(event string, body any) {
|
||||
k, err := w.Folder.keep(event, eventSubject(event, w.Folder.Node), body)
|
||||
if err != nil {
|
||||
journal("keeping %s failed: %v", event, err)
|
||||
return
|
||||
}
|
||||
journal("kept %s as %s", event, k.MessageID)
|
||||
kept, err := w.Folder.pending()
|
||||
if err != nil {
|
||||
journal("reading the kept events failed: %v", err)
|
||||
return
|
||||
}
|
||||
for i := 0; len(kept)-i > keptBound; i++ {
|
||||
if err := w.Folder.drop(kept[i]); err != nil {
|
||||
journal("dropping the kept event %s past the bound of %d failed: %v", kept[i].MessageID, keptBound, err)
|
||||
continue
|
||||
}
|
||||
w.state.DroppedPastBound++
|
||||
journal("dropped the kept event %s past the bound of %d", kept[i].MessageID, keptBound)
|
||||
}
|
||||
}
|
||||
|
||||
// answer answers an ask of the watcher's socket: its state, or rating-again, which subscribes again and acts on the
|
||||
// rating read now as on a change (§12).
|
||||
func (w *Watcher) answer(ask string) (any, error) {
|
||||
switch ask {
|
||||
case askState:
|
||||
s := w.state
|
||||
if w.ask != nil {
|
||||
a := *w.ask
|
||||
s.Ask = &a
|
||||
}
|
||||
return s, nil
|
||||
case askRatingAgain:
|
||||
journal("asked rating-again: subscribing again")
|
||||
w.subscribe()
|
||||
if !w.state.Subscribed {
|
||||
return nil, errors.New("subscribing on the system bus failed; waiting for its socket")
|
||||
}
|
||||
return w.state, nil
|
||||
}
|
||||
return nil, fmt.Errorf("the watcher has no ask %q", ask)
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
)
|
||||
|
||||
// The system bus stood in: the rating the test sets, each connection's signals on an unbuffered channel (a send
|
||||
// returns once the watcher's loop took it), and the system bus's socket fired by the test.
|
||||
type fakeSystem struct {
|
||||
mu sync.Mutex
|
||||
now Rating
|
||||
sessions []loginSession
|
||||
// refuse is how many dials, from the next, are refused.
|
||||
refuse int
|
||||
reads int
|
||||
dials int
|
||||
buses []*fakeBus
|
||||
socket chan struct{}
|
||||
}
|
||||
|
||||
type fakeBus struct {
|
||||
sys *fakeSystem
|
||||
signals chan signal
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (s *fakeSystem) dial() (systemBus, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.dials++
|
||||
if s.refuse > 0 {
|
||||
s.refuse--
|
||||
return nil, errors.New("connection refused")
|
||||
}
|
||||
b := &fakeBus{sys: s, signals: make(chan signal)}
|
||||
s.buses = append(s.buses, b)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (s *fakeSystem) set(r Rating) {
|
||||
s.mu.Lock()
|
||||
s.now = r
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *fakeSystem) last() *fakeBus {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.buses[len(s.buses)-1]
|
||||
}
|
||||
|
||||
func (s *fakeSystem) counts() (int, int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.reads, s.dials
|
||||
}
|
||||
|
||||
func (b *fakeBus) listen() (<-chan signal, error) { return b.signals, nil }
|
||||
func (b *fakeBus) sessions(uid uint32) ([]loginSession, error) {
|
||||
b.sys.mu.Lock()
|
||||
defer b.sys.mu.Unlock()
|
||||
var out []loginSession
|
||||
for _, s := range b.sys.sessions {
|
||||
if s.UID == uid {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (b *fakeBus) session(path string) (loginSession, error) {
|
||||
b.sys.mu.Lock()
|
||||
defer b.sys.mu.Unlock()
|
||||
for _, s := range b.sys.sessions {
|
||||
if s.Path == path {
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
return loginSession{}, fmt.Errorf("no session %s", path)
|
||||
}
|
||||
func (b *fakeBus) close() { b.closed = true }
|
||||
func (b *fakeBus) rating() (Rating, error) {
|
||||
b.sys.mu.Lock()
|
||||
defer b.sys.mu.Unlock()
|
||||
b.sys.reads++
|
||||
return b.sys.now, nil
|
||||
}
|
||||
|
||||
// journalLines collects the journal for one test.
|
||||
func journalLines(t *testing.T) func() []string {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var lines []string
|
||||
was := journal
|
||||
journal = func(format string, args ...any) {
|
||||
mu.Lock()
|
||||
lines = append(lines, fmt.Sprintf(format, args...))
|
||||
mu.Unlock()
|
||||
}
|
||||
t.Cleanup(func() { journal = was })
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), lines...)
|
||||
}
|
||||
}
|
||||
|
||||
var clockStart = time.Date(2026, 11, 24, 19, 0, 0, 0, time.UTC)
|
||||
|
||||
// aWatcher is a watcher over the stood-in system bus, its clock one second on at each reading.
|
||||
func aWatcher(t *testing.T, sys *fakeSystem) *Watcher {
|
||||
t.Helper()
|
||||
tick := clockStart
|
||||
var mu sync.Mutex
|
||||
return &Watcher{Folder: aFolder(t), Dial: sys.dial, Now: func() time.Time {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
tick = tick.Add(time.Second)
|
||||
return tick
|
||||
}, SocketThere: func(stop <-chan struct{}) <-chan struct{} { return sys.socket }, asks: make(chan asked),
|
||||
UID: 1000, Desk: &fakeDesk{}, Environment: func(string) ([]string, error) { return nil, nil },
|
||||
FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
After: func(time.Duration) <-chan time.Time { return nil },
|
||||
Beside: func(work func() func()) { work()() }}
|
||||
}
|
||||
|
||||
// The desktop stood in: each open it was asked, answered with outcome.
|
||||
type fakeDesk struct {
|
||||
mu sync.Mutex
|
||||
opens []string
|
||||
notes []note
|
||||
outcome openOutcome
|
||||
}
|
||||
|
||||
func (d *fakeDesk) notify(s Session, n note) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.notes = append(d.notes, n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// shown is every notification shown, as `[critical] summary: body`.
|
||||
func (d *fakeDesk) shown() []string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
var out []string
|
||||
for _, n := range d.notes {
|
||||
critical := ""
|
||||
if n.Critical {
|
||||
critical = "critical "
|
||||
}
|
||||
out = append(out, critical+n.Summary+": "+n.Body)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (d *fakeDesk) open(s Session, address string) openOutcome {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.opens = append(d.opens, s.ID+" "+address)
|
||||
o := d.outcome
|
||||
if o.Outcome == "" {
|
||||
o = openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened}
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (d *fakeDesk) opened() []string {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return append([]string(nil), d.opens...)
|
||||
}
|
||||
|
||||
// keptSaid is every kept event as `<event> <why> <network> <link>`, in order.
|
||||
func keptSaid(t *testing.T, f Folder) []string {
|
||||
t.Helper()
|
||||
kept, err := f.pending()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, k := range kept {
|
||||
var b struct{ Node, Link, Network, Address, At, Why string }
|
||||
if err := json.Unmarshal(k.Body, &b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
event := strings.Split(k.MessageID, ".")[1]
|
||||
if k.Subject != "mesh.seat.node-uplink.event."+event+".laptop" || b.Node != "laptop" || b.At == "" {
|
||||
t.Errorf("kept %+v %+v", k, b)
|
||||
}
|
||||
if event == eventAsked && b.Address != "http://check.example.net/" {
|
||||
t.Errorf("asked with the address %q", b.Address)
|
||||
}
|
||||
out = append(out, strings.Join(strings.Fields(fmt.Sprintf("%s %s %s %s", event, b.Why, b.Network, b.Link)), " "))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func guest(connectivity uint32) Rating {
|
||||
return Rating{Connectivity: connectivity, CheckEnabled: true, CheckAvailable: true,
|
||||
CheckURI: "http://check.example.net/", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1",
|
||||
Network: "guest-example", Link: "wlan0"}
|
||||
}
|
||||
|
||||
func other(connectivity uint32) Rating {
|
||||
r := guest(connectivity)
|
||||
r.Connection, r.Network, r.Link = "/org/freedesktop/NetworkManager/ActiveConnection/2", "home-example", "eth0"
|
||||
return r
|
||||
}
|
||||
|
||||
func with(r Rating, change func(*Rating)) Rating {
|
||||
change(&r)
|
||||
return r
|
||||
}
|
||||
|
||||
// Each line of §21 keeps its event, and with the check off, or a check address that is not http or https, nothing is
|
||||
// kept (design 08 sign-in-page §21, §25).
|
||||
func TestEachLineOfTheRulesKeepsItsEvent(t *testing.T) {
|
||||
off := func(r *Rating) { r.CheckEnabled = false }
|
||||
unavailable := func(r *Rating) { r.CheckAvailable = false }
|
||||
none := func(r *Rating) { r.Connection, r.Network, r.Link = "/", "", "" }
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
ratings []Rating
|
||||
kept []string
|
||||
}{
|
||||
{"PORTAL at the start", []Rating{guest(ratingPortal)}, []string{"sign-in-asked guest-example wlan0"}},
|
||||
{"FULL at the start", []Rating{guest(ratingFull)},
|
||||
[]string{"sign-in-ended no-longer-asked guest-example wlan0"}},
|
||||
{"no connection at the start", []Rating{with(guest(ratingNone), none)},
|
||||
[]string{"sign-in-ended no-longer-asked"}},
|
||||
{"PORTAL at a join", []Rating{guest(ratingFull), guest(ratingPortal)},
|
||||
[]string{"sign-in-ended no-longer-asked guest-example wlan0", "sign-in-asked guest-example wlan0"}},
|
||||
{"staying PORTAL says it once", []Rating{guest(ratingPortal), guest(ratingPortal), guest(ratingPortal)},
|
||||
[]string{"sign-in-asked guest-example wlan0"}},
|
||||
{"signed in", []Rating{guest(ratingPortal), guest(ratingFull), guest(ratingFull)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended signed-in guest-example wlan0"}},
|
||||
{"the connection replaced, PORTAL again", []Rating{guest(ratingPortal), other(ratingPortal)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0",
|
||||
"sign-in-asked home-example eth0"}},
|
||||
{"the connection gone", []Rating{guest(ratingPortal), with(guest(ratingNone), none)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0"}},
|
||||
{"LIMITED", []Rating{guest(ratingPortal), guest(ratingLimited)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
|
||||
{"UNKNOWN", []Rating{guest(ratingPortal), guest(ratingUnknown)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
|
||||
{"the check switched off while asked", []Rating{guest(ratingPortal), with(guest(ratingPortal), off)},
|
||||
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
|
||||
{"the check off", []Rating{with(guest(ratingPortal), off), with(guest(ratingFull), off),
|
||||
with(guest(ratingPortal), off)}, nil},
|
||||
{"the check not available", []Rating{with(guest(ratingPortal), unavailable), with(guest(ratingPortal), unavailable)},
|
||||
nil},
|
||||
{"a check address not http", []Rating{with(guest(ratingPortal), func(r *Rating) { r.CheckURI = "ftp://check.example.net/" })},
|
||||
nil},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
journalLines(t)
|
||||
w := aWatcher(t, &fakeSystem{})
|
||||
for i, r := range c.ratings {
|
||||
w.heard(r, i == 0)
|
||||
}
|
||||
if got := keptSaid(t, w.Folder); strings.Join(got, "|") != strings.Join(c.kept, "|") {
|
||||
t.Fatalf("kept %q, want %q", got, c.kept)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Past 256 kept events the oldest goes, with a journal line naming it, and the state counts it (§20, §25).
|
||||
func TestPastTheBoundTheOldestKeptEventGoes(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
w := aWatcher(t, &fakeSystem{})
|
||||
for range keptBound {
|
||||
if _, err := w.Folder.keep(eventEnded, eventSubject(eventEnded, "laptop"), map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
w.heard(guest(ratingPortal), true)
|
||||
kept, _ := w.Folder.pending()
|
||||
if len(kept) != keptBound || kept[0].Sequence != 2 || kept[len(kept)-1].MessageID != "laptop.sign-in-asked.257" {
|
||||
t.Fatalf("kept %d, from %d", len(kept), kept[0].Sequence)
|
||||
}
|
||||
said := strings.Join(lines(), "\n")
|
||||
if !strings.Contains(said, "dropped the kept event laptop.sign-in-ended.1 past the bound of 256") ||
|
||||
w.state.DroppedPastBound != 1 {
|
||||
t.Fatalf("the drop was not said: %s", said)
|
||||
}
|
||||
}
|
||||
|
||||
// The system bus dropping and its socket coming back make the watcher subscribe again and act on the rating read then
|
||||
// as on a change; rating-again does the same at once; between them, nothing reads the rating but a signal (§14, §25).
|
||||
func TestTheWatcherSubscribesAgainAndRunsOnNoTimer(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{socket: make(chan struct{})}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
stop := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() { _ = w.run(stop); close(done) }()
|
||||
defer func() { close(stop); <-done }()
|
||||
state := func() watcherState {
|
||||
s, err := w.askLoop(askState)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s.(watcherState)
|
||||
}
|
||||
if s := state(); !s.Subscribed || s.Rating != "FULL" {
|
||||
t.Fatalf("at its start %+v", s)
|
||||
}
|
||||
for range 3 {
|
||||
state()
|
||||
}
|
||||
if reads, _ := sys.counts(); reads != 1 {
|
||||
t.Fatalf("the rating was read %d times with no signal: something reads it on a timer", reads)
|
||||
}
|
||||
sys.set(guest(ratingPortal))
|
||||
sys.last().signals <- signal{Rating: true}
|
||||
if s := state(); s.Ask == nil || s.Ask.Network != "guest-example" {
|
||||
t.Fatalf("PORTAL heard as %+v", s)
|
||||
}
|
||||
|
||||
close(sys.last().signals)
|
||||
if s := state(); s.Subscribed {
|
||||
t.Fatal("subscribed after the system bus dropped")
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "the system bus connection dropped") {
|
||||
t.Fatal("the drop was not written to the journal")
|
||||
}
|
||||
sys.set(guest(ratingFull))
|
||||
sys.socket <- struct{}{}
|
||||
if s := state(); !s.Subscribed || s.Ask != nil || s.Rating != "FULL" {
|
||||
t.Fatalf("after the socket came back %+v", s)
|
||||
}
|
||||
if got := keptSaid(t, w.Folder); got[len(got)-1] != "sign-in-ended signed-in guest-example wlan0" {
|
||||
t.Fatalf("the rating read on subscribing again was not acted on as a change: %q", got)
|
||||
}
|
||||
|
||||
sys.set(guest(ratingPortal))
|
||||
if _, err := w.askLoop(askRatingAgain); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reads, dials := sys.counts(); dials != 3 || reads != 4 || !sys.buses[1].closed {
|
||||
t.Fatalf("rating-again: %d dials, %d reads", dials, reads)
|
||||
}
|
||||
if s := state(); !s.Subscribed || s.Ask == nil || s.AsksOpened != 2 || s.AsksEnded != 1 {
|
||||
t.Fatalf("after rating-again %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// The signals the watcher hears, as the system bus sends them (recorded with dbus-monitor): the network manager's
|
||||
// PropertiesChanged for a property of the rating, not for another, and logind's SessionNew (§14, §17).
|
||||
func TestTheWatcherHearsTheSystemBusSignals(t *testing.T) {
|
||||
changed := func(props map[string]dbus.Variant, invalidated []string) *dbus.Signal {
|
||||
return &dbus.Signal{Sender: ":1.5", Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged",
|
||||
Body: []any{"org.freedesktop.NetworkManager", props, invalidated}}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
s *dbus.Signal
|
||||
want signal
|
||||
ok bool
|
||||
}{
|
||||
{"Connectivity", changed(map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, []string{}),
|
||||
signal{Rating: true}, true},
|
||||
{"PrimaryConnection", changed(map[string]dbus.Variant{"PrimaryConnection": dbus.MakeVariant(dbus.ObjectPath("/"))},
|
||||
[]string{}), signal{Rating: true}, true},
|
||||
{"ConnectivityCheckUri invalidated", changed(map[string]dbus.Variant{}, []string{"ConnectivityCheckUri"}),
|
||||
signal{Rating: true}, true},
|
||||
{"another property", changed(map[string]dbus.Variant{"Metered": dbus.MakeVariant(uint32(4))}, []string{}),
|
||||
signal{}, false},
|
||||
{"another interface", &dbus.Signal{Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged",
|
||||
Body: []any{"org.freedesktop.NetworkManager.Device", map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))},
|
||||
[]string{}}}, signal{}, false},
|
||||
{"SessionNew", &dbus.Signal{Sender: ":1.3", Path: login1Path, Name: "org.freedesktop.login1.Manager.SessionNew",
|
||||
Body: []any{"4", dbus.ObjectPath("/org/freedesktop/login1/session/_34")}},
|
||||
signal{Session: "/org/freedesktop/login1/session/_34"}, true},
|
||||
} {
|
||||
got, ok := readSignal(c.s)
|
||||
if ok != c.ok || got != c.want {
|
||||
t.Errorf("%s: heard %+v %v", c.name, got, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The watcher dials the system bus again only at the file event that makes its socket and at rating-again, never in a
|
||||
// loop (§14; note d); and when the bus came back and it cannot subscribe on it, it ends with an error, so its process
|
||||
// exits non-zero and its unit shows failing (§11; lead answer C-2c).
|
||||
func TestTheWatcherRedialsOnlyAtTheSocketsEventAndRatingAgain(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{socket: make(chan struct{}), refuse: 1}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
stop, done := make(chan struct{}), make(chan error, 1)
|
||||
go func() { done <- w.run(stop) }()
|
||||
state := func() watcherState {
|
||||
s, _ := w.askLoop(askState)
|
||||
return s.(watcherState)
|
||||
}
|
||||
dials := func() int { _, d := sys.counts(); return d }
|
||||
for range 3 {
|
||||
if s := state(); s.Subscribed {
|
||||
t.Fatal("subscribed through a refused dial")
|
||||
}
|
||||
}
|
||||
if d := dials(); d != 1 {
|
||||
t.Fatalf("a bus that refused the watcher at its start was dialled %d times with no event", d)
|
||||
}
|
||||
sys.socket <- struct{}{}
|
||||
if s := state(); !s.Subscribed || dials() != 2 {
|
||||
t.Fatalf("at the socket's event: %+v, %d dials", s, dials())
|
||||
}
|
||||
close(sys.last().signals)
|
||||
state()
|
||||
state()
|
||||
if d := dials(); d != 2 {
|
||||
t.Fatalf("a dropped connection was dialled again before the socket's event: %d dials", d)
|
||||
}
|
||||
if _, err := w.askLoop(askRatingAgain); err != nil || dials() != 3 || !state().Subscribed {
|
||||
t.Fatalf("rating-again: %v, %d dials", err, dials())
|
||||
}
|
||||
close(sys.last().signals)
|
||||
sys.mu.Lock()
|
||||
sys.refuse = 1
|
||||
sys.mu.Unlock()
|
||||
sys.socket <- struct{}{}
|
||||
if err := <-done; err == nil || !strings.Contains(err.Error(), "could not subscribe") || dials() != 4 {
|
||||
t.Fatalf("the bus came back refusing: the watcher ended with %v after %d dials", err, dials())
|
||||
}
|
||||
close(stop)
|
||||
}
|
||||
|
||||
// When its first subscribe at its start fails while the system bus's socket is there, no file event will come: the
|
||||
// watcher writes the reason to its journal and ends with an error, so its process exits non-zero (§14; lead answer
|
||||
// C2-1). With no socket there it waits for the one that makes it, as above.
|
||||
func TestARefusedStartWithTheSocketThereEndsTheWatcher(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{socket: make(chan struct{}), refuse: 1}
|
||||
w := aWatcher(t, sys)
|
||||
w.SocketExists = func() bool { return true }
|
||||
ended := make(chan error, 1)
|
||||
go func() { ended <- w.run(make(chan struct{})) }()
|
||||
answered := make(chan struct{})
|
||||
go func() { w.askLoop(askState); close(answered) }()
|
||||
var err error
|
||||
select {
|
||||
case err = <-ended:
|
||||
case <-answered:
|
||||
t.Fatal("the watcher waits for a file event that will not come, its unit left active")
|
||||
}
|
||||
if _, dials := sys.counts(); err == nil || !strings.Contains(err.Error(), "at its start") || dials != 1 {
|
||||
t.Fatalf("the watcher ended with %v after %d dials", err, dials)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "could not subscribe on it at its start") {
|
||||
t.Fatalf("the reason is not in the journal: %q", lines())
|
||||
}
|
||||
}
|
||||
|
||||
// The real wait fires at the file event that makes the system bus's socket, not for one that is merely there (note d).
|
||||
func TestTheSocketsWaitFiresWhenTheSocketIsMade(t *testing.T) {
|
||||
journalLines(t)
|
||||
dir := t.TempDir()
|
||||
was := systemSocket
|
||||
systemSocket = filepath.Join(dir, "system_bus_socket")
|
||||
t.Cleanup(func() { systemSocket = was })
|
||||
if err := os.WriteFile(systemSocket, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stop := make(chan struct{})
|
||||
defer close(stop)
|
||||
there := systemSocketThere(stop)
|
||||
select {
|
||||
case <-there:
|
||||
t.Fatal("fired for a socket that was already there")
|
||||
default:
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "other"), nil, 0o600)
|
||||
os.Remove(systemSocket)
|
||||
if err := os.WriteFile(systemSocket+".made", nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(systemSocket+".made", systemSocket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-there
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//go:build integration
|
||||
|
||||
package main
|
||||
|
||||
// networkmanager whole (design 08 sign-in-page §25, R-M4, R2-1): its watcher, with the system bus, logind, the user
|
||||
// manager and the desktop stood in, runs with no bus and opens the page; then the bundle, the built binary played over
|
||||
// its real stdin and stdout as the node's tool runner plays it, meets a real bus holding node-uplink's events family and
|
||||
// a stand-in holder of node-resolver: the kept events are published in order with the times of their changes, each
|
||||
// matching the seat's definition, and uplink-names is called.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
)
|
||||
|
||||
// clock is the watcher's clock, set by the test before each change.
|
||||
type clock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (c *clock) set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() }
|
||||
func (c *clock) read() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now }
|
||||
|
||||
// tellingDesk is the stood-in desktop, saying each notification on a channel.
|
||||
type tellingDesk struct {
|
||||
fakeDesk
|
||||
told chan note
|
||||
}
|
||||
|
||||
func (d *tellingDesk) notify(s Session, n note) error {
|
||||
d.fakeDesk.notify(s, n)
|
||||
d.told <- n
|
||||
return nil
|
||||
}
|
||||
|
||||
// runtime plays the node's tool runner for the bundle over a real bus: a kept event said on the seat is published on
|
||||
// the stream with the module's prefix on its id, awaiting the acknowledgement; a seat verb is asked of its holder.
|
||||
type runtime struct {
|
||||
t *testing.T
|
||||
ctx context.Context
|
||||
nc *nats.Conn
|
||||
js jetstream.JetStream
|
||||
mu sync.Mutex
|
||||
in io.Writer
|
||||
next int
|
||||
pending map[string]chan json.RawMessage
|
||||
// mayPublish is every subject the module's membership lets it say, as the runtime's mayPublish reads it.
|
||||
mayPublish map[string]bool
|
||||
}
|
||||
|
||||
// membershipPublish is what the module's membership lists it may publish on node: a held seat's own-node machine
|
||||
// events, the rule mesh-grants' MembershipFor holds (mesh-delivery ef8dd120), read here from the shared contract and the
|
||||
// module's own manifest, never from mesh-grants' code.
|
||||
func membershipPublish(t *testing.T, node string) map[string]bool {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Claims []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"claims"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, c := range m.Claims {
|
||||
if c.Name == nodeuplink.Seat {
|
||||
out[nodeuplink.SubjectSignInAsked(node)] = true
|
||||
out[nodeuplink.SubjectSignInEnded(node)] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *runtime) send(m map[string]any) {
|
||||
m["jsonrpc"] = "2.0"
|
||||
raw, _ := json.Marshal(m)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.in.Write(append(raw, '\n'))
|
||||
}
|
||||
|
||||
func (r *runtime) answer(id json.RawMessage, result any, err error) {
|
||||
if err != nil {
|
||||
r.send(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
|
||||
return
|
||||
}
|
||||
r.send(map[string]any{"id": id, "result": result})
|
||||
}
|
||||
|
||||
func (r *runtime) serve(out io.Reader) {
|
||||
scanner := bufio.NewScanner(out)
|
||||
scanner.Buffer(make([]byte, 1<<20), 1<<24)
|
||||
for scanner.Scan() {
|
||||
var m struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(scanner.Bytes(), &m) != nil {
|
||||
continue
|
||||
}
|
||||
if m.Method == "" {
|
||||
var id string
|
||||
json.Unmarshal(m.ID, &id)
|
||||
r.mu.Lock()
|
||||
ch := r.pending[id]
|
||||
r.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- m.Result
|
||||
}
|
||||
continue
|
||||
}
|
||||
go r.handle(m.ID, m.Method, m.Params)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *runtime) handle(id json.RawMessage, method string, params json.RawMessage) {
|
||||
switch method {
|
||||
case "mesh/seat.publish":
|
||||
var p struct {
|
||||
Subject string `json:"subject"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
json.Unmarshal(params, &p)
|
||||
if !r.mayPublish[p.Subject] {
|
||||
r.answer(id, nil, fmt.Errorf("%s may not publish %s: its membership does not list it", Module, p.Subject))
|
||||
return
|
||||
}
|
||||
_, err := r.js.Publish(r.ctx, p.Subject, p.Body, jetstream.WithMsgID(Module+"."+p.ID))
|
||||
r.answer(id, map[string]any{}, err)
|
||||
case "mesh/ask":
|
||||
var p struct {
|
||||
Key string `json:"key"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
json.Unmarshal(params, &p)
|
||||
switch p.Key {
|
||||
case "seat:mesh-module-assigner.assignments":
|
||||
r.answer(id, json.RawMessage(`{"seats":[{"seat":"node-resolver","node":"home-server",`+
|
||||
`"holders":[{"module":"systemd-resolved","node":"home-server"}]}]}`), nil)
|
||||
case "seat:node-resolver.uplink-names@home-server":
|
||||
msg, err := r.nc.Request("stand-in.node-resolver.uplink-names", p.Body, testbus.SetupBound(r.t))
|
||||
if err != nil {
|
||||
r.answer(id, nil, err)
|
||||
return
|
||||
}
|
||||
r.answer(id, json.RawMessage(msg.Data), nil)
|
||||
default:
|
||||
r.answer(id, nil, errors.New("nats: no responders available for request"))
|
||||
}
|
||||
case "mesh/subscribe":
|
||||
r.answer(id, map[string]any{}, nil)
|
||||
default:
|
||||
r.answer(id, nil, fmt.Errorf("%s is not played here", method))
|
||||
}
|
||||
}
|
||||
|
||||
// call calls one of the bundle's tools and answers its result's text.
|
||||
func (r *runtime) call(name string) string {
|
||||
r.t.Helper()
|
||||
r.mu.Lock()
|
||||
r.next++
|
||||
id := fmt.Sprintf("c-%d", r.next)
|
||||
ch := make(chan json.RawMessage, 1)
|
||||
r.pending[id] = ch
|
||||
r.mu.Unlock()
|
||||
r.send(map[string]any{"id": id, "method": "tools/call", "params": map[string]any{"name": name, "arguments": map[string]any{}}})
|
||||
select {
|
||||
case raw := <-ch:
|
||||
var res struct {
|
||||
Content []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
IsError bool `json:"isError"`
|
||||
}
|
||||
json.Unmarshal(raw, &res)
|
||||
if res.IsError || len(res.Content) == 0 {
|
||||
r.t.Fatalf("%s answered %s", name, raw)
|
||||
}
|
||||
return res.Content[0].Text
|
||||
case <-time.After(testbus.SetupBound(r.t)):
|
||||
testbus.Starved(r.t, name+" was not answered")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Module is the module the runtime serves the bundle as.
|
||||
const Module = "networkmanager"
|
||||
|
||||
func TestNetworkManagerWhole(t *testing.T) {
|
||||
home, err := os.MkdirTemp("", "nm")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(home) })
|
||||
f := Folder{Dir: filepath.Join(home, stateHome), Node: "home-server"}
|
||||
if err := os.MkdirAll(f.Dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The watcher, with no bus: the rating FULL at its start, then PORTAL at 10:00, FULL at 10:05.
|
||||
portal := Rating{Connectivity: ratingFull, CheckEnabled: true, CheckAvailable: true,
|
||||
CheckURI: "http://example.net/portal", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1",
|
||||
Network: "guest-example", Link: "wlan0"}
|
||||
sys := &fakeSystem{socket: make(chan struct{}), sessions: []loginSession{personsSession()}}
|
||||
sys.set(portal)
|
||||
at := &clock{}
|
||||
desk := &tellingDesk{told: make(chan note, 4)}
|
||||
w := &Watcher{Folder: f, Dial: sys.dial, SocketThere: func(<-chan struct{}) <-chan struct{} { return sys.socket },
|
||||
Now: at.read, asks: make(chan asked), UID: 1000, Desk: desk, ends: make(chan func()),
|
||||
Environment: func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil },
|
||||
FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
After: func(time.Duration) <-chan time.Time { return nil }}
|
||||
w.Beside = w.besideLoop
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { l.Close() })
|
||||
go serveSocket(l, w.askLoop)
|
||||
stop, stopped := make(chan struct{}), make(chan struct{})
|
||||
at.set(time.Date(2026, 11, 24, 9, 59, 0, 0, time.UTC))
|
||||
go func() { _ = w.run(stop); close(stopped) }()
|
||||
t.Cleanup(func() { close(stop); <-stopped })
|
||||
told := func(summary string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case n := <-desk.told:
|
||||
if n.Summary != summary {
|
||||
t.Fatalf("told %q, want %q", n.Summary, summary)
|
||||
}
|
||||
case <-time.After(testbus.SetupBound(t)):
|
||||
testbus.Starved(t, "no notification "+summary)
|
||||
}
|
||||
}
|
||||
w.askLoop(askState)
|
||||
at.set(time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC))
|
||||
portal.Connectivity = ratingPortal
|
||||
sys.set(portal)
|
||||
sys.last().signals <- signal{Rating: true}
|
||||
told("This network asks you to sign in")
|
||||
if got := desk.opened(); len(got) != 1 || got[0] != "2 http://example.net/portal" {
|
||||
t.Fatalf("with no bus the watcher opened %q", got)
|
||||
}
|
||||
at.set(time.Date(2026, 11, 24, 10, 5, 0, 0, time.UTC))
|
||||
portal.Connectivity = ratingFull
|
||||
sys.set(portal)
|
||||
sys.last().signals <- signal{Rating: true}
|
||||
told("The network is open")
|
||||
w.askLoop(askState)
|
||||
kept, err := f.pending()
|
||||
if err != nil || len(kept) != 3 {
|
||||
t.Fatalf("kept %+v %v", kept, err)
|
||||
}
|
||||
|
||||
// The bus comes: node-uplink's family on the events stream, and a stand-in holder of node-resolver.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
nc, err := nats.Connect(testbus.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
js, err := jetstream.New(nc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stream, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS",
|
||||
Subjects: []string{nodeuplink.SubjectSignInAskedAll, nodeuplink.SubjectSignInEndedAll},
|
||||
MaxAge: nodeuplink.FamilyMaxAgeDays * 24 * time.Hour, Duplicates: time.Hour})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
given := make(chan string, 8)
|
||||
if _, err := nc.Subscribe("stand-in.node-resolver.uplink-names", func(m *nats.Msg) {
|
||||
given <- string(m.Data)
|
||||
m.Respond([]byte(`{"names":["example.net"],"link":"wlan0","set_at":"2026-11-24T10:06:00Z"}`))
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
bin := filepath.Join(home, "uplink-tools")
|
||||
if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil {
|
||||
t.Fatalf("building uplink-tools: %v\n%s", err, out)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, bin)
|
||||
cmd.Env = append(os.Environ(), "HOME="+home, "MESH_NODE=home-server", "MESH_MODULE="+Module, "MESH_SERVED_MODULE="+Module)
|
||||
in, _ := cmd.StdinPipe()
|
||||
out, _ := cmd.StdoutPipe()
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { in.Close(); cmd.Wait() })
|
||||
r := &runtime{t: t, ctx: ctx, nc: nc, js: js, in: in, pending: map[string]chan json.RawMessage{},
|
||||
mayPublish: membershipPublish(t, "home-server")}
|
||||
go r.serve(out)
|
||||
|
||||
select {
|
||||
case body := <-given:
|
||||
if body != `{"names":["example.net"]}` {
|
||||
t.Fatalf("uplink-names was given %s", body)
|
||||
}
|
||||
case <-time.After(testbus.SetupBound(t)):
|
||||
testbus.Starved(t, "uplink-names was not called")
|
||||
}
|
||||
consumer, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type published struct {
|
||||
subject, id string
|
||||
body []byte
|
||||
}
|
||||
var got []published
|
||||
for len(got) < 3 {
|
||||
msg, err := consumer.Next(jetstream.FetchMaxWait(testbus.SetupBound(t)))
|
||||
if err != nil {
|
||||
testbus.Starved(t, fmt.Sprintf("%d of the 3 kept events were published: %v", len(got), err))
|
||||
}
|
||||
got = append(got, published{msg.Subject(), msg.Headers().Get(jetstream.MsgIDHeader), msg.Data()})
|
||||
}
|
||||
for i, k := range kept {
|
||||
if got[i].id != Module+"."+k.MessageID || string(got[i].body) != string(k.Body) || got[i].subject != k.Subject {
|
||||
t.Errorf("published %d: %s %s %s, kept %s %s %s", i, got[i].subject, got[i].id, got[i].body, k.Subject,
|
||||
k.MessageID, k.Body)
|
||||
}
|
||||
}
|
||||
strict := func(raw []byte, into any) {
|
||||
t.Helper()
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(into); err != nil {
|
||||
t.Fatalf("%s does not match the seat's definition: %v", raw, err)
|
||||
}
|
||||
}
|
||||
var asked nodeuplink.SignInAsked
|
||||
strict(got[1].body, &asked)
|
||||
if got[1].subject != nodeuplink.SubjectSignInAsked("home-server") || asked != (nodeuplink.SignInAsked{
|
||||
Node: "home-server", Link: "wlan0", Network: "guest-example", Address: "http://example.net/portal",
|
||||
At: "2026-11-24T10:00:00Z"}) {
|
||||
t.Errorf("sign-in-asked is %s on %s", got[1].body, got[1].subject)
|
||||
}
|
||||
var ended nodeuplink.SignInEnded
|
||||
strict(got[2].body, &ended)
|
||||
if got[2].subject != nodeuplink.SubjectSignInEnded("home-server") || ended != (nodeuplink.SignInEnded{
|
||||
Node: "home-server", Link: "wlan0", Network: "guest-example", At: "2026-11-24T10:05:00Z",
|
||||
Why: nodeuplink.SignInEndedWhySignedIn}) {
|
||||
t.Errorf("sign-in-ended is %s on %s", got[2].body, got[2].subject)
|
||||
}
|
||||
if text := r.call("uplink_publish_again"); text != `{"published":0,"waiting":0}` {
|
||||
t.Fatalf("after the publishes uplink_publish_again answered %s", text)
|
||||
}
|
||||
if left, _ := f.pending(); len(left) != 0 {
|
||||
t.Fatalf("left in pending/: %+v", left)
|
||||
}
|
||||
|
||||
// Another node's subject is not the module's to say: the runtime refuses it and it stays kept.
|
||||
if _, err := f.keep(eventAsked, nodeuplink.SubjectSignInAsked("other-node"), map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if text := r.call("uplink_publish_again"); !strings.Contains(text, `"waiting":1`) ||
|
||||
!strings.Contains(text, "its membership does not list it") {
|
||||
t.Fatalf("another node's subject: uplink_publish_again answered %s", text)
|
||||
}
|
||||
if left, _ := f.pending(); len(left) != 1 {
|
||||
t.Fatalf("the refused event is not kept: %+v", left)
|
||||
}
|
||||
if info, err := stream.Info(ctx); err != nil || info.State.Msgs != 3 {
|
||||
t.Fatalf("the stream holds %v messages (%v), not the 3 published", info.State.Msgs, err)
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,24 @@ module networkmanager
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
require (
|
||||
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
github.com/godbus/dbus/v5 v5.1.0
|
||||
github.com/nats-io/nats.go v1.54.0
|
||||
golang.org/x/sys v0.48.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/klauspost/compress v1.20.1 // indirect
|
||||
github.com/nats-io/nats.go v1.54.0 // indirect
|
||||
github.com/minio/highwayhash v1.0.4 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.1 // indirect
|
||||
github.com/nats-io/nats-server/v2 v2.11.17 // indirect
|
||||
github.com/nats-io/nkeys v0.4.16 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
|
||||
github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
|
||||
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
|
||||
github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:B1sFVz4StNosQ903ak4N1G01Fl/9f8e06mXpFIE2K24=
|
||||
github.com/nats-io/nats-server/v2 v2.11.17 h1:GKEghcFK6A+aFx11Yf1LjgLC3txAwvyhnYzhBIQZA8I=
|
||||
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
|
||||
@@ -21,6 +21,21 @@
|
||||
"scope": "node"
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"node-engine.running"
|
||||
],
|
||||
"invokes": [
|
||||
"seat:mesh-module-assigner.assignments",
|
||||
"seat:node-resolver.uplink-names",
|
||||
"seat:node-resolver.routes"
|
||||
],
|
||||
"tools": [
|
||||
"uplink_sign_in",
|
||||
"uplink_names_again",
|
||||
"uplink_rating_again",
|
||||
"uplink_publish_again",
|
||||
"uplink_health"
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
@@ -67,6 +82,28 @@
|
||||
"reload-on": [
|
||||
"config"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sign-in-state",
|
||||
"type": "directory",
|
||||
"path": "${machine:account-home}/.local/state/mesh/networkmanager",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0700",
|
||||
"unknown": "module"
|
||||
},
|
||||
{
|
||||
"id": "sign-in",
|
||||
"type": "process",
|
||||
"name": "networkmanager-sign-in",
|
||||
"artifact": "tools",
|
||||
"run": [
|
||||
"./uplink-tools",
|
||||
"watch"
|
||||
],
|
||||
"user": "${machine:account}",
|
||||
"health": {
|
||||
"kind": "unit"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# systemd-networkd
|
||||
|
||||
The machine's network, managed by systemd-networkd: this module holds the node seat `node-uplink` (novox/hq ADR
|
||||
0241), answering its verbs `resolvers` and `links` from the same code as every holder of the seat, and writes the
|
||||
machine's resolver file from the mesh's resolvers (ADR 0117, ADR 0223).
|
||||
|
||||
**It announces neither of the seat's events and opens nothing** (ADR 0687 §1; design 08 sign-in-page §28).
|
||||
systemd-networkd cannot tell a network that asks the person to sign in on its sign-in page, so this holder says no
|
||||
`sign-in-asked` or `sign-in-ended`, which the seat's definition asks of no holder, and opens no page.
|
||||
@@ -1,5 +1,6 @@
|
||||
// The uplink holder's tools bundle: the node-uplink seat's verbs (novox/hq ADR 0241), served by the node's
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own. stdout is
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own, and gives the
|
||||
// holder's own subcommands, tools and the work its bundle starts beside them (design 08 sign-in-page §11). stdout is
|
||||
// the MCP channel; this says nothing else.
|
||||
package main
|
||||
|
||||
@@ -11,8 +12,16 @@ import (
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func tools(m Machine) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
// holderOwn is what a holder adds to the seat's verbs, from its manager.go: its subcommands (a process of the module
|
||||
// runs one, as `uplink-tools <name>`), its own tools and the work its bundle starts once it serves.
|
||||
type holderOwn struct {
|
||||
Commands map[string]func(args []string) error
|
||||
Tools []stdio.Tool
|
||||
Start func()
|
||||
}
|
||||
|
||||
func tools(m Machine, own holderOwn) []stdio.Tool {
|
||||
return append([]stdio.Tool{
|
||||
{Name: seat + ".resolvers",
|
||||
Description: "The machine's resolver file as it is now: the resolvers, search domains and options it lists, " +
|
||||
"whether it is the file the mesh declares, and when it is not, who wrote it as far as the machine shows " +
|
||||
@@ -23,12 +32,40 @@ func tools(m Machine) []stdio.Tool {
|
||||
"leaves through it, and the resolvers and search domains the network manager knows for it — a VPN's " +
|
||||
"tunnel included. (r)",
|
||||
Run: func(map[string]any) (any, error) { return m.Links(context.Background()) }},
|
||||
}, own.Tools...)
|
||||
}
|
||||
|
||||
// command is the holder's subcommand args name, or an error naming it when the holder has none such; nil with no args,
|
||||
// which is the bundle.
|
||||
func command(own holderOwn, args []string) (func(args []string) error, error) {
|
||||
if len(args) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if run, ok := own.Commands[args[0]]; ok {
|
||||
return run, nil
|
||||
}
|
||||
return nil, fmt.Errorf("uplink-tools has no subcommand %q", args[0])
|
||||
}
|
||||
|
||||
func main() {
|
||||
m := Machine{ResolvPath: ResolvConf, Run: execRunner, Running: running, LinkDNS: managerDNS}
|
||||
if err := stdio.Serve("", tools(m)); err != nil {
|
||||
own := holder(m)
|
||||
run, err := command(own, os.Args[1:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if run != nil {
|
||||
if err := run(os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if own.Start != nil {
|
||||
go own.Start()
|
||||
}
|
||||
if err := stdio.Serve("", tools(m, own)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -65,3 +65,7 @@ func parseNetworkctl(out string) map[string]LinkDNS {
|
||||
flush()
|
||||
return links
|
||||
}
|
||||
|
||||
// holder is what systemd-networkd adds to the seat's verbs: nothing, for it cannot tell a sign-in page (design 08
|
||||
// sign-in-page §11, §28).
|
||||
func holder(Machine) holderOwn { return holderOwn{} }
|
||||
|
||||
@@ -27,3 +27,16 @@ func TestNetworkctlIsReadPerLink(t *testing.T) {
|
||||
t.Fatalf("read %+v", links)
|
||||
}
|
||||
}
|
||||
|
||||
// systemd-networkd serves the seat's two verbs and nothing of its own: no subcommand, no tool, no work at its start
|
||||
// (design 08 sign-in-page §11, §28).
|
||||
func TestNetworkdServesTheSeatsVerbsAlone(t *testing.T) {
|
||||
own := holder(Machine{})
|
||||
if len(own.Commands) != 0 || len(own.Tools) != 0 || own.Start != nil {
|
||||
t.Fatalf("systemd-networkd adds %+v", own)
|
||||
}
|
||||
served := tools(Machine{}, own)
|
||||
if len(served) != 2 || served[0].Name != "node-uplink.resolvers" || served[1].Name != "node-uplink.links" {
|
||||
t.Fatalf("served %v", served)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The node-uplink seat's verbs (novox/hq ADR 0241), every holder's: the resolver file as it is, the mesh's
|
||||
@@ -148,3 +150,30 @@ func TestTheLinksCarryTheirDefaultRouteAndTheirNames(t *testing.T) {
|
||||
t.Fatalf("a manager that does not answer is not said: %+v", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// main.go serves the seat's two verbs first and the holder's own tools after them, and runs a subcommand only when
|
||||
// the holder's manager.go gives it (design 08 sign-in-page §11).
|
||||
func TestTheHoldersOwnPartComesBesideTheSeatsVerbs(t *testing.T) {
|
||||
ran := ""
|
||||
own := holderOwn{
|
||||
Commands: map[string]func([]string) error{"watch": func(args []string) error { ran = strings.Join(args, " "); return nil }},
|
||||
Tools: []stdio.Tool{{Name: "own_tool"}},
|
||||
}
|
||||
var names []string
|
||||
for _, tool := range tools(Machine{}, own) {
|
||||
names = append(names, tool.Name)
|
||||
}
|
||||
if strings.Join(names, " ") != "node-uplink.resolvers node-uplink.links own_tool" {
|
||||
t.Fatalf("served %v", names)
|
||||
}
|
||||
if run, err := command(own, nil); run != nil || err != nil {
|
||||
t.Fatalf("no arguments is the bundle, got a subcommand or %v", err)
|
||||
}
|
||||
if _, err := command(own, []string{"nothing"}); err == nil || !strings.Contains(err.Error(), `"nothing"`) {
|
||||
t.Fatalf("a subcommand the holder has not was taken: %v", err)
|
||||
}
|
||||
run, err := command(own, []string{"watch", "a"})
|
||||
if err != nil || run([]string{"a"}) != nil || ran != "a" {
|
||||
t.Fatalf("the holder's subcommand did not run: %v %q", err, ran)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user