client_discovery_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // client_discovery_test.go — Regla de descubrimiento de clientes por red
  2. // lógica de OpenWrt (y respaldo por dispositivo Linux) en el servidor: modo
  3. // automático, overrides explícitos ("on" / "off"), resolución cuando varias
  4. // redes comparten dispositivo, interacción con WanSide (#1485) en el gateway y
  5. // construcción de RouterDetail.Discovery.
  6. package adapters
  7. import (
  8. "context"
  9. "reflect"
  10. "testing"
  11. "time"
  12. "github.com/gnacho/netpulse/agent/probe"
  13. "github.com/gnacho/netpulse/server-go/internal/db"
  14. )
  15. func boolPtr(b bool) *bool { return &b }
  16. func travelNetIfaces() []probe.NetIface {
  17. return []probe.NetIface{
  18. {Name: "lan", Proto: "static", Up: true, Devices: []string{"br-lan"}},
  19. {Name: "wan", Proto: "dhcp", Up: false, Devices: []string{"eth0.2"}},
  20. {Name: "wan6", Proto: "dhcpv6", Up: false, Devices: []string{"eth0.2"}},
  21. {Name: "wg0", Proto: "wireguard", Up: true, Devices: []string{"wg0"}},
  22. {Name: "wwan", Proto: "dhcp", Up: true, Devices: []string{"phy1-sta0"}},
  23. }
  24. }
  25. func travelPolled(ov DiscoveryOverrides) *routerPolled {
  26. return &routerPolled{
  27. cfg: RouterConfig{
  28. ID: "travel",
  29. Name: "travel",
  30. Host: "192.168.2.1",
  31. DiscoveryOverrides: ov,
  32. },
  33. wanInfo: probe.WanInfo{Device: "phy1-sta0", Port: "phy1-sta0"},
  34. uplinkDevs: []string{"phy1-sta0"},
  35. netIfaces: travelNetIfaces(),
  36. arp: map[string]string{
  37. "AA:BB:CC:00:00:01": "10.20.0.177", // vecino en wwan (uplink)
  38. "AA:BB:CC:00:00:02": "192.168.2.50", // vecino en lan
  39. },
  40. arpDevs: map[string]string{
  41. "AA:BB:CC:00:00:01": "phy1-sta0",
  42. "AA:BB:CC:00:00:02": "br-lan",
  43. },
  44. }
  45. }
  46. // En un router de viaje, buildDiscoveryIfaces emite una fila por cada red en
  47. // orden del dump (sin filas device cuando todos los dispositivos pertenecen a
  48. // una red), con Auto=false solo en wwan y el conteo de vecinos confirmados
  49. // correcto.
  50. func TestClientDiscoveryTravelRouterNetworkRows(t *testing.T) {
  51. p := travelPolled(DiscoveryOverrides{})
  52. p.arp["AA:BB:CC:00:00:03"] = "10.20.0.178"
  53. p.arpDevs["AA:BB:CC:00:00:03"] = "phy1-sta0"
  54. p.arpStale = map[string]bool{"AA:BB:CC:00:00:03": true} // stale no suma
  55. got := buildDiscoveryIfaces(p)
  56. want := []DiscoveryIface{
  57. {Kind: "network", Name: "lan", Devices: []string{"br-lan"}, Up: boolPtr(true), Mode: "auto", Auto: true, Effective: true, Neighbours: 1},
  58. {Kind: "network", Name: "wan", Devices: []string{"eth0.2"}, Up: boolPtr(false), Mode: "auto", Auto: true, Effective: true, Neighbours: 0},
  59. {Kind: "network", Name: "wan6", Devices: []string{"eth0.2"}, Up: boolPtr(false), Mode: "auto", Auto: true, Effective: true, Neighbours: 0},
  60. {Kind: "network", Name: "wg0", Devices: []string{"wg0"}, Up: boolPtr(true), Mode: "auto", Auto: true, Effective: true, Neighbours: 0},
  61. {Kind: "network", Name: "wwan", Devices: []string{"phy1-sta0"}, Up: boolPtr(true), Mode: "auto", Auto: false, Effective: false, Neighbours: 1},
  62. }
  63. if !reflect.DeepEqual(got, want) {
  64. t.Fatalf("filas de descubrimiento del router de viaje:\ngot %+v\nwant %+v", got, want)
  65. }
  66. // En automático solo cuenta el vecino de br-lan, no el de phy1-sta0.
  67. l := NewLive(nil, nil, nil, nil)
  68. devs := l.buildDevices(map[string]*routerPolled{"travel": p}, "")
  69. if len(devs) != 1 || devs[0].MAC != "AA:BB:CC:00:00:02" {
  70. t.Fatalf("en automático solo debe contar el vecino de lan: %+v", devs)
  71. }
  72. }
  73. // Un vecino en un dispositivo que no pertenece a ninguna red (p. ej. eth3)
  74. // aparece como fila device y cuenta como cliente en automático.
  75. func TestClientDiscoveryUnassignedDeviceRow(t *testing.T) {
  76. p := travelPolled(DiscoveryOverrides{})
  77. p.arp["AA:BB:CC:00:00:09"] = "192.168.9.10"
  78. p.arpDevs["AA:BB:CC:00:00:09"] = "eth3"
  79. rows := buildDiscoveryIfaces(p)
  80. if len(rows) != 6 {
  81. t.Fatalf("esperaba 5 redes + 1 fila device, obtuve %d: %+v", len(rows), rows)
  82. }
  83. wantDev := DiscoveryIface{Kind: "device", Name: "eth3", Mode: "auto", Auto: true, Effective: true, Neighbours: 1}
  84. if !reflect.DeepEqual(rows[5], wantDev) {
  85. t.Fatalf("fila device de respaldo:\ngot %+v\nwant %+v", rows[5], wantDev)
  86. }
  87. l := NewLive(nil, nil, nil, nil)
  88. devs := l.buildDevices(map[string]*routerPolled{"travel": p}, "")
  89. gotMACs := map[string]bool{}
  90. for _, d := range devs {
  91. gotMACs[d.MAC] = true
  92. }
  93. if !gotMACs["AA:BB:CC:00:00:02"] || !gotMACs["AA:BB:CC:00:00:09"] || gotMACs["AA:BB:CC:00:00:01"] {
  94. t.Fatalf("esperaba clientes en br-lan y eth3 (sin phy1-sta0): %+v", devs)
  95. }
  96. }
  97. // Con Networks["wwan"]="on", los vecinos del uplink pasan a contar como clientes.
  98. func TestClientDiscoveryNetworkOverrideOnWwan(t *testing.T) {
  99. p := travelPolled(DiscoveryOverrides{
  100. Networks: map[string]DiscoveryMode{"wwan": "on"},
  101. })
  102. l := NewLive(nil, nil, nil, nil)
  103. devs := l.buildDevices(map[string]*routerPolled{"travel": p}, "")
  104. if len(devs) != 2 {
  105. t.Fatalf("con wwan='on' deben contar ambos vecinos (lan y wwan): %+v", devs)
  106. }
  107. }
  108. // Con Networks["lan"]="off", los vecinos de br-lan se descartan.
  109. func TestClientDiscoveryNetworkOverrideOffLan(t *testing.T) {
  110. p := travelPolled(DiscoveryOverrides{
  111. Networks: map[string]DiscoveryMode{"lan": "off"},
  112. })
  113. l := NewLive(nil, nil, nil, nil)
  114. if devs := l.buildDevices(map[string]*routerPolled{"travel": p}, ""); len(devs) != 0 {
  115. t.Fatalf("con lan='off' y wwan en automático no debe haber clientes: %+v", devs)
  116. }
  117. }
  118. // Dos redes que comparten dispositivo (wan y wan6 sobre eth0.2) cuando eth0.2
  119. // es el uplink: ambas tienen Auto=false; explícito vence a automático; entre
  120. // explícitos, "off" vence a "on".
  121. func TestClientDiscoverySharedDeviceResolution(t *testing.T) {
  122. makePolled := func(nets map[string]DiscoveryMode) *routerPolled {
  123. return &routerPolled{
  124. cfg: RouterConfig{
  125. ID: "rt",
  126. Name: "rt",
  127. Host: "192.168.1.1",
  128. DiscoveryOverrides: DiscoveryOverrides{Networks: nets},
  129. },
  130. wanInfo: probe.WanInfo{Device: "eth0.2"},
  131. netIfaces: travelNetIfaces(),
  132. arp: map[string]string{"AA:BB:CC:00:00:55": "198.51.100.1"},
  133. arpDevs: map[string]string{"AA:BB:CC:00:00:55": "eth0.2"},
  134. }
  135. }
  136. t.Run("automatico desactiva wan y wan6", func(t *testing.T) {
  137. p := makePolled(nil)
  138. rows := buildDiscoveryIfaces(p)
  139. for _, r := range rows {
  140. if r.Name == "wan" || r.Name == "wan6" {
  141. if r.Auto || r.Effective || r.Neighbours != 1 {
  142. t.Fatalf("fila %s esperaba Auto=false Effective=false Neighbours=1: %+v", r.Name, r)
  143. }
  144. }
  145. }
  146. if resolveDiscovery(p, "eth0.2", nil).allowed() {
  147. t.Fatal("eth0.2 debía quedar bloqueado en automático")
  148. }
  149. })
  150. t.Run("wan on con wan6 en automatico permite el dispositivo", func(t *testing.T) {
  151. p := makePolled(map[string]DiscoveryMode{"wan": "on"})
  152. if !resolveDiscovery(p, "eth0.2", nil).allowed() {
  153. t.Fatal("wan='on' + wan6='auto' debía permitir eth0.2 (explícito vence a automático)")
  154. }
  155. if !discoveryExplicitOn(p, "eth0.2") {
  156. t.Fatal("wan='on' + wan6='auto' debía considerarse explicitOn")
  157. }
  158. })
  159. t.Run("wan on con wan6 off bloquea el dispositivo", func(t *testing.T) {
  160. p := makePolled(map[string]DiscoveryMode{"wan": "on", "wan6": "off"})
  161. if resolveDiscovery(p, "eth0.2", nil).allowed() {
  162. t.Fatal("wan='on' + wan6='off' debía bloquear eth0.2 ('off' vence a 'on')")
  163. }
  164. if discoveryExplicitOn(p, "eth0.2") {
  165. t.Fatal("wan='on' + wan6='off' no debe ser explicitOn")
  166. }
  167. })
  168. // El orden de las redes no importa: un Off en la primera corta el bucle y
  169. // el On de la segunda no lo deshace.
  170. t.Run("wan off con wan6 on bloquea el dispositivo", func(t *testing.T) {
  171. p := makePolled(map[string]DiscoveryMode{"wan": "off", "wan6": "on"})
  172. if resolveDiscovery(p, "eth0.2", nil).allowed() {
  173. t.Fatal("wan='off' + wan6='on' debía bloquear eth0.2 ('off' vence a 'on')")
  174. }
  175. if discoveryExplicitOn(p, "eth0.2") {
  176. t.Fatal("wan='off' + wan6='on' no debe ser explicitOn")
  177. }
  178. })
  179. }
  180. // En el gateway, el vecino de wanPort es WanSide por defecto (#1485) y solo
  181. // deja de marcarse WanSide cuando hay un override explícito "on" por red.
  182. func TestClientDiscoveryGatewayWanPortNetworkOverride(t *testing.T) {
  183. gwCfg := RouterConfig{ID: "gw", Name: "gw", Host: "192.168.1.1", IsGateway: true}
  184. l := NewLive(nil, nil, []RouterConfig{gwCfg}, nil)
  185. ifaces := []probe.NetIface{
  186. {Name: "lan", Proto: "static", Up: true, Devices: []string{"br-lan"}},
  187. {Name: "wan", Proto: "dhcp", Up: true, Devices: []string{"eth0.2"}},
  188. {Name: "wan6", Proto: "dhcpv6", Up: true, Devices: []string{"eth0.2"}},
  189. }
  190. makeGW := func(cfg RouterConfig) map[string]*routerPolled {
  191. return map[string]*routerPolled{
  192. "gw": {
  193. cfg: cfg,
  194. wanInfo: probe.WanInfo{Device: "eth0.2", Port: "eth0.2"},
  195. netIfaces: ifaces,
  196. arp: map[string]string{"AA:BB:CC:00:00:99": "192.168.100.1"},
  197. arpDevs: map[string]string{"AA:BB:CC:00:00:99": "eth0.2"},
  198. },
  199. }
  200. }
  201. // Sin override: sigue siendo WanSide.
  202. devs := l.buildDevices(makeGW(gwCfg), "eth0.2")
  203. if len(devs) != 1 || !devs[0].WanSide {
  204. t.Fatalf("sin override el vecino de wanPort debe seguir siendo WanSide: %+v", devs)
  205. }
  206. // Con Networks["wan"]="on": deja de ser WanSide y entra como cliente normal.
  207. gwOn := gwCfg
  208. gwOn.DiscoveryOverrides = DiscoveryOverrides{Networks: map[string]DiscoveryMode{"wan": "on"}}
  209. l.SetRouters([]RouterConfig{gwOn})
  210. devs = l.buildDevices(makeGW(gwOn), "eth0.2")
  211. if len(devs) != 1 || devs[0].WanSide {
  212. t.Fatalf("con Networks['wan']='on' el vecino debe ser cliente y no WanSide: %+v", devs)
  213. }
  214. // Con wan="on" y wan6="off": off vence a on, así que no es explicitOn -> WanSide.
  215. gwConflict := gwCfg
  216. gwConflict.DiscoveryOverrides = DiscoveryOverrides{Networks: map[string]DiscoveryMode{"wan": "on", "wan6": "off"}}
  217. l.SetRouters([]RouterConfig{gwConflict})
  218. devs = l.buildDevices(makeGW(gwConflict), "eth0.2")
  219. if len(devs) != 1 || !devs[0].WanSide {
  220. t.Fatalf("con wan='on' y wan6='off' debe seguir siendo WanSide: %+v", devs)
  221. }
  222. }
  223. // En el gateway con IP de puerta de enlace WAN (#2183/#1791): sin override no
  224. // entra ni el peer de la ruta por defecto (#1791) ni el vecino del segmento
  225. // (wanIgnored, #2188). Con Networks["wan"]="on", el vecino confirmado pasa a
  226. // ser un cliente normal (WanSide=false), pero el peer sigue absorbido por #1791.
  227. func TestClientDiscoveryGatewayWanPortWithGatewayIP(t *testing.T) {
  228. const (
  229. peer = "0C:EF:15:00:00:01"
  230. neighbour = "0C:EF:15:00:00:02"
  231. )
  232. gwCfg := RouterConfig{ID: "gw", Name: "gw", Host: "192.168.1.1", IsGateway: true}
  233. l := NewLive(nil, nil, []RouterConfig{gwCfg}, nil)
  234. ifaces := []probe.NetIface{
  235. {Name: "lan", Proto: "static", Up: true, Devices: []string{"br-lan"}},
  236. {Name: "wan", Proto: "dhcp", Up: true, Devices: []string{"eth0.2"}},
  237. {Name: "wan6", Proto: "dhcpv6", Up: true, Devices: []string{"eth0.2"}},
  238. }
  239. makeGW := func(cfg RouterConfig) map[string]*routerPolled {
  240. return map[string]*routerPolled{
  241. "gw": {
  242. cfg: cfg,
  243. wanInfo: probe.WanInfo{Device: "eth0.2", Port: "eth0.2", Gateway: "203.0.113.1"},
  244. netIfaces: ifaces,
  245. arp: map[string]string{
  246. peer: "203.0.113.1",
  247. neighbour: "203.0.113.248",
  248. },
  249. arpDevs: map[string]string{
  250. peer: "eth0.2",
  251. neighbour: "eth0.2",
  252. },
  253. },
  254. }
  255. }
  256. // Sin override: el peer cae en #1791 y el vecino en wanIgnored (#2188).
  257. if devs := l.buildDevices(makeGW(gwCfg), "eth0.2"); len(devs) != 0 {
  258. t.Fatalf("sin override no debe salir ni el peer ni el vecino del segmento WAN: %+v", devs)
  259. }
  260. // Con Networks["wan"]="on": el vecino confirmado entra como cliente normal,
  261. // pero el peer de la ruta por defecto sigue descartado por #1791.
  262. gwOn := gwCfg
  263. gwOn.DiscoveryOverrides = DiscoveryOverrides{Networks: map[string]DiscoveryMode{"wan": "on"}}
  264. l.SetRouters([]RouterConfig{gwOn})
  265. devs := l.buildDevices(makeGW(gwOn), "eth0.2")
  266. if len(devs) != 1 || devs[0].MAC != neighbour || devs[0].WanSide {
  267. t.Fatalf("con Networks['wan']='on' solo debe entrar el vecino (%s) como cliente normal (WanSide=false): %+v", neighbour, devs)
  268. }
  269. }
  270. // Una MAC solo-IPv6 cuya interfaz (reportada en arpDevs tras el recheck NDP) es
  271. // el uplink de la unidad no se cuenta como cliente en modo automático.
  272. func TestClientDiscoveryIPv6OnlyOnWanSkippedInAuto(t *testing.T) {
  273. l := NewLive(nil, nil, nil, nil)
  274. polled := map[string]*routerPolled{
  275. "travel": {
  276. cfg: RouterConfig{ID: "travel", Name: "travel", Host: "192.168.2.1"},
  277. uplinkDevs: []string{"phy1-sta0"},
  278. arp: map[string]string{"BB:BB:BB:00:00:77": "fe80::1"},
  279. arpDevs: map[string]string{"BB:BB:BB:00:00:77": "phy1-sta0"},
  280. },
  281. }
  282. if devs := l.buildDevices(polled, ""); len(devs) != 0 {
  283. t.Fatalf("un vecino solo-IPv6 en el uplink no debe ser cliente en automático: %+v", devs)
  284. }
  285. }
  286. // Sin netIfaces (agente antiguo o equipo no-OpenWrt), RouterDetail.Discovery
  287. // produce exactamente las filas device de respaldo, ordenadas por nombre.
  288. func TestRouterDetailDiscoveryRowsOldAgent(t *testing.T) {
  289. cfg := RouterConfig{
  290. ID: "travel",
  291. Name: "travel",
  292. Host: "192.168.2.1",
  293. DiscoveryOverrides: DiscoveryOverrides{
  294. Devices: map[string]DiscoveryMode{
  295. "eth2": "off",
  296. "phy1-sta0": "on",
  297. },
  298. },
  299. }
  300. l := liveTestLive()
  301. l.SetRouters([]RouterConfig{
  302. {ID: "gw", Name: "gw", Host: "192.168.1.1", IsGateway: true},
  303. cfg,
  304. })
  305. // Unidad aún no sondeada -> Discovery es nil.
  306. detBefore, err := l.GetRouterDetail(context.Background(), "travel")
  307. if err != nil || detBefore == nil {
  308. t.Fatalf("GetRouterDetail sin sondeo: det=%+v err=%v", detBefore, err)
  309. }
  310. if detBefore.Discovery != nil {
  311. t.Fatalf("Discovery sin sondeo debe ser nil: %+v", detBefore.Discovery)
  312. }
  313. l.mu.Lock()
  314. l.lastPolled["travel"] = &routerPolled{
  315. cfg: cfg,
  316. uplinkDevs: []string{"phy1-sta0", "wan0"},
  317. arp: map[string]string{
  318. "AA:BB:CC:00:00:01": "192.168.2.10", // confirmada en br-lan
  319. "AA:BB:CC:00:00:02": "192.168.2.11", // confirmada en br-lan
  320. "AA:BB:CC:00:00:03": "192.168.2.12", // stale en br-lan (no cuenta)
  321. "AA:BB:CC:00:00:04": "10.20.0.1", // confirmada en phy1-sta0
  322. },
  323. arpStale: map[string]bool{
  324. "AA:BB:CC:00:00:03": true,
  325. },
  326. arpDevs: map[string]string{
  327. "AA:BB:CC:00:00:01": "br-lan",
  328. "AA:BB:CC:00:00:02": "br-lan",
  329. "AA:BB:CC:00:00:03": "br-lan",
  330. "AA:BB:CC:00:00:04": "phy1-sta0",
  331. },
  332. }
  333. l.mu.Unlock()
  334. det, err := l.GetRouterDetail(context.Background(), "travel")
  335. if err != nil || det == nil {
  336. t.Fatalf("GetRouterDetail: det=%+v err=%v", det, err)
  337. }
  338. want := []DiscoveryIface{
  339. {Kind: "device", Name: "br-lan", Mode: "auto", Auto: true, Effective: true, Neighbours: 2},
  340. {Kind: "device", Name: "eth2", Mode: "off", Auto: true, Effective: false, Neighbours: 0},
  341. {Kind: "device", Name: "phy1-sta0", Mode: "on", Auto: false, Effective: true, Neighbours: 1},
  342. {Kind: "device", Name: "wan0", Mode: "auto", Auto: false, Effective: false, Neighbours: 0},
  343. }
  344. if !reflect.DeepEqual(det.Discovery, want) {
  345. t.Fatalf("Discovery:\ngot %+v\nwant %+v", det.Discovery, want)
  346. }
  347. }
  348. // Un override guardado de una red que ahora no se reporta (un tether USB
  349. // desenchufado) sigue teniendo fila: si no, guardar otra fila desde el panel
  350. // lo borraría sin avisar.
  351. func TestBuildDiscoveryIfacesKeepsSavedMissingNetworkOverride(t *testing.T) {
  352. p := travelPolled(DiscoveryOverrides{
  353. Networks: map[string]DiscoveryMode{
  354. "wwan": DiscoveryOn,
  355. "usb0": DiscoveryOff, // red guardada, temporalmente ausente de netIfaces
  356. },
  357. })
  358. rows := buildDiscoveryIfaces(p)
  359. found := false
  360. for _, r := range rows {
  361. if r.Kind == DiscoveryKindNetwork && r.Name == "usb0" {
  362. found = true
  363. if r.Mode != DiscoveryOff || r.Effective {
  364. t.Fatalf("fila usb0 esperada mode=off effective=false, got %+v", r)
  365. }
  366. }
  367. }
  368. if !found {
  369. t.Fatalf("buildDiscoveryIfaces omitió el override guardado de la red ausente usb0: %+v", rows)
  370. }
  371. }
  372. // Las interfaces del uplink valen aunque la unidad no sea el gateway y no
  373. // traiga wanInfo (sondeo SSH de una unidad que no es gateway).
  374. func TestBuildDevicesSkipsArpOnUplinkDevs(t *testing.T) {
  375. l := NewLive(nil, nil, nil, nil)
  376. polled := map[string]*routerPolled{
  377. "travel": {
  378. cfg: RouterConfig{ID: "travel", Name: "travel", Host: "192.168.2.1"},
  379. uplinkDevs: []string{"phy1-sta0", "phy1-sta0"},
  380. arp: map[string]string{
  381. "AA:BB:CC:00:00:01": "10.20.0.177",
  382. "AA:BB:CC:00:00:02": "192.168.2.50",
  383. },
  384. arpDevs: map[string]string{
  385. "AA:BB:CC:00:00:01": "phy1-sta0",
  386. "AA:BB:CC:00:00:02": "br-lan",
  387. },
  388. },
  389. }
  390. devs := l.buildDevices(polled, "")
  391. if len(devs) != 1 || devs[0].MAC != "AA:BB:CC:00:00:02" {
  392. t.Fatalf("esperaba solo el vecino de la LAN, got %+v", devs)
  393. }
  394. }
  395. // Un push event-driven (solo wireless + ARP, sin sección WAN) conserva las
  396. // interfaces del uplink del último push completo: si no, sus vecinos salían
  397. // como clientes cableados en cada asociación Wi-Fi.
  398. func TestPolledFromAgentKeepsUplinkDevsOnEventPush(t *testing.T) {
  399. l := NewLive(nil, nil, []RouterConfig{{ID: "travel", Host: "192.0.2.3", Name: "travel", AgentOnly: true}}, nil)
  400. full := &probe.Payload{Router: "travel", Ts: 1, Version: "3.0.49",
  401. Data: probe.PayloadData{Wan: &probe.WanInfo{Proto: "dhcp", Device: "phy1-sta0", Port: "phy1-sta0"}}}
  402. _ = l.polledFromAgent(l.routers[0], full)
  403. event := &probe.Payload{Router: "travel", Ts: 2, Version: "3.0.49"}
  404. p := l.polledFromAgent(l.routers[0], event)
  405. if !arpUplinkDevs(p)["phy1-sta0"] {
  406. t.Fatalf("el push event-driven perdió el uplink: %+v", p.uplinkDevs)
  407. }
  408. if p.wanInfo.Proto != "" {
  409. t.Fatalf("wanInfo es dirección viva y no se recicla: %+v", p.wanInfo)
  410. }
  411. }
  412. // Un vecino de uplink descartado por descubrimiento no sale como fantasma
  413. // offline en GetOverview ni en GetDevices, pero conserva su fila previa en
  414. // device_seen.
  415. func TestDiscoverySkippedUplinkNeighbourNotGhost(t *testing.T) {
  416. const (
  417. uplinkMAC = "0C:EF:15:00:00:30"
  418. lanMAC = "AA:BB:CC:00:00:02"
  419. )
  420. d, err := db.Open(t.TempDir())
  421. if err != nil {
  422. t.Fatalf("db.Open: %v", err)
  423. }
  424. defer d.Close()
  425. for _, mac := range []string{uplinkMAC, lanMAC} {
  426. if _, err := d.Exec(`INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES (?, 1, 1, '')`, mac); err != nil {
  427. t.Fatalf("sembrar %s: %v", mac, err)
  428. }
  429. }
  430. routers := []RouterConfig{
  431. {ID: "gw", Name: "Gateway", Host: "127.0.0.1", SSHPort: 1, IsGateway: true, AgentOnly: true},
  432. {ID: "travel", Name: "Travel", Host: "192.168.2.1", SSHPort: 1, AgentOnly: true},
  433. }
  434. l, reg := newOverviewTestLive(t, d, routers)
  435. now := time.Now().Unix()
  436. reg.Ingest(&probe.Payload{
  437. Router: "gw",
  438. Ts: now,
  439. Version: "3.0.51",
  440. Data: probe.PayloadData{},
  441. })
  442. reg.Ingest(&probe.Payload{
  443. Router: "travel",
  444. Ts: now,
  445. Version: "3.0.51",
  446. Data: probe.PayloadData{
  447. Wan: &probe.WanInfo{Proto: "dhcp", Device: "phy1-sta0", Port: "phy1-sta0"},
  448. NetIfaces: travelNetIfaces(),
  449. Arp: map[string]string{
  450. uplinkMAC: "10.20.0.177",
  451. lanMAC: "192.168.2.50",
  452. },
  453. ArpDevs: map[string]string{
  454. uplinkMAC: "phy1-sta0",
  455. lanMAC: "br-lan",
  456. },
  457. },
  458. })
  459. ov, err := l.GetOverview(t.Context())
  460. if err != nil {
  461. t.Fatalf("GetOverview: %v", err)
  462. }
  463. check := func(where string, devs []Device) {
  464. t.Helper()
  465. foundLAN := false
  466. for _, dev := range devs {
  467. if dev.MAC == uplinkMAC {
  468. t.Errorf("%s: el vecino de uplink %s no debe aparecer como fantasma: %+v", where, dev.MAC, dev)
  469. }
  470. if dev.MAC == lanMAC {
  471. foundLAN = true
  472. }
  473. }
  474. if !foundLAN {
  475. t.Errorf("%s: cliente LAN %s ausente", where, lanMAC)
  476. }
  477. }
  478. check("GetOverview", ov.Devices)
  479. check("GetDevices", l.GetDevices(t.Context()))
  480. if n := countRows(t, d, "SELECT COUNT(*) FROM device_seen WHERE mac = ? AND first_seen = 1", uplinkMAC); n != 1 {
  481. t.Errorf("el vecino de uplink %s debe conservar su fila en device_seen (filas=%d)", uplinkMAC, n)
  482. }
  483. if n := countRows(t, d, "SELECT COUNT(*) FROM device_seen WHERE mac = ? AND first_seen = 1", lanMAC); n != 1 {
  484. t.Errorf("el cliente LAN %s debe conservar su fila con first_seen = 1 (filas=%d)", lanMAC, n)
  485. }
  486. }