Files
mesh-catalog/modules/networkmanager/cmd/uplink-tools/state.go
T
jochen 42b5a7aef3 networkmanager: the watcher socket's bound is a stated constant
Builds: design 08 sign-in-page §12; lead answer C-8 (hq df22a138)
2026-11-24 21:50:00 +01:00

330 lines
9.7 KiB
Go

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