proxmox_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. // proxmox_test.go — sellado de infraestructura desde el inventario PVE (#561).
  2. package adapters
  3. import (
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "github.com/gnacho/netpulse/server-go/internal/pve"
  9. )
  10. // TestSealProxmoxInfra: con un cluster de 1 nodo (citadel-01) y 2 CTs
  11. // (webs + pbs con MACs BC:24:11 y locally-administered), los devices que
  12. // coinciden por MAC se sellan ct y cuelgan del host; el host se sella
  13. // hypervisor. El caso que la heurística L2 NO puede resolver (puerto mezclado).
  14. func TestSealProxmoxInfra(t *testing.T) {
  15. inv := &pveInventory{
  16. ctByMAC: map[string]pveVM{
  17. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
  18. "02:78:F4:02:8A:94": {Name: "homeassistant", Node: "citadel-01", Type: "lxc", Instance: "default"},
  19. },
  20. nodes: map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
  21. }
  22. devices := []Device{
  23. {ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01", RouterID: "gateway", Band: "—"},
  24. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway", Band: "cable", Port: "lan3", AttachTo: "dist-gateway-lan3"},
  25. {ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "homeassistant", RouterID: "gateway", Band: "cable", Port: "lan3", AttachTo: "dist-gateway-lan3"},
  26. {ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "shield", RouterID: "gateway", Band: "cable", Port: "lan3"},
  27. }
  28. applyPVEInfra(devices, nil, inv)
  29. if devices[0].Infra != "hypervisor" {
  30. t.Fatalf("host citadel-01: infra=%q (want hypervisor)", devices[0].Infra)
  31. }
  32. hostID := devices[0].ID
  33. for i, want := range map[int]string{
  34. 1: "ct", 2: "ct", 3: "",
  35. } {
  36. if devices[i].Infra != want {
  37. t.Errorf("device[%d] %s: infra=%q (want %q)", i, devices[i].Name, devices[i].Infra, want)
  38. }
  39. }
  40. // El sello PVE sobreescribe el attachTo inferido por L2 (dist-gateway-lan3)
  41. // y cuelga los CTs del host.
  42. if devices[1].AttachTo != hostID {
  43. t.Errorf("webs attachTo=%q (want host %q, sobreescribe el inferred)", devices[1].AttachTo, hostID)
  44. }
  45. if devices[2].AttachTo != hostID {
  46. t.Errorf("homeassistant attachTo=%q (want host %q)", devices[2].AttachTo, hostID)
  47. }
  48. // El device no relacionado (shield) queda intacto.
  49. if devices[3].Infra != "" || devices[3].AttachTo != "" {
  50. t.Errorf("shield tocado: %+v", devices[3])
  51. }
  52. }
  53. // TestSealProxmoxInfraCarriesTheGuestVlan: la VLAN de cada invitado sale de
  54. // tag= en su config de Proxmox, el único sitio donde consta: cuelga del
  55. // bridge del host, así que ni el FDB ni `bridge vlan show` del router la ven
  56. // (#1757). Un invitado sin tag queda en 0 (VLAN nativa del bridge).
  57. func TestSealProxmoxInfraCarriesTheGuestVlan(t *testing.T) {
  58. inv := &pveInventory{
  59. ctByMAC: map[string]pveVM{
  60. "BC:24:11:00:00:01": {Name: "iot", Node: "pve", Type: "lxc", Instance: "default", Tag: 999},
  61. "BC:24:11:00:00:02": {Name: "lan", Node: "pve", Type: "lxc", Instance: "default"},
  62. },
  63. nodes: map[string]pveNode{"default|pve": {Instance: "default", Node: "pve"}},
  64. }
  65. devices := []Device{
  66. {ID: "pve", MAC: "C8:FF:BF:0C:60:12", Name: "pve"},
  67. {ID: "bc-24-11-00-00-01", MAC: "BC:24:11:00:00:01", Name: "iot"},
  68. {ID: "bc-24-11-00-00-02", MAC: "BC:24:11:00:00:02", Name: "lan"},
  69. }
  70. applyPVEInfra(devices, nil, inv)
  71. if devices[1].Vlan != 999 {
  72. t.Errorf("iot vlan=%d (want 999)", devices[1].Vlan)
  73. }
  74. if devices[2].Vlan != 0 {
  75. t.Errorf("lan vlan=%d (want 0: sin tag, VLAN nativa)", devices[2].Vlan)
  76. }
  77. // La config de Proxmox resolvio ambos: sin tag tambien es una respuesta
  78. // (#1757), asi que la UI no debe caer al puerto del trunk.
  79. for _, i := range []int{1, 2} {
  80. if !devices[i].VlanKnown {
  81. t.Errorf("%s: la VLAN vino de Proxmox y VlanKnown deberia ser true", devices[i].Name)
  82. }
  83. }
  84. }
  85. // TestSealProxmoxInfraUntaggedGuestClearsTheFdbVlan: el FDB del router se
  86. // aplica en buildDevices, ANTES del sello PVE, y rellena la VLAN de cualquier
  87. // device que no tenga una. En un host cuyo puerto es un trunk esa evidencia
  88. // es falsa: un invitado sin tag= y el propio host acababan pintados con la
  89. // VLAN de otro invitado (#1757, ronda de 2.51.4). La config de Proxmox es la
  90. // única fuente: sin tag, la respuesta honesta es "sin VLAN".
  91. func TestSealProxmoxInfraUntaggedGuestClearsTheFdbVlan(t *testing.T) {
  92. inv := &pveInventory{
  93. ctByMAC: map[string]pveVM{
  94. "BC:24:11:00:00:01": {Name: "tagged", Node: "pve", Type: "qemu", Instance: "default", Tag: 999},
  95. "BC:24:11:00:00:02": {Name: "untagged", Node: "pve", Type: "lxc", Instance: "default"},
  96. },
  97. nodes: map[string]pveNode{"default|pve": {Instance: "default", Node: "pve"}},
  98. }
  99. devices := []Device{
  100. {ID: "pve", MAC: "C8:FF:BF:0C:60:12", Name: "pve", Vlan: 888},
  101. {ID: "bc-24-11-00-00-01", MAC: "BC:24:11:00:00:01", Name: "tagged", Vlan: 1},
  102. {ID: "bc-24-11-00-00-02", MAC: "BC:24:11:00:00:02", Name: "untagged", Vlan: 888},
  103. {ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "otro", Vlan: 888},
  104. }
  105. applyPVEInfra(devices, nil, inv)
  106. if devices[0].Vlan != 0 {
  107. t.Errorf("host vlan=%d (want 0: el FDB de un trunk no es su gestión)", devices[0].Vlan)
  108. }
  109. if devices[1].Vlan != 999 {
  110. t.Errorf("tagged vlan=%d (want 999: el tag= manda sobre el FDB)", devices[1].Vlan)
  111. }
  112. if devices[2].Vlan != 0 {
  113. t.Errorf("untagged vlan=%d (want 0: sin tag no se inventa)", devices[2].Vlan)
  114. }
  115. if devices[3].Vlan != 888 {
  116. t.Errorf("device ajeno a PVE tocado: vlan=%d (want 888)", devices[3].Vlan)
  117. }
  118. // Host e invitados quedan resueltos (VlanKnown true, aunque Vlan sea 0);
  119. // el device ajeno a PVE conserva "sin dato" para que la UI use el puerto.
  120. for _, i := range []int{0, 1, 2} {
  121. if !devices[i].VlanKnown {
  122. t.Errorf("%s: Proxmox resolvio la VLAN y VlanKnown deberia ser true", devices[i].Name)
  123. }
  124. }
  125. if devices[3].VlanKnown {
  126. t.Error("un device ajeno a PVE no debe marcarse como resuelto")
  127. }
  128. }
  129. // TestSealProxmoxInfraSinInventario: sin cluster configurado o sin CTs
  130. // conocidos → no-op (los devices no cambian).
  131. func TestSealProxmoxInfraSinInventario(t *testing.T) {
  132. devices := []Device{{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01"}}
  133. applyPVEInfra(devices, nil, nil)
  134. if devices[0].Infra != "" || devices[0].AttachTo != "" {
  135. t.Fatalf("sin inventario no debe tocar devices: %+v", devices[0])
  136. }
  137. }
  138. // TestSealProxmoxInfraHostSinDevice: un nodo PVE cuyo host NO es un device
  139. // conocido (no habla a la LAN) no rompe nada: los CTs se sellan ct sin host.
  140. func TestSealProxmoxInfraHostSinDevice(t *testing.T) {
  141. inv := &pveInventory{
  142. ctByMAC: map[string]pveVM{
  143. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-99", Type: "lxc", Instance: "default"},
  144. },
  145. nodes: map[string]pveNode{"default|citadel-99": {Instance: "default", Node: "citadel-99"}},
  146. }
  147. devices := []Device{
  148. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway"},
  149. }
  150. applyPVEInfra(devices, nil, inv)
  151. if devices[0].Infra != "ct" {
  152. t.Fatalf("webs infra=%q (want ct aunque no haya host device)", devices[0].Infra)
  153. }
  154. if devices[0].AttachTo != "" {
  155. t.Fatalf("sin host device no debe haber attachTo: %q", devices[0].AttachTo)
  156. }
  157. }
  158. // TestSealProxmoxInfraHostPorIP: cuando NetPulse no conoce el NOMBRE del host
  159. // (aparece solo por MAC/IP, p. ej. citadel-02 = E8:FF:1E... con IP .101), el
  160. // host se casa por IP del nodo (vmbr0).
  161. func TestSealProxmoxInfraHostPorIP(t *testing.T) {
  162. inv := &pveInventory{
  163. ctByMAC: map[string]pveVM{
  164. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc", Instance: "default"},
  165. },
  166. nodes: map[string]pveNode{"default|citadel-02": {Instance: "default", Node: "citadel-02"}},
  167. nodeIPs: map[string][]string{"default|citadel-02": {"192.168.1.101"}},
  168. }
  169. devices := []Device{
  170. {ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "E8:FF:1E:DD:C7:ED", IP: "192.168.1.101", RouterID: "switch16"},
  171. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", RouterID: "switch16", AttachTo: "dist-switch16-lan8"},
  172. }
  173. applyPVEInfra(devices, nil, inv)
  174. if devices[0].Infra != "hypervisor" {
  175. t.Fatalf("host por IP: infra=%q (want hypervisor)", devices[0].Infra)
  176. }
  177. if devices[0].Name != "citadel-02" {
  178. t.Fatalf("host renombrado: name=%q (want citadel-02)", devices[0].Name)
  179. }
  180. if devices[1].AttachTo != devices[0].ID {
  181. t.Fatalf("webs attachTo=%q (want host por IP %q)", devices[1].AttachTo, devices[0].ID)
  182. }
  183. }
  184. // TestSealProxmoxInfraHostConflictoNICs: un host físico con dos NICs aparece
  185. // como dos devices (p. ej. citadel-01 online con IP vmbr0 .100, y el mismo
  186. // host offline con IP de gestión .243). El host correcto es el de la IP del
  187. // nodo (vmbr0), aunque otro device tenga el nombre "citadel-01".
  188. func TestSealProxmoxInfraHostConflictoNICs(t *testing.T) {
  189. inv := &pveInventory{
  190. ctByMAC: map[string]pveVM{
  191. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
  192. },
  193. nodes: map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
  194. nodeIPs: map[string][]string{"default|citadel-01": {"192.168.1.100"}},
  195. }
  196. devices := []Device{
  197. // device con nombre citadel-01 pero IP de gestión (.243) y offline.
  198. {ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01", IP: "192.168.1.243", Online: false},
  199. // device online con la IP vmbr0 del nodo (.100): host correcto.
  200. {ID: "fe-c9-95-97-15-30", MAC: "FE:C9:95:97:15:30", Name: "FE:C9:95:97:15:30", IP: "192.168.1.100", Online: true},
  201. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", Online: true},
  202. }
  203. applyPVEInfra(devices, nil, inv)
  204. // El hypervisor debe ser el device con IP .100 (online), no el offline.
  205. if devices[1].Infra != "hypervisor" || devices[1].Name != "citadel-01" {
  206. t.Fatalf("host por IP debería ganar: %+v (infra=%q name=%q)", devices[1], devices[1].Infra, devices[1].Name)
  207. }
  208. if devices[0].Infra == "hypervisor" {
  209. t.Fatalf("el device offline con nombre citadel-01 NO debe ser hypervisor: %+v", devices[0])
  210. }
  211. if devices[2].AttachTo != devices[1].ID {
  212. t.Fatalf("webs attachTo=%q (want host online %q)", devices[2].AttachTo, devices[1].ID)
  213. }
  214. }
  215. // TestPVEHostMACDeviceID: el id del device (MAC minúsculas con guiones) casa
  216. // con la clave del inventario (MAC mayúsculas con ':') para CTs.
  217. func TestPVEMacToDeviceID(t *testing.T) {
  218. if got := macToDeviceID("BC:24:11:A4:9E:BB"); got != "bc-24-11-a4-9e-bb" {
  219. t.Fatalf("macToDeviceID: %q", got)
  220. }
  221. }
  222. // TestPVEHypervisorDistNodes: el sellado PVE crea un distnode kind=hypervisor
  223. // por host (con Source=proxmox y HostDeviceID del host) para que el frontend
  224. // anide los CTs bajo él (grid +N). Un host que ya tenga distnode hypervisor
  225. // inferido por L2 NO se duplica.
  226. func TestPVEHypervisorDistNodes(t *testing.T) {
  227. inv := &pveInventory{
  228. ctByMAC: map[string]pveVM{
  229. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc", Instance: "default"},
  230. "02:78:F4:02:8A:94": {Name: "pbs", Node: "citadel-02", Type: "lxc", Instance: "default"},
  231. },
  232. nodes: map[string]pveNode{"default|citadel-02": {Instance: "default", Node: "citadel-02"}, "default|citadel-01": {Instance: "default", Node: "citadel-01"}},
  233. nodeIPs: map[string][]string{"default|citadel-02": {"192.168.1.101"}, "default|citadel-01": {"192.168.1.100"}},
  234. }
  235. devices := []Device{
  236. {ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "E8:FF:1E:DD:C7:ED", IP: "192.168.1.101", RouterID: "switch16", Port: "lan8"},
  237. {ID: "fe-c9-95-97-15-30", MAC: "FE:C9:95:97:15:30", Name: "FE:C9:95:97:15:30", IP: "192.168.1.100", RouterID: "gateway", Port: "lan1"},
  238. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs"},
  239. {ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "pbs"},
  240. }
  241. // citadel-01 ya tiene distnode hypervisor inferido por L2: no duplicar.
  242. dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "hypervisor", RouterID: "gateway", HostDeviceID: "fe-c9-95-97-15-30"}}
  243. dists = applyPVEInfra(devices, dists, inv)
  244. if len(dists) != 2 {
  245. t.Fatalf("esperado 2 distnodes (L2 + 1 PVE), got %d: %+v", len(dists), dists)
  246. }
  247. dn := dists[1]
  248. if dn.ID != "dist-pve-default-citadel-02" || dn.Kind != "hypervisor" || dn.Source != "proxmox" {
  249. t.Fatalf("distnode PVE mal construido: %+v", dn)
  250. }
  251. if dn.HostDeviceID != devices[0].ID {
  252. t.Fatalf("HostDeviceID=%q (want %q)", dn.HostDeviceID, devices[0].ID)
  253. }
  254. if dn.Name != "citadel-02" || dn.RouterID != "switch16" || dn.Port != "lan8" {
  255. t.Fatalf("distnode PVE con metadatos del host incorrectos: %+v", dn)
  256. }
  257. if dn.MacCount != 2 {
  258. t.Fatalf("MacCount=%d (want 2 CTs sellados)", dn.MacCount)
  259. }
  260. }
  261. // TestPVEHypervisorDistNodesSinHost: sin inventario los distnodes no cambian.
  262. func TestPVEHypervisorDistNodesSinHost(t *testing.T) {
  263. dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred"}}
  264. out := applyPVEInfra([]Device{{ID: "x", MAC: "AA:BB:CC:DD:EE:FF"}}, dists, nil)
  265. if len(out) != 1 || out[0].ID != "dist-gateway-lan1" {
  266. t.Fatalf("sin inventario no debe añadir distnodes: %+v", out)
  267. }
  268. }
  269. // TestSealProxmoxInfraMultiInstancia (#764): dos clusters con un nodo
  270. // homónimo ("pve1") en ambos: las claves compuestas evitan que se pisen, los
  271. // CTs cuelgan del host de SU instancia y los distnodes son distintos.
  272. func TestSealProxmoxInfraMultiInstancia(t *testing.T) {
  273. inv := &pveInventory{
  274. ctByMAC: map[string]pveVM{
  275. "AA:00:00:00:00:01": {Name: "webs", Node: "pve1", Type: "lxc", Instance: "casa"},
  276. "BB:00:00:00:00:02": {Name: "erp", Node: "pve1", Type: "qemu", Instance: "ofi"},
  277. },
  278. nodes: map[string]pveNode{
  279. "casa|pve1": {Instance: "casa", Node: "pve1"},
  280. "ofi|pve1": {Instance: "ofi", Node: "pve1"},
  281. },
  282. }
  283. devices := []Device{
  284. {ID: "aa-11", MAC: "AA:11:00:00:00:01", Name: "host-casa", RouterID: "gateway", Band: "—"},
  285. {ID: "bb-22", MAC: "BB:11:00:00:00:02", Name: "host-ofi", RouterID: "gateway", Band: "—"},
  286. }
  287. // Hosts casados por IP de su instancia.
  288. inv.nodeIPs = map[string][]string{"casa|pve1": {"10.0.0.1"}, "ofi|pve1": {"10.0.0.2"}}
  289. devices[0].IP = "10.0.0.1"
  290. devices[1].IP = "10.0.0.2"
  291. dists := applyPVEInfra(devices, nil, inv)
  292. if devices[0].Infra != "hypervisor" || devices[1].Infra != "hypervisor" {
  293. t.Fatalf("hosts: %q %q", devices[0].Infra, devices[1].Infra)
  294. }
  295. // Cada CT cuelga del host de SU instancia (no del homónimo).
  296. byMAC := map[string]int{}
  297. for i, d := range devices {
  298. byMAC[d.MAC] = i
  299. }
  300. _ = byMAC
  301. // (Los CT webs/erp no son devices aquí: basta con que los hosts sellaran
  302. // y los distnodes salgan separados por instancia.)
  303. if len(dists) != 2 {
  304. t.Fatalf("distnodes: %v", dists)
  305. }
  306. ids := map[string]bool{}
  307. for _, dn := range dists {
  308. ids[dn.ID] = true
  309. if dn.Instance == "" {
  310. t.Fatalf("distnode sin instancia: %+v", dn)
  311. }
  312. }
  313. if !ids["dist-pve-casa-pve1"] || !ids["dist-pve-ofi-pve1"] {
  314. t.Fatalf("IDs de distnodes homónimos: %v", ids)
  315. }
  316. }
  317. // A container rarely asks for DHCP with a hostname, so the name the admin
  318. // gave it in Proxmox is usually the only one there is: without it the list
  319. // is a column of MACs wearing a CT badge.
  320. func TestSealProxmoxNamesContainersKnownOnlyByMAC(t *testing.T) {
  321. inv := &pveInventory{
  322. ctByMAC: map[string]pveVM{
  323. "BC:24:11:A4:9E:BB": {Name: "storage", Node: "pve1", Type: "lxc", Instance: "default"},
  324. "02:00:00:00:00:32": {Name: "proxyapp", Node: "pve1", Type: "lxc", Instance: "default"},
  325. "02:00:00:00:00:31": {Name: "jellyfin", Node: "pve1", Type: "lxc", Instance: "default"},
  326. },
  327. nodes: map[string]pveNode{"default|pve1": {Instance: "default", Node: "pve1"}},
  328. }
  329. devices := []Device{
  330. // Known only by its MAC: the guest name is all we have.
  331. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "BC:24:11:A4:9E:BB"},
  332. // Same, spelled with dashes as the device id is.
  333. {ID: "02-00-00-00-00-32", MAC: "02:00:00:00:00:32", Name: "02-00-00-00-00-32"},
  334. // This one has a real name from its DHCP lease: Proxmox must not
  335. // overwrite what the network already knows it as.
  336. {ID: "02-00-00-00-00-31", MAC: "02:00:00:00:00:31", Name: "media-server"},
  337. }
  338. applyPVEInfra(devices, nil, inv)
  339. if devices[0].Name != "storage" {
  340. t.Errorf("name: %q (want storage)", devices[0].Name)
  341. }
  342. if devices[1].Name != "proxyapp" {
  343. t.Errorf("name: %q (want proxyapp)", devices[1].Name)
  344. }
  345. if devices[2].Name != "media-server" {
  346. t.Errorf("a real name was overwritten: %q", devices[2].Name)
  347. }
  348. for i := range devices {
  349. if devices[i].Infra != "ct" {
  350. t.Errorf("device[%d]: infra=%q", i, devices[i].Infra)
  351. }
  352. }
  353. }
  354. // A guest the controller reports without a name leaves the device alone.
  355. func TestSealProxmoxKeepsMACWhenTheGuestHasNoName(t *testing.T) {
  356. inv := &pveInventory{
  357. ctByMAC: map[string]pveVM{"BC:24:11:A4:9E:BB": {Node: "pve1", Type: "qemu", Instance: "default"}},
  358. nodes: map[string]pveNode{"default|pve1": {Instance: "default", Node: "pve1"}},
  359. }
  360. devices := []Device{{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "BC:24:11:A4:9E:BB"}}
  361. applyPVEInfra(devices, nil, inv)
  362. if devices[0].Name != "BC:24:11:A4:9E:BB" {
  363. t.Fatalf("name: %q", devices[0].Name)
  364. }
  365. }
  366. // pveFakeAPI: a Proxmox endpoint with one node and one running CT. The two
  367. // switches decide where a node's address can be read from.
  368. func pveFakeAPI(t *testing.T, clusterStatusOK bool, ifaceAddress string) *httptest.Server {
  369. t.Helper()
  370. return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  371. w.Header().Set("Content-Type", "application/json")
  372. switch {
  373. case r.URL.Path == "/api2/json/cluster/resources":
  374. w.Write([]byte(`{"data":[
  375. {"id":"node/pve1","node":"pve1","type":"node","status":"online"},
  376. {"id":"lxc/100","vmid":100,"node":"pve1","type":"lxc","status":"running","name":"storage"}
  377. ]}`))
  378. case r.URL.Path == "/api2/json/cluster/status":
  379. if !clusterStatusOK {
  380. w.WriteHeader(http.StatusForbidden)
  381. w.Write([]byte(`{"message":"Permission check failed (/, Sys.Audit)\n","data":null}`))
  382. return
  383. }
  384. w.Write([]byte(`{"data":[{"type":"node","name":"pve1","ip":"192.0.2.2","online":1}]}`))
  385. case strings.HasSuffix(r.URL.Path, "/network"):
  386. if ifaceAddress == "" {
  387. // A host configured outside /etc/network/interfaces: NICs
  388. // with no address at all, which is what hid the hypervisor.
  389. w.Write([]byte(`{"data":[{"iface":"enp2s0","type":"eth","method":"manual"}]}`))
  390. return
  391. }
  392. w.Write([]byte(`{"data":[{"iface":"vmbr0","type":"bridge","address":"` + ifaceAddress + `"}]}`))
  393. case strings.HasSuffix(r.URL.Path, "/config"):
  394. w.Write([]byte(`{"data":{"net0":"bridge=vmbr0,hwaddr=BC:24:11:A4:9E:BB,name=eth0,type=veth"}}`))
  395. default:
  396. t.Errorf("unexpected path %q", r.URL.Path)
  397. w.WriteHeader(404)
  398. }
  399. }))
  400. }
  401. func pveInventoryFrom(t *testing.T, srv *httptest.Server) *pveInventory {
  402. t.Helper()
  403. cfg := pve.Config{URL: srv.URL, TokenID: "netpulse@pam!t", Secret: "s"}
  404. inv := NewLive(nil, nil, nil, nil).fetchPveInventory([]pveInstClient{
  405. {inst: pve.Instance{ID: "acasa", Name: "casa", Config: cfg}, c: pve.NewClient(cfg)},
  406. })
  407. if inv == nil {
  408. t.Fatal("inventario nil")
  409. }
  410. return inv
  411. }
  412. // The address comes from cluster/status, the only source that knows it when
  413. // the node's interfaces declare none.
  414. func TestPVENodeIPFromClusterStatus(t *testing.T) {
  415. srv := pveFakeAPI(t, true, "")
  416. defer srv.Close()
  417. if got := pveInventoryFrom(t, srv).nodeIPs["acasa|pve1"]; !hasIP(got, "192.0.2.2") {
  418. t.Fatalf("nodeIPs: %q", got)
  419. }
  420. }
  421. // Without Sys.Audit there is no cluster/status, and the declared bridge is
  422. // still a good answer.
  423. func TestPVENodeIPFallsBackToTheInterfaces(t *testing.T) {
  424. srv := pveFakeAPI(t, false, "192.0.2.7")
  425. defer srv.Close()
  426. if got := pveInventoryFrom(t, srv).nodeIPs["acasa|pve1"]; !hasIP(got, "192.0.2.7") {
  427. t.Fatalf("nodeIPs: %q", got)
  428. }
  429. }
  430. // Neither source says anything: for a single node the configured endpoint
  431. // IS that node, so the host can still be matched.
  432. func TestPVENodeIPFallsBackToTheEndpoint(t *testing.T) {
  433. srv := pveFakeAPI(t, false, "")
  434. defer srv.Close()
  435. inv := pveInventoryFrom(t, srv)
  436. want := strings.TrimPrefix(srv.URL, "http://")
  437. want = want[:strings.LastIndex(want, ":")]
  438. if got := inv.nodeIPs["acasa|pve1"]; !hasIP(got, want) {
  439. t.Fatalf("nodeIPs: %q (want %q)", got, want)
  440. }
  441. // And with that address the seal finally produces the hypervisor node
  442. // and hangs the container off it -- the whole point of the fallback.
  443. devices := []Device{
  444. {ID: "02-00-00-00-00-40", MAC: "02:00:00:00:00:40", Name: "proxmox", IP: want, RouterID: "gateway", Port: "lan2"},
  445. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "BC:24:11:A4:9E:BB"},
  446. }
  447. dists := applyPVEInfra(devices, nil, inv)
  448. if devices[0].Infra != "hypervisor" {
  449. t.Fatalf("host: %+v", devices[0])
  450. }
  451. if len(dists) != 1 || dists[0].Kind != "hypervisor" || dists[0].HostDeviceID != devices[0].ID {
  452. t.Fatalf("distnode: %+v", dists)
  453. }
  454. if devices[1].AttachTo != devices[0].ID || devices[1].Name != "storage" {
  455. t.Fatalf("ct: %+v", devices[1])
  456. }
  457. }
  458. func hasIP(ips []string, want string) bool {
  459. for _, ip := range ips {
  460. if ip == want {
  461. return true
  462. }
  463. }
  464. return false
  465. }
  466. // A cluster where corosync has its own network: the address the node
  467. // announces to the cluster is NOT the management one the LAN knows it by.
  468. // Keeping only one of the two would lose the host on half the installs --
  469. // exactly the setups where matching by the declared bridge already worked.
  470. func TestPVEKeepsBothTheManagementAndTheClusterAddress(t *testing.T) {
  471. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  472. w.Header().Set("Content-Type", "application/json")
  473. switch {
  474. case r.URL.Path == "/api2/json/cluster/resources":
  475. w.Write([]byte(`{"data":[
  476. {"id":"node/pve1","node":"pve1","type":"node","status":"online"},
  477. {"id":"node/pve2","node":"pve2","type":"node","status":"online"},
  478. {"id":"lxc/100","vmid":100,"node":"pve1","type":"lxc","status":"running","name":"storage"}
  479. ]}`))
  480. case r.URL.Path == "/api2/json/cluster/status":
  481. // corosync ring on a dedicated network.
  482. w.Write([]byte(`{"data":[
  483. {"type":"node","name":"pve1","ip":"10.10.10.1","online":1},
  484. {"type":"node","name":"pve2","ip":"10.10.10.2","online":1}
  485. ]}`))
  486. case strings.HasSuffix(r.URL.Path, "/network"):
  487. // management address, the one the LAN resolves.
  488. w.Write([]byte(`{"data":[{"iface":"vmbr0","type":"bridge","address":"192.0.2.50"}]}`))
  489. case strings.HasSuffix(r.URL.Path, "/config"):
  490. w.Write([]byte(`{"data":{"net0":"bridge=vmbr0,hwaddr=BC:24:11:A4:9E:BB,name=eth0,type=veth"}}`))
  491. default:
  492. t.Errorf("unexpected path %q", r.URL.Path)
  493. w.WriteHeader(404)
  494. }
  495. }))
  496. defer srv.Close()
  497. inv := pveInventoryFrom(t, srv)
  498. got := inv.nodeIPs["acasa|pve1"]
  499. if !hasIP(got, "192.0.2.50") || !hasIP(got, "10.10.10.1") {
  500. t.Fatalf("both addresses must survive: %q", got)
  501. }
  502. // And the host still matches on the management address, as it did
  503. // before cluster/status existed here.
  504. devices := []Device{
  505. {ID: "aa-bb-cc-00-00-01", MAC: "AA:BB:CC:00:00:01", Name: "pve-host", IP: "192.0.2.50"},
  506. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "BC:24:11:A4:9E:BB"},
  507. }
  508. applyPVEInfra(devices, nil, inv)
  509. if devices[0].Infra != "hypervisor" {
  510. t.Fatalf("host: %+v", devices[0])
  511. }
  512. if devices[1].AttachTo != devices[0].ID {
  513. t.Fatalf("ct: %+v", devices[1])
  514. }
  515. }
  516. // A qemu guest is a virtual machine, not a container. The inventory says
  517. // which it is and the seal used to ignore it, so a VM wore a CT badge.
  518. func TestSealProxmoxTellsVMsFromContainers(t *testing.T) {
  519. inv := &pveInventory{
  520. ctByMAC: map[string]pveVM{
  521. "BC:24:11:A4:9E:BB": {Name: "appbox", Node: "pve1", Type: "lxc", Instance: "default"},
  522. "02:00:00:00:00:50": {Name: "vm-appliance", Node: "pve1", Type: "qemu", Instance: "default"},
  523. },
  524. nodes: map[string]pveNode{"default|pve1": {Instance: "default", Node: "pve1"}},
  525. nodeIPs: map[string][]string{"default|pve1": {"192.0.2.2"}},
  526. }
  527. devices := []Device{
  528. {ID: "aa-bb-cc-00-00-01", MAC: "AA:BB:CC:00:00:01", Name: "pve-host", IP: "192.0.2.2"},
  529. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "BC:24:11:A4:9E:BB"},
  530. {ID: "02-00-00-00-00-50", MAC: "02:00:00:00:00:50", Name: "02:00:00:00:00:50"},
  531. }
  532. applyPVEInfra(devices, nil, inv)
  533. if devices[1].Infra != "ct" {
  534. t.Errorf("lxc: infra=%q (want ct)", devices[1].Infra)
  535. }
  536. if devices[2].Infra != "vm" {
  537. t.Errorf("qemu: infra=%q (want vm)", devices[2].Infra)
  538. }
  539. // Both are still guests of the host: the badge changes, not the nesting.
  540. for _, i := range []int{1, 2} {
  541. if devices[i].AttachTo != devices[0].ID {
  542. t.Errorf("device[%d] attachTo=%q", i, devices[i].AttachTo)
  543. }
  544. }
  545. if devices[2].Name != "vm-appliance" {
  546. t.Errorf("name: %q", devices[2].Name)
  547. }
  548. }
  549. // Classification runs inside buildDevices and this seal renames afterwards,
  550. // so a guest named here had been classified while its name was still its
  551. // MAC: "adguard" came out untyped although that word has always been a
  552. // "servidor" rule.
  553. func TestSealProxmoxReclassifiesWhatItRenames(t *testing.T) {
  554. inv := &pveInventory{
  555. ctByMAC: map[string]pveVM{
  556. "BC:24:11:00:00:01": {Name: "adguard", Node: "pve1", Type: "lxc", Instance: "default"},
  557. "BC:24:11:00:00:02": {Name: "appbox", Node: "pve1", Type: "lxc", Instance: "default"},
  558. "BC:24:11:00:00:03": {Name: "pixel-of-someone", Node: "pve1", Type: "lxc", Instance: "default"},
  559. },
  560. nodes: map[string]pveNode{"default|pve1": {Instance: "default", Node: "pve1"}},
  561. nodeIPs: map[string][]string{"default|pve1": {"192.0.2.2"}},
  562. }
  563. devices := []Device{
  564. {ID: "aa-bb-cc-00-00-01", MAC: "AA:BB:CC:00:00:01", Name: "pve-host", IP: "192.0.2.2", Type: "desconocido"},
  565. {ID: "bc-24-11-00-00-01", MAC: "BC:24:11:00:00:01", Name: "BC:24:11:00:00:01", Type: "desconocido"},
  566. {ID: "bc-24-11-00-00-02", MAC: "BC:24:11:00:00:02", Name: "BC:24:11:00:00:02", Type: "desconocido"},
  567. // Already typed from its own evidence: the rename must not re-open it.
  568. {ID: "bc-24-11-00-00-03", MAC: "BC:24:11:00:00:03", Name: "BC:24:11:00:00:03", Type: "servidor"},
  569. }
  570. applyPVEInfra(devices, nil, inv)
  571. if devices[1].Type != "servidor" {
  572. t.Errorf("adguard: type=%q (want servidor)", devices[1].Type)
  573. }
  574. // A name no rule covers is still a machine running a service: being a
  575. // guest of a hypervisor is the evidence, and no word list will ever
  576. // hold every application anyone runs in a container.
  577. if devices[2].Type != "servidor" {
  578. t.Errorf("appbox: type=%q (want servidor)", devices[2].Type)
  579. }
  580. // A type that was already decided is not overwritten by the new name.
  581. if devices[3].Type != "servidor" {
  582. t.Errorf("pre-typed device: %q", devices[3].Type)
  583. }
  584. }
  585. // Every guest ends up typed, whether it was renamed here or already had a
  586. // name of its own, and a rule that matches something more specific than
  587. // "a server" still wins.
  588. func TestSealProxmoxTypesEveryGuest(t *testing.T) {
  589. inv := &pveInventory{
  590. ctByMAC: map[string]pveVM{
  591. "BC:24:11:00:00:01": {Name: "metrics", Node: "pve1", Type: "lxc", Instance: "default"},
  592. "BC:24:11:00:00:02": {Name: "unifi", Node: "pve1", Type: "lxc", Instance: "default"},
  593. "BC:24:11:00:00:03": {Name: "frigate", Node: "pve1", Type: "qemu", Instance: "default"},
  594. },
  595. nodes: map[string]pveNode{"default|pve1": {Instance: "default", Node: "pve1"}},
  596. nodeIPs: map[string][]string{"default|pve1": {"192.0.2.2"}},
  597. }
  598. devices := []Device{
  599. // The host itself, named by nothing in particular.
  600. {ID: "aa-bb-cc-00-00-01", MAC: "AA:BB:CC:00:00:01", Name: "maquina-del-armario", IP: "192.0.2.2", Type: "desconocido"},
  601. // Renamed by the seal.
  602. {ID: "bc-24-11-00-00-01", MAC: "BC:24:11:00:00:01", Name: "BC:24:11:00:00:01", Type: "desconocido"},
  603. // Already had a lease name, so the seal does not rename it -- and it
  604. // was still left untyped before this.
  605. {ID: "bc-24-11-00-00-02", MAC: "BC:24:11:00:00:02", Name: "unifi", Type: "desconocido"},
  606. // A name a rule covers: the camera wins over the generic default.
  607. {ID: "bc-24-11-00-00-03", MAC: "BC:24:11:00:00:03", Name: "camera-nvr", Type: "desconocido"},
  608. }
  609. applyPVEInfra(devices, nil, inv)
  610. for i, want := range []string{"servidor", "servidor", "servidor", "camara"} {
  611. if devices[i].Type != want {
  612. t.Errorf("device[%d] %s: type=%q (want %q)", i, devices[i].Name, devices[i].Type, want)
  613. }
  614. }
  615. }
  616. // TestPVEAbsorbeInferredDeHypervisor: cuando L2 infirió un nodo "inferred" en
  617. // el (router, puerto) del host PVE y todo lo colgado es el host o sus
  618. // invitados (#1053), el inferred se absorbe: el host pasa a colgar del router
  619. // con su puerto (como el canon) y solo queda el distnode PVE de agrupación.
  620. func TestPVEAbsorbeInferredDeHypervisor(t *testing.T) {
  621. inv := &pveInventory{
  622. ctByMAC: map[string]pveVM{
  623. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
  624. "02:78:F4:02:8A:94": {Name: "ha", Node: "citadel-01", Type: "lxc", Instance: "default"},
  625. },
  626. nodes: map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
  627. nodeIPs: map[string][]string{"default|citadel-01": {"192.168.1.100"}},
  628. }
  629. devices := []Device{
  630. {ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "C8:FF:BF:0C:60:12", IP: "192.168.1.100",
  631. RouterID: "switch16", Port: "lan5", AttachTo: "dist-switch16-lan5", Online: true},
  632. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", AttachTo: "dist-switch16-lan5"},
  633. {ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "ha", AttachTo: "dist-switch16-lan5"},
  634. }
  635. dists := []DistributionNode{{ID: "dist-switch16-lan5", Kind: "inferred", RouterID: "switch16", Port: "lan5", MacCount: 3}}
  636. out := applyPVEInfra(devices, dists, inv)
  637. if len(out) != 1 || out[0].Kind != "hypervisor" || out[0].ID != "dist-pve-default-citadel-01" {
  638. t.Fatalf("distnodes = %+v (want solo el distnode PVE)", out)
  639. }
  640. if devices[0].AttachTo != "" {
  641. t.Fatalf("host AttachTo=%q (want vacío: cuelga del router con su puerto)", devices[0].AttachTo)
  642. }
  643. if devices[1].AttachTo != devices[0].ID || devices[2].AttachTo != devices[0].ID {
  644. t.Fatalf("CTs no re-anidados bajo el host: %+v", devices)
  645. }
  646. }
  647. // TestPVENoAbsorbeInferredConDesconocidos: si en el puerto inferred hay algo
  648. // que NO es el host ni un invitado, el nodo inferred se conserva (hay
  649. // hardware real sin explicar detrás).
  650. func TestPVENoAbsorbeInferredConDesconocidos(t *testing.T) {
  651. inv := &pveInventory{
  652. ctByMAC: map[string]pveVM{
  653. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
  654. },
  655. nodes: map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
  656. nodeIPs: map[string][]string{"default|citadel-01": {"192.168.1.100"}},
  657. }
  658. devices := []Device{
  659. {ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "C8:FF:BF:0C:60:12", IP: "192.168.1.100",
  660. RouterID: "switch16", Port: "lan5", AttachTo: "dist-switch16-lan5", Online: true},
  661. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", AttachTo: "dist-switch16-lan5"},
  662. {ID: "a4-d5-c2-05-ef-66", MAC: "A4:D5:C2:05:EF:66", Name: "equipo-suelto", AttachTo: "dist-switch16-lan5"},
  663. }
  664. dists := []DistributionNode{{ID: "dist-switch16-lan5", Kind: "inferred", RouterID: "switch16", Port: "lan5", MacCount: 3}}
  665. out := applyPVEInfra(devices, dists, inv)
  666. if len(out) != 2 || out[0].ID != "dist-switch16-lan5" || out[0].Kind != "inferred" {
  667. t.Fatalf("el inferred con desconocidos debe conservarse: %+v", out)
  668. }
  669. if devices[0].AttachTo != "dist-switch16-lan5" {
  670. t.Fatalf("host AttachTo=%q (want sin cambios)", devices[0].AttachTo)
  671. }
  672. }
  673. // #1378: dos claves de inventario que resuelven al mismo host (p. ej. dos
  674. // entradas nodeIPs con la misma IP, o IP + nombre) no deben emitir el
  675. // distnode hypervisor dos veces: el frontend dibujaba los CTs duplicados.
  676. func TestPVEHypervisorDistNodesNoDuplicaHostRepetido(t *testing.T) {
  677. inv := &pveInventory{
  678. ctByMAC: map[string]pveVM{
  679. "BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc", Instance: "default"},
  680. },
  681. nodes: map[string]pveNode{
  682. "default|citadel-02": {Instance: "default", Node: "citadel-02"},
  683. "default|pve2": {Instance: "default", Node: "pve2"},
  684. },
  685. nodeIPs: map[string][]string{
  686. "default|citadel-02": {"192.168.1.101"},
  687. "default|pve2": {"192.168.1.101"}, // misma IP: mismo host físico
  688. },
  689. }
  690. devices := []Device{
  691. {ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "beelink-nas", IP: "192.168.1.101", RouterID: "switch16", Port: "lan8"},
  692. {ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs"},
  693. }
  694. dists := applyPVEInfra(devices, nil, inv)
  695. count := 0
  696. for _, dn := range dists {
  697. if dn.Kind == "hypervisor" && dn.HostDeviceID == "e8-ff-1e-dd-c7-ed" {
  698. count++
  699. }
  700. }
  701. if count != 1 {
  702. t.Fatalf("distnodes hypervisor para el mismo host: %d (want 1): %+v", count, dists)
  703. }
  704. }