local.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // local.go — prober local del agente: ejecuta EN EL ROUTER los mismos
  2. // comandos que el servidor lanza por SSH (constantes Cmd* de probe.go) y
  3. // construye el Payload con los shapes parseados. Cada sonda es best-effort:
  4. // si un comando no existe (ubus, iwinfo, brctl...) la sección queda ausente
  5. // y el servidor conserva el último dato bueno (anti-parpadeo).
  6. package probe
  7. import (
  8. "context"
  9. "encoding/json"
  10. "fmt"
  11. "os/exec"
  12. "strings"
  13. "time"
  14. )
  15. // Runner ejecuta un comando de shell local y devuelve su stdout.
  16. // timeout 0 = default corto de sonda.
  17. type Runner interface {
  18. Run(ctx context.Context, cmd string, timeout time.Duration) (string, error)
  19. }
  20. // ShellRunner ejecuta con /bin/sh -c (BusyBox ash en OpenWrt).
  21. type ShellRunner struct {
  22. DefaultTimeout time.Duration
  23. }
  24. // Run implementa Runner.
  25. func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) {
  26. if timeout <= 0 {
  27. timeout = s.DefaultTimeout
  28. if timeout <= 0 {
  29. timeout = 5 * time.Second
  30. }
  31. }
  32. cctx, cancel := context.WithTimeout(ctx, timeout)
  33. defer cancel()
  34. out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output()
  35. if err != nil {
  36. return "", err
  37. }
  38. return string(out), nil
  39. }
  40. // Options configura las sondas opcionales del prober.
  41. type Options struct {
  42. // WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway.
  43. WanPingTarget string
  44. // GwPingTarget: si no está vacío, ping corto al gateway (latencia) — AP.
  45. GwPingTarget string
  46. }
  47. // Prober sondea el equipo local y construye payloads. Mantiene el estado de
  48. // deltas (/proc/stat y /proc/net/dev) entre muestras — es el único estado
  49. // del agente y vive solo en RAM.
  50. type Prober struct {
  51. run Runner
  52. opts Options
  53. lastStat *CPUSample
  54. lastNetRx float64
  55. lastNetTx float64
  56. lastNetAt time.Time
  57. hasLastNet bool
  58. }
  59. // NewProber crea el prober con el runner dado.
  60. func NewProber(run Runner, opts Options) *Prober {
  61. return &Prober{run: run, opts: opts}
  62. }
  63. // runBest es best-effort: error → "" (la sección queda ausente).
  64. func (p *Prober) runBest(ctx context.Context, cmd string, timeout time.Duration) string {
  65. out, err := p.run.Run(ctx, cmd, timeout)
  66. if err != nil {
  67. return ""
  68. }
  69. return out
  70. }
  71. // Build ejecuta una ronda de sondas y devuelve el payload listo para empujar.
  72. // router/version los rellena el caller (main) o van aquí por comodidad.
  73. func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
  74. pl := &Payload{
  75. Router: router,
  76. Ts: time.Now().Unix(),
  77. Version: version,
  78. }
  79. pl.Data.System = p.probeSystem(ctx)
  80. pl.Data.Wireless = p.probeWireless(ctx)
  81. pl.Data.DHCP = p.probeDHCP(ctx)
  82. pl.Data.FDB = p.probeFDB(ctx)
  83. return pl
  84. }
  85. // BuildWireless es un sondeo rápido de solo wireless + DHCP (Fase 7.1:
  86. // disparado por eventos ubus assoc/disassoc). El servidor conserva el último
  87. // dato bueno de system y FDB (parpadeo suprimido por secciones nil).
  88. func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Payload {
  89. pl := &Payload{
  90. Router: router,
  91. Ts: time.Now().Unix(),
  92. Version: version,
  93. }
  94. pl.Data.Wireless = p.probeWireless(ctx)
  95. pl.Data.DHCP = p.probeDHCP(ctx)
  96. return pl
  97. }
  98. // probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC
  99. // del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin
  100. // ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests).
  101. func (p *Prober) probeSystem(ctx context.Context) *SystemData {
  102. sd := &SystemData{}
  103. any := false
  104. if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" {
  105. var si SysInfo
  106. if err := json.Unmarshal([]byte(out), &si); err == nil {
  107. sd.SysInfo = &si
  108. any = true
  109. }
  110. }
  111. if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" {
  112. var b BoardInfo
  113. if err := json.Unmarshal([]byte(out), &b); err == nil {
  114. sd.Board = &b
  115. any = true
  116. }
  117. }
  118. if out := p.runBest(ctx, CmdProcStat, 0); out != "" {
  119. if cur, err := ParseProcStat(out); err == nil {
  120. if p.lastStat != nil {
  121. sd.CPU = CPUPercent(*p.lastStat, cur)
  122. }
  123. c := cur
  124. p.lastStat = &c
  125. any = true
  126. }
  127. }
  128. if out := p.runBest(ctx, CmdTemp, 0); out != "" {
  129. sd.Temp = ParseTempC(out)
  130. any = true
  131. }
  132. if out := p.runBest(ctx, CmdNetDev, 0); out != "" {
  133. rx, tx := ParseNetDev(out)
  134. now := time.Now()
  135. if p.hasLastNet {
  136. sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds())
  137. }
  138. p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true
  139. any = true
  140. }
  141. if p.opts.WanPingTarget != "" {
  142. out := p.runBest(ctx, fmt.Sprintf(CmdPingWan, p.opts.WanPingTarget), 10*time.Second)
  143. sd.LatencyMs, sd.LossPct = ParsePingSummary(out)
  144. any = true
  145. } else if p.opts.GwPingTarget != "" {
  146. out := p.runBest(ctx, fmt.Sprintf(CmdPingGateway, p.opts.GwPingTarget), 10*time.Second)
  147. sd.LatencyMs, _ = ParsePingSummary(out)
  148. any = true
  149. }
  150. if out := p.runBest(ctx, CmdUbusWireless, 0); out != "" {
  151. if wifi, err := ParseWirelessUplink([]byte(out)); err == nil {
  152. sd.Backhaul = "cable"
  153. if wifi {
  154. sd.Backhaul = "wifi"
  155. }
  156. any = true
  157. }
  158. }
  159. if out := p.runBest(ctx, CmdBridgeMAC, 0); out != "" {
  160. sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out))
  161. any = true
  162. }
  163. if !any {
  164. return nil
  165. }
  166. return sd
  167. }
  168. // probeWireless: clientes asociados (iwinfo assoclist) + radios por banda.
  169. // nil si iwinfo no existe en el equipo.
  170. func (p *Prober) probeWireless(ctx context.Context) *WirelessData {
  171. wd := &WirelessData{}
  172. any := false
  173. if out := p.runBest(ctx, CmdIwinfoAssoc, 8*time.Second); out != "" {
  174. wd.Clients = ParseWirelessClients(out)
  175. any = true
  176. }
  177. if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" {
  178. wd.Radios = ParseRadios(out)
  179. any = true
  180. }
  181. if !any {
  182. return nil
  183. }
  184. if wd.Clients == nil {
  185. wd.Clients = map[string]WirelessClient{}
  186. }
  187. if wd.Radios == nil {
  188. wd.Radios = []Radio{}
  189. }
  190. return wd
  191. }
  192. // probeDHCP: ubus dhcp ipv4leases con fallback a /tmp/dhcp.leases, más
  193. // gl-clients (GL.iNet) como superset para resolver IPs sin lease
  194. // (issue #5 bug 1 — el gateway Flint2 llega por esta ruta de agente).
  195. func (p *Prober) probeDHCP(ctx context.Context) *DHCPData {
  196. var dd *DHCPData
  197. if out := p.runBest(ctx, CmdDhcpUbus, 0); out != "" {
  198. if leases, err := ParseDhcpUbus([]byte(out)); err == nil {
  199. dd = &DHCPData{Leases: leases}
  200. }
  201. }
  202. if dd == nil {
  203. out := p.runBest(ctx, CmdDhcpFile, 0)
  204. if out == "" {
  205. return nil
  206. }
  207. dd = &DHCPData{Leases: ParseDhcpLeasesFile(out)}
  208. }
  209. if out := p.runBest(ctx, CmdGlClients, 0); out != "" {
  210. if gl, err := ParseGlClients([]byte(out)); err == nil {
  211. dd.GlClients = gl
  212. }
  213. }
  214. return dd
  215. }
  216. // probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys).
  217. func (p *Prober) probeFDB(ctx context.Context) *FDBData {
  218. fd := &FDBData{}
  219. any := false
  220. if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
  221. fd.MACs = ParseBridgeFdb(out)
  222. any = true
  223. }
  224. statesOut := p.runBest(ctx, CmdPortStates, 0)
  225. if statesOut != "" {
  226. states := ParsePortStates(statesOut)
  227. layout := []PortLayout{}
  228. if out := p.runBest(ctx, CmdBoardJSON, 0); out != "" {
  229. if lay, err := ParsePortLayout(out); err == nil {
  230. layout = lay
  231. }
  232. }
  233. members := map[string]bool{}
  234. if out := p.runBest(ctx, CmdBrifMembers, 0); out != "" {
  235. for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
  236. if l != "" {
  237. members[l] = true
  238. }
  239. }
  240. }
  241. fd.Ports = BuildEthPorts(layout, states, members)
  242. any = true
  243. }
  244. if !any {
  245. return nil
  246. }
  247. if fd.MACs == nil {
  248. fd.MACs = map[string]string{}
  249. }
  250. if fd.Ports == nil {
  251. fd.Ports = []EthPort{}
  252. }
  253. return fd
  254. }