Files
mesh-catalog/modules/networkmanager/cmd/uplink-tools/watch.go
T
jochen 349ef43a36 networkmanager: a watcher refused at its start by a bus that is there exits
When the first subscribe fails while the system bus's socket is already there, no file
event will make it again: the watcher writes the reason to its journal and exits
non-zero, so its unit shows failing instead of staying active and deaf.

Builds: design 08 sign-in-page §14; lead answer C2-1 (hq f15bc2fd)
2026-11-25 01:12:23 +01:00

474 lines
14 KiB
Go

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)
}