lldp_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. // lldp_test.go — parser de `lldpcli -f json show neighbors` (fixture
  2. // portado de adapters/lldp_test.go al mover el parser a probe, #489) y
  3. // comportamiento de la sonda probeLldp con runner fake.
  4. package probe
  5. import (
  6. "context"
  7. "encoding/json"
  8. "reflect"
  9. "strings"
  10. "testing"
  11. )
  12. // Fixture realista (lldpd 1.0.x en OpenWrt): switch gestionado GS308E con
  13. // mgmt-ip (array) y caps Bridge, un AP anunciándose (mgmt-ip como string
  14. // suelto), un equipo sin mgmt-ip ni descr de puerto.
  15. const lldpcliFixture = `{
  16. "lldp": {
  17. "interface": [
  18. {
  19. "name": "lan3",
  20. "via": "LLDP",
  21. "rid": "2",
  22. "age": "0 day, 00:01:12",
  23. "chassis": {
  24. "GS308E": {
  25. "id": {"type": "mac", "value": "28:c6:8e:1d:90:44"},
  26. "descr": "Netgear GS308E 8-Port Gigabit Smart Managed Plus Switch",
  27. "mgmt-ip": ["192.168.8.13", "fe80::2ac6:8eff:fe1d:9044"],
  28. "capability": [
  29. {"type": "Bridge", "enabled": true},
  30. {"type": "Router", "enabled": false}
  31. ]
  32. }
  33. },
  34. "port": {
  35. "id": {"type": "ifname", "value": "ge5"},
  36. "descr": "ge5",
  37. "ttl": "120"
  38. }
  39. },
  40. {
  41. "name": "lan1",
  42. "chassis": {
  43. "AP-patio": {
  44. "id": {"type": "mac", "value": "aa:bb:cc:dd:ee:ff"},
  45. "mgmt-ip": "192.168.8.20"
  46. }
  47. },
  48. "port": {"id": {"type": "local", "value": "0.2"}}
  49. },
  50. {
  51. "name": "lan4",
  52. "chassis": {
  53. " Equipo-sin-nombre ": {
  54. "id": {"type": "mac", "value": "11:22:33:44:55:66"}
  55. }
  56. }
  57. }
  58. ]
  59. }
  60. }`
  61. func TestParseLldpNeighborsFixture(t *testing.T) {
  62. nbs, err := ParseLldpNeighbors([]byte(lldpcliFixture))
  63. if err != nil {
  64. t.Fatalf("parse: %v", err)
  65. }
  66. if len(nbs) != 3 {
  67. t.Fatalf("vecinos: %d", len(nbs))
  68. }
  69. // Orden estable: el array llega lan3, lan1, lan4
  70. got := nbs[0]
  71. if got.Port != "lan3" || got.Chassis != "GS308E" || got.ChassisMac != "28:C6:8E:1D:90:44" {
  72. t.Fatalf("n[0]: %+v", got)
  73. }
  74. if got.Mgmt != "192.168.8.13" {
  75. t.Fatalf("mgmt: %q", got.Mgmt)
  76. }
  77. if !reflect.DeepEqual(got.Caps, []string{"Bridge"}) {
  78. t.Fatalf("caps: %v", got.Caps)
  79. }
  80. if got.PortDesc != "ge5" {
  81. t.Fatalf("portDesc: %q", got.PortDesc)
  82. }
  83. // mgmt-ip como string suelto + port descr ausente → id del puerto
  84. if nbs[1].Mgmt != "192.168.8.20" || nbs[1].PortDesc != "0.2" {
  85. t.Fatalf("n[1]: %+v", nbs[1])
  86. }
  87. // sin mgmt-ip ni port
  88. if nbs[2].Mgmt != "" || nbs[2].PortDesc != "" {
  89. t.Fatalf("n[2]: %+v", nbs[2])
  90. }
  91. }
  92. func TestParseLldpNeighborsDefensivo(t *testing.T) {
  93. // Raíz no JSON → error (el caller reintenta; NO es lldpd ausente)
  94. if _, err := ParseLldpNeighbors([]byte("lldpd is not running")); err == nil {
  95. t.Fatal("no JSON debería dar error")
  96. }
  97. // Formas vacías → sin vecinos, sin error
  98. for _, in := range []string{`{}`, `{"lldp":{}}`, `{"lldp":{"interface":null}}`, `{"lldp":{"interface":[]}}`, `null`} {
  99. neighbors, err := ParseLldpNeighbors([]byte(in))
  100. if err != nil || len(neighbors) != 0 {
  101. t.Fatalf("%s → %v %v", in, neighbors, err)
  102. }
  103. }
  104. // Forma mapa (lldpd viejo): {"interface": {"lan3": {...}}}; la CLAVE es
  105. // el puerto local.
  106. mapForm := `{"lldp":{"interface":{"lan3":{"chassis":{"sw1":{"id":{"type":"mac","value":"AA:BB:CC:DD:EE:FF"}}}}}}}`
  107. neighbors, err := ParseLldpNeighbors([]byte(mapForm))
  108. if err != nil || len(neighbors) != 1 {
  109. t.Fatalf("forma mapa: %v %v", neighbors, err)
  110. }
  111. if neighbors[0].Port != "lan3" || neighbors[0].ChassisMac != "AA:BB:CC:DD:EE:FF" || neighbors[0].Chassis != "sw1" {
  112. t.Fatalf("forma mapa parseada: %+v", neighbors[0])
  113. }
  114. // Tipos inesperados por todas partes: nunca panic, campos vacíos
  115. weird := `{"lldp":{"interface":[
  116. {"name":"lan1","chassis":"una cadena","port":123},
  117. {"name":"lan2","chassis":{"x":{"id":"no-objeto","mgmt-ip":42,"capability":"no-array"}},"port":{"id":{}}},
  118. 42,
  119. null
  120. ]}}`
  121. neighbors, err = ParseLldpNeighbors([]byte(weird))
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. if len(neighbors) != 4 {
  126. t.Fatalf("entradas raras: %d", len(neighbors))
  127. }
  128. if neighbors[0].Port != "lan1" || neighbors[0].Chassis != "" || neighbors[0].PortDesc != "" {
  129. t.Fatalf("chassis cadena: %+v", neighbors[0])
  130. }
  131. if neighbors[1].Port != "lan2" || neighbors[1].ChassisMac != "" || neighbors[1].Mgmt != "" {
  132. t.Fatalf("subcampos raros: %+v", neighbors[1])
  133. }
  134. if neighbors[2].Port != "" || neighbors[2].Chassis != "" || neighbors[2].Caps != nil {
  135. t.Fatalf("entrada no-objeto: %+v", neighbors[2])
  136. }
  137. if neighbors[3].Port != "" || neighbors[3].ChassisMac != "" {
  138. t.Fatalf("entrada null: %+v", neighbors[3])
  139. }
  140. // interface con forma ni array ni mapa → sin datos, no error
  141. neighbors, err = ParseLldpNeighbors([]byte(`{"lldp":{"interface":42}}`))
  142. if err != nil || len(neighbors) != 0 {
  143. t.Fatalf("interface escalar: %v %v", neighbors, err)
  144. }
  145. }
  146. // Fixture real de lldpd 1.0.20 (OpenWrt 25.12, #1370): el array de interface
  147. // lleva objetos de UNA clave con el nombre de la interfaz, sin campo "name".
  148. const lldpcliKeyedArrayFixture = `{
  149. "lldp": {
  150. "interface": [
  151. {
  152. "lan1": {
  153. "via": "LLDP",
  154. "rid": "1",
  155. "age": "0 day, 00:06:34",
  156. "chassis": {
  157. "core-switch": {
  158. "id": {"type": "mac", "value": "78:d8:00:32:31:49"},
  159. "descr": "Managed switch",
  160. "mgmt-ip": ["192.168.8.6"],
  161. "capability": [
  162. {"type": "Bridge", "enabled": true},
  163. {"type": "Router", "enabled": false}
  164. ]
  165. }
  166. },
  167. "port": {
  168. "id": {"type": "ifname", "value": "3"},
  169. "ttl": "120"
  170. }
  171. }
  172. },
  173. {
  174. "lan1": {
  175. "via": "LLDP",
  176. "rid": "2",
  177. "age": "0 day, 00:00:59",
  178. "chassis": {
  179. "ap-atico": {
  180. "id": {"type": "mac", "value": "9c:9d:7e:54:ef:b8"},
  181. "capability": [
  182. {"type": "Wlan", "enabled": true}
  183. ]
  184. }
  185. },
  186. "port": {
  187. "id": {"type": "mac", "value": "9c:9d:7e:54:ef:b8"},
  188. "descr": "lan1",
  189. "ttl": "120"
  190. }
  191. }
  192. }
  193. ]
  194. }
  195. }`
  196. func TestParseLldpNeighborsKeyedArray(t *testing.T) {
  197. nbs, err := ParseLldpNeighbors([]byte(lldpcliKeyedArrayFixture))
  198. if err != nil {
  199. t.Fatalf("parse: %v", err)
  200. }
  201. if len(nbs) != 2 {
  202. t.Fatalf("vecinos: %d", len(nbs))
  203. }
  204. got := nbs[0]
  205. if got.Port != "lan1" || got.Chassis != "core-switch" || got.ChassisMac != "78:D8:00:32:31:49" {
  206. t.Fatalf("n[0]: %+v", got)
  207. }
  208. if got.Mgmt != "192.168.8.6" || !reflect.DeepEqual(got.Caps, []string{"Bridge"}) {
  209. t.Fatalf("n[0] mgmt/caps: %+v", got)
  210. }
  211. got = nbs[1]
  212. if got.Port != "lan1" || got.Chassis != "ap-atico" || got.ChassisMac != "9C:9D:7E:54:EF:B8" || got.PortDesc != "lan1" {
  213. t.Fatalf("n[1]: %+v", got)
  214. }
  215. }
  216. // TestProberLldp: contrato de disponibilidad de la sonda (#489).
  217. func TestProberLldp(t *testing.T) {
  218. ctx := context.Background()
  219. // lldpd NO instalado: command -v falla → Available=false.
  220. p := NewProber(fakeRunner{outs: map[string]string{}}, Options{})
  221. ld := p.probeLldp(ctx)
  222. if ld == nil || ld.Available || ld.Neighbors != nil {
  223. t.Fatalf("sin lldpd: %+v", ld)
  224. }
  225. // Instalado con vecinos: fixture completo.
  226. p = NewProber(fakeRunner{outs: map[string]string{
  227. CmdLldpCheck: "/usr/sbin/lldpcli\n",
  228. CmdLldpNeighbors: lldpcliFixture,
  229. }}, Options{})
  230. ld = p.probeLldp(ctx)
  231. if ld == nil || !ld.Available || len(ld.Neighbors) != 3 {
  232. t.Fatalf("con vecinos: %+v", ld)
  233. }
  234. // Instalado, lldpd parado: check OK pero lldpcli sin salida →
  235. // Available=true con Neighbors nil (sonda fallida, no "no instalado").
  236. p = NewProber(fakeRunner{outs: map[string]string{
  237. CmdLldpCheck: "/usr/sbin/lldpcli\n",
  238. }}, Options{})
  239. ld = p.probeLldp(ctx)
  240. if ld == nil || !ld.Available || ld.Neighbors != nil {
  241. t.Fatalf("parado: %+v", ld)
  242. }
  243. // Instalado, cero vecinos: interface [] → vacío honesto, no nil.
  244. p = NewProber(fakeRunner{outs: map[string]string{
  245. CmdLldpCheck: "/usr/sbin/lldpcli\n",
  246. CmdLldpNeighbors: `{"lldp":{"interface":[]}}`,
  247. }}, Options{})
  248. ld = p.probeLldp(ctx)
  249. if ld == nil || !ld.Available || ld.Neighbors == nil || len(ld.Neighbors) != 0 {
  250. t.Fatalf("cero vecinos: %+v", ld)
  251. }
  252. }
  253. // TestPayloadLldpWire: nil vs vacío viaja distinto en el JSON (contrato del
  254. // anti-parpadeo del server). Sin omitempty en Neighbors a propósito.
  255. func TestPayloadLldpWire(t *testing.T) {
  256. mustJSON := func(v any) string {
  257. b, err := json.Marshal(v)
  258. if err != nil {
  259. t.Fatalf("marshal: %v", err)
  260. }
  261. return string(b)
  262. }
  263. // Sección presente con vecinos
  264. if s := mustJSON(PayloadData{Lldp: &LldpData{Available: true, Neighbors: []LldpNeighbor{{Port: "lan3"}}}}); !strings.Contains(s, `"neighbors":[{`) {
  265. t.Fatalf("wire con vecinos: %s", s)
  266. }
  267. // Sección presente, sonda fallida: neighbors null (no ausente)
  268. if s := mustJSON(PayloadData{Lldp: &LldpData{Available: true}}); !strings.Contains(s, `"neighbors":null`) {
  269. t.Fatalf("wire sonda fallida: %s", s)
  270. }
  271. // Sección ausente (push event-driven): nada de lldp en el JSON
  272. if s := mustJSON(PayloadData{}); strings.Contains(s, "lldp") {
  273. t.Fatalf("wire sin sección: %s", s)
  274. }
  275. // Disponible sin vecinos (vacío honesto): "neighbors":[]
  276. if s := mustJSON(PayloadData{Lldp: &LldpData{Available: true, Neighbors: []LldpNeighbor{}}}); !strings.Contains(s, `"neighbors":[]`) {
  277. t.Fatalf("wire vacío honesto: %s", s)
  278. }
  279. }
  280. // #1369: el hint bridge-only sale solo cuando el binding UCI es SOLO bridge.
  281. func TestLldpdBridgeOnly(t *testing.T) {
  282. cases := []struct {
  283. ifaces string
  284. want bool
  285. }{
  286. {"", false}, // sin opción UCI: lldpd escucha en físicas
  287. {"br-lan", true}, // el caso del issue (stock qualcommax)
  288. {"br-lan,br-guest", true}, // varios bridges: igual de ciego
  289. {"lan*,wan", false}, // el fix aplicado en la flota
  290. {"lan1", false}, // puerto físico suelto
  291. {"br-lan,lan1", false}, // mixto: ya escucha en físicas
  292. {" lan1 , wan ", false}, // espacios tolerados
  293. {"eth0", false}, // Linux genérico con nombre eth
  294. {",,,", false}, // tokens vacíos: sin binding efectivo
  295. }
  296. for _, c := range cases {
  297. if got := LldpdBridgeOnly(c.ifaces); got != c.want {
  298. t.Errorf("LldpdBridgeOnly(%q) = %v, want %v", c.ifaces, got, c.want)
  299. }
  300. }
  301. }