feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
This commit is contained in:
@@ -0,0 +1,273 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// All commands are explicitly requested, runtime-bound and processed once.
|
||||
// The result cache outlives the maximum admission deadline; a Node restart
|
||||
// invalidates every previous runtime. No network write is retried automatically.
|
||||
type verification struct {
|
||||
command Command
|
||||
started time.Time
|
||||
until time.Time
|
||||
uptime *float64
|
||||
manualMode string
|
||||
}
|
||||
|
||||
func validCommand(c Command) bool {
|
||||
if c.Action == "" {
|
||||
return c.Mode == "" && len(c.Slots) == 0 && len(c.Username) > 0 && len(c.Username) <= 64 && len(c.Password) > 0 && len(c.Password) <= 256
|
||||
}
|
||||
if c.Username != "" || c.Password != "" {
|
||||
return false
|
||||
}
|
||||
if c.Action == "reboot" {
|
||||
return c.Mode == "" && len(c.Slots) == 0
|
||||
}
|
||||
if c.Action != "mode" || (c.Mode != "direct" && c.Mode != "aggregation") || len(c.Slots) < 1 || len(c.Slots) > 3 || (c.Mode == "direct" && len(c.Slots) != 1) {
|
||||
return false
|
||||
}
|
||||
seen := map[int]bool{}
|
||||
for _, slot := range c.Slots {
|
||||
if slot < 1 || slot > 3 || seen[slot] {
|
||||
return false
|
||||
}
|
||||
seen[slot] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var deviceName = regexp.MustCompile(`^[a-zA-Z0-9_.:-]{1,32}$`)
|
||||
|
||||
func manualSlots(m map[string]any) []int {
|
||||
result := []int{}
|
||||
modems, _ := m["modems"].([]any)
|
||||
for _, raw := range modems {
|
||||
modem, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for slot := 1; slot <= 3; slot++ {
|
||||
if modem["slot"] != fmt.Sprintf("M%d", slot) {
|
||||
continue
|
||||
}
|
||||
selected := false
|
||||
switch m["mode"] {
|
||||
case "direct":
|
||||
selected = modem["wan"] == m["wan"] && m["wan"] == fmt.Sprintf("wan%d", slot)
|
||||
case "glue":
|
||||
selected = slices.Contains(strings.Split(text(m["allow"]), ","), text(modem["dev"])) && text(modem["dev"]) != ""
|
||||
case "auto":
|
||||
selected = modem["up"] == true
|
||||
}
|
||||
if selected && !slices.Contains(result, slot) {
|
||||
result = append(result, slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// Resolve public slot numbers against the current vendor response. Never accept
|
||||
// raw device names, endpoint paths or form fields supplied by an operator.
|
||||
func controlForm(cmd Command, manual map[string]any) (url.Values, string, error) {
|
||||
modems, ok := manual["modems"].([]any)
|
||||
if !ok || len(modems) > 3 || manual["ok"] != true {
|
||||
return nil, "", errProtocol
|
||||
}
|
||||
live := map[int]string{}
|
||||
for _, raw := range modems {
|
||||
m, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return nil, "", errProtocol
|
||||
}
|
||||
for slot := 1; slot <= 3; slot++ {
|
||||
if m["slot"] != fmt.Sprintf("M%d", slot) {
|
||||
continue
|
||||
}
|
||||
if m["up"] != true || net.ParseIP(text(m["ip"])) == nil {
|
||||
continue
|
||||
}
|
||||
dev := text(m["dev"])
|
||||
if m["wan"] != fmt.Sprintf("wan%d", slot) || !deviceName.MatchString(dev) || live[slot] != "" {
|
||||
return nil, "", errProtocol
|
||||
}
|
||||
live[slot] = dev
|
||||
}
|
||||
}
|
||||
selected := append([]int{}, cmd.Slots...)
|
||||
slices.Sort(selected)
|
||||
devices := []string{}
|
||||
for _, slot := range selected {
|
||||
if live[slot] == "" {
|
||||
return nil, "", errors.New("sim_unavailable")
|
||||
}
|
||||
devices = append(devices, live[slot])
|
||||
}
|
||||
if cmd.Mode == "direct" {
|
||||
return url.Values{"mode": {"direct"}, "wan": {fmt.Sprintf("wan%d", selected[0])}}, "direct", nil
|
||||
}
|
||||
if len(selected) == len(live) {
|
||||
return url.Values{"mode": {"auto"}}, "auto", nil
|
||||
}
|
||||
return url.Values{"mode": {"glue"}, "allow": {strings.Join(devices, ",")}}, "glue", nil
|
||||
}
|
||||
|
||||
func (c *Collector) setControlResult(cmd Command, state, reason string) {
|
||||
c.mu.Lock()
|
||||
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, Error: reason}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Collector) applyControl(parent context.Context, cmd Command) {
|
||||
result := "router_unavailable"
|
||||
sent := false
|
||||
defer func() {
|
||||
if !sent {
|
||||
c.setControlResult(cmd, "error", result)
|
||||
}
|
||||
}()
|
||||
if time.Now().Unix() >= cmd.Deadline {
|
||||
result = "expired"
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithDeadline(parent, time.Unix(cmd.Deadline, 0))
|
||||
defer cancel()
|
||||
r, ok := c.state.Records[cmd.DeviceID]
|
||||
if !ok || r.Access == nil || r.Rejected || r.Device.State != "ready" {
|
||||
return
|
||||
}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if c.neighbor(candidate.Interface, candidate.Address) != r.MAC {
|
||||
continue
|
||||
}
|
||||
candidate.MAC = r.MAC
|
||||
a := c.client(candidate)
|
||||
if !a.family(ctx) {
|
||||
return
|
||||
}
|
||||
if err := a.login(ctx, *r.Access); err != nil {
|
||||
result = "access_rejected"
|
||||
return
|
||||
}
|
||||
var uptime *float64
|
||||
form := url.Values{"confirm": {"1"}}
|
||||
path := "dexaflow_reboot"
|
||||
expected := ""
|
||||
if cmd.Action == "mode" {
|
||||
manual, err := a.json(ctx, "dexaflow_manual", nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
form, expected, err = controlForm(cmd, manual)
|
||||
if err != nil {
|
||||
if err.Error() == "sim_unavailable" {
|
||||
result = "sim_unavailable"
|
||||
} else {
|
||||
result = "unsupported_response"
|
||||
}
|
||||
return
|
||||
}
|
||||
path = "dexaflow_manual"
|
||||
} else {
|
||||
status, err := a.json(ctx, "dexaflow_status", nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
uptime = number(status["uptime"], 0, 1e12)
|
||||
if uptime == nil {
|
||||
result = "unsupported_response"
|
||||
return
|
||||
}
|
||||
}
|
||||
// Persist intent before issuing the write. A crash cannot silently erase
|
||||
// the attempted operation, and old runtimes cannot re-send it after boot.
|
||||
c.event(cmd.DeviceID, "command_requested", 0, cmd.Action, cmd.Mode)
|
||||
c.persist()
|
||||
if c.storageError {
|
||||
result = "storage_error"
|
||||
return
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
result = "expired"
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
data, writeErr := a.request(ctx, path, form) // Exactly ONE write, even on timeout.
|
||||
if writeErr == nil && cmd.Action == "mode" {
|
||||
var response map[string]any
|
||||
if json.Unmarshal(data, &response) == nil && response["ok"] == false {
|
||||
result = "command_rejected"
|
||||
switch response["error"] {
|
||||
case "busy":
|
||||
result = "router_busy"
|
||||
case "need_modem", "no_ip":
|
||||
result = "sim_unavailable"
|
||||
}
|
||||
c.event(cmd.DeviceID, "command_failed", 0, cmd.Action, result)
|
||||
c.persist()
|
||||
return
|
||||
}
|
||||
}
|
||||
if errors.Is(writeErr, errAccess) {
|
||||
result = "access_rejected"
|
||||
return
|
||||
}
|
||||
sent = true
|
||||
c.control = &verification{command: cmd, started: start, until: start.Add(180 * time.Second), uptime: uptime, manualMode: expected}
|
||||
c.clients[cmd.DeviceID] = a
|
||||
c.setControlResult(cmd, "applying", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func confirms(v *verification, d Device, now time.Time) bool {
|
||||
if d.State != "ready" || d.ObservedAt <= v.started.Unix() {
|
||||
return false
|
||||
}
|
||||
if v.command.Action == "reboot" {
|
||||
// Uptime measures the router, not the Node. Missing samples and a reachable
|
||||
// login page alone never count as a successful reboot.
|
||||
return v.uptime != nil && d.Uptime != nil && *d.Uptime+15 < *v.uptime+now.Sub(v.started).Seconds()
|
||||
}
|
||||
if d.ManualMode != v.manualMode {
|
||||
return false
|
||||
}
|
||||
want := append([]int{}, v.command.Slots...)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(d.ActiveSlots, want) {
|
||||
return false
|
||||
}
|
||||
if v.command.Mode == "direct" {
|
||||
return d.ActiveMode == "direct" && d.ActiveWAN == fmt.Sprintf("wan%d", want[0])
|
||||
}
|
||||
return d.ActiveMode == "aggregation"
|
||||
}
|
||||
|
||||
func (c *Collector) verifyControl() {
|
||||
v := c.control
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if r, ok := c.state.Records[v.command.DeviceID]; ok && confirms(v, r.Device, now) {
|
||||
c.setControlResult(v.command, "complete", "")
|
||||
c.event(v.command.DeviceID, "command_complete", 0, v.command.Action, v.command.Mode)
|
||||
c.control = nil
|
||||
} else if !now.Before(v.until) {
|
||||
c.setControlResult(v.command, "unknown", "confirmation_timeout")
|
||||
c.event(v.command.DeviceID, "command_unconfirmed", 0, v.command.Action, v.command.Mode)
|
||||
c.control = nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user