racks.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // racks.go — API REST del rack canvas bajo /api/racks (fase 1.5).
  2. //
  3. // Contrato wire en snake_case; el dominio (internal/rack) usa camelCase y el
  4. // mapper de este fichero es la frontera explícita entre ambos. Lecturas para
  5. // cualquier sesión (RequireAuth global); escrituras solo admin.
  6. package httpapi
  7. import (
  8. "context"
  9. "database/sql"
  10. "errors"
  11. "log"
  12. "net/http"
  13. "github.com/gnacho/netpulse/agent/macaddr"
  14. "github.com/gnacho/netpulse/server-go/internal/adapters"
  15. "github.com/gnacho/netpulse/server-go/internal/auth"
  16. "github.com/gnacho/netpulse/server-go/internal/rack"
  17. )
  18. func (s *server) registerRackRoutes(mux *http.ServeMux) {
  19. if s.db == nil {
  20. return
  21. }
  22. mux.HandleFunc("GET /api/racks", s.handleRacksGet)
  23. mux.Handle("POST /api/racks", auth.RequireAdmin(http.HandlerFunc(s.handleRackCreate)))
  24. mux.Handle("PUT /api/racks/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackUpdate)))
  25. mux.Handle("DELETE /api/racks/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackDelete)))
  26. mux.Handle("PUT /api/racks/layout", auth.RequireAdmin(http.HandlerFunc(s.handleRackLayoutPut)))
  27. mux.Handle("POST /api/racks/cables", auth.RequireAdmin(http.HandlerFunc(s.handleRackCableAdd)))
  28. mux.Handle("DELETE /api/racks/cables/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackCableDelete)))
  29. mux.Handle("PUT /api/racks/profiles/{mac}", auth.RequireAdmin(http.HandlerFunc(s.handleRackProfilePut)))
  30. mux.Handle("POST /api/racks/import-cables", auth.RequireAdmin(http.HandlerFunc(s.handleRackImportCables)))
  31. }
  32. // buildRackHints deriva candidatos de cable desde la DETECCIÓN (FDB): cada
  33. // dispositivo cableado cuya MAC y la de su router están montados genera un
  34. // hint con el puerto físico donde el bridge aprende su MAC. La fuente es el
  35. // descubrimiento, no el dibujo.
  36. func (s *server) buildRackHints(ctx context.Context, mounts []rack.MountRow) []rack.CableHint {
  37. mounted := map[string]bool{}
  38. for _, m := range mounts {
  39. if m.DeviceMAC != "" {
  40. mounted[macaddr.NormalizeLenient(m.DeviceMAC)] = true
  41. }
  42. }
  43. routerMAC := map[string]string{}
  44. if ov := s.lastOv(); ov != nil {
  45. for _, r := range ov.Routers {
  46. if r.MAC != "" {
  47. routerMAC[r.ID] = macaddr.NormalizeLenient(r.MAC)
  48. }
  49. }
  50. }
  51. // Honestidad de la inferencia: un puerto con VARIAS MACs aprendidas es un
  52. // agregado (switch/bridge/hipervisor detrás); cablearlo a un dispositivo
  53. // concreto sería inventar infraestructura. Solo los puertos de MAC única
  54. // generan hint.
  55. perPort := map[string]int{}
  56. for _, d := range s.adapter.GetDevices(ctx) {
  57. if d.Band != "cable" || d.MAC == "" || d.Port == "" {
  58. continue
  59. }
  60. perPort[d.RouterID+"|"+d.Port]++
  61. }
  62. type macPair struct{ a, b string }
  63. hints := []rack.CableHint{}
  64. seen := map[macPair]bool{}
  65. addHint := func(from, to, fromPort, toPort string) {
  66. if from == "" || to == "" || !mounted[from] || !mounted[to] {
  67. return
  68. }
  69. key := macPair{from, to}
  70. if from > to {
  71. key = macPair{to, from}
  72. }
  73. if seen[key] {
  74. return
  75. }
  76. seen[key] = true
  77. hints = append(hints, rack.CableHint{
  78. FromDeviceID: from,
  79. ToDeviceID: to,
  80. FromPortHint: fromPort,
  81. ToPortHint: toPort,
  82. Source: "fdb",
  83. })
  84. }
  85. for _, d := range s.adapter.GetDevices(ctx) {
  86. if d.Band != "cable" || d.MAC == "" || d.Port == "" {
  87. continue
  88. }
  89. if perPort[d.RouterID+"|"+d.Port] != 1 {
  90. continue
  91. }
  92. addHint(routerMAC[d.RouterID], macaddr.NormalizeLenient(d.MAC), d.Port, "")
  93. }
  94. // Uplinks entre miembros de flota montados: el FDB de la unidad designada
  95. // como central (#1186) dice en qué puerto de ella cuelga cada unidad.
  96. // Sin designación (kv rack_uplink_unit vacío) no hay hints de flota: el
  97. // auto-cableado no inventa nada. Fuente directa del último sondeo
  98. // (FleetFdbProvider, live).
  99. if prov, ok := s.adapter.(adapters.FleetFdbProvider); ok {
  100. infra := s.uplinkUnitID()
  101. if infra != "" {
  102. for childID, up := range prov.FleetFdbUplinks(infra, routerMAC[infra]) {
  103. addHint(routerMAC[up.ParentID], routerMAC[childID], up.Port, up.ChildPort)
  104. }
  105. }
  106. }
  107. return hints
  108. }
  109. // --- DTOs (snake_case en el wire) ---
  110. type rackDTO struct {
  111. ID string `json:"id"`
  112. Name string `json:"name"`
  113. UHeight int `json:"u_height"`
  114. WidthStandard string `json:"width_standard"`
  115. Numbering string `json:"numbering"`
  116. Style string `json:"style"`
  117. Location string `json:"location,omitempty"`
  118. PositionX float64 `json:"position_x"`
  119. PositionY float64 `json:"position_y"`
  120. }
  121. type mountDTO struct {
  122. ID string `json:"id"`
  123. RackID string `json:"rack_id"`
  124. DeviceMAC string `json:"device_mac,omitempty"`
  125. FaceplateID string `json:"faceplate_id"`
  126. UStart int `json:"u_start"`
  127. UHeight int `json:"u_height"`
  128. ColStart int `json:"col_start"`
  129. ColSpan int `json:"col_span"`
  130. Label string `json:"label,omitempty"`
  131. StatusPin string `json:"status_pin"`
  132. PortVisibility string `json:"port_visibility"`
  133. }
  134. type cableDTO struct {
  135. ID string `json:"id"`
  136. FromMount string `json:"from_mount"`
  137. FromPort string `json:"from_port"`
  138. ToMount string `json:"to_mount"`
  139. ToPort string `json:"to_port"`
  140. Type string `json:"type"`
  141. Label string `json:"label,omitempty"`
  142. Properties string `json:"properties,omitempty"`
  143. Origin string `json:"origin"`
  144. CreatedAt int64 `json:"created_at"`
  145. }
  146. type profileDTO struct {
  147. MAC string `json:"mac"`
  148. FaceplateID string `json:"faceplate_id"`
  149. UHeight int `json:"u_height"`
  150. ColSpan int `json:"col_span"`
  151. Color string `json:"color"`
  152. Ports []rack.Port `json:"ports"`
  153. }
  154. func rackToDTO(r rack.Rack) rackDTO {
  155. return rackDTO{
  156. ID: r.ID, Name: r.Name, UHeight: r.UHeight, WidthStandard: r.WidthStandard,
  157. Numbering: r.Numbering, Style: r.StyleJSON, Location: r.Location,
  158. PositionX: r.PositionX, PositionY: r.PositionY,
  159. }
  160. }
  161. func dtoToRack(d rackDTO) rack.Rack {
  162. return rack.Rack{
  163. ID: d.ID, Name: d.Name, UHeight: d.UHeight, WidthStandard: d.WidthStandard,
  164. Numbering: d.Numbering, StyleJSON: d.Style, Location: d.Location,
  165. PositionX: d.PositionX, PositionY: d.PositionY,
  166. }
  167. }
  168. func mountRowToDTO(m rack.MountRow) mountDTO {
  169. return mountDTO{
  170. ID: m.ID, RackID: m.RackID, DeviceMAC: m.DeviceMAC, FaceplateID: m.FaceplateID,
  171. UStart: m.UStart, UHeight: m.UHeight, ColStart: m.ColStart, ColSpan: m.ColSpan,
  172. Label: m.Label, StatusPin: m.StatusPin, PortVisibility: m.PortVisibility,
  173. }
  174. }
  175. func dtoToMount(d mountDTO) rack.Mount {
  176. return rack.Mount{
  177. ID: d.ID, RackID: d.RackID, DeviceMAC: d.DeviceMAC, FaceplateID: d.FaceplateID,
  178. UStart: d.UStart, ColStart: d.ColStart,
  179. Label: d.Label, StatusPin: d.StatusPin, PortVisibility: d.PortVisibility,
  180. }
  181. }
  182. func cableToDTO(c rack.Cable) cableDTO {
  183. return cableDTO{
  184. ID: c.ID, FromMount: c.FromMount, FromPort: c.FromPort, ToMount: c.ToMount,
  185. ToPort: c.ToPort, Type: c.Type, Label: c.Label, Properties: c.PropertiesJSON,
  186. Origin: c.Origin, CreatedAt: c.CreatedAt,
  187. }
  188. }
  189. func dtoToCable(d cableDTO) rack.Cable {
  190. return rack.Cable{
  191. ID: d.ID, FromMount: d.FromMount, FromPort: d.FromPort, ToMount: d.ToMount,
  192. ToPort: d.ToPort, Type: d.Type, Label: d.Label, PropertiesJSON: d.Properties,
  193. Origin: d.Origin, CreatedAt: d.CreatedAt,
  194. }
  195. }
  196. func profileToDTO(p rack.DeviceProfile) profileDTO {
  197. return profileDTO{
  198. MAC: p.MAC, FaceplateID: p.FaceplateID, UHeight: p.UHeight,
  199. ColSpan: p.ColSpan, Color: p.Color, Ports: p.Ports,
  200. }
  201. }
  202. func dtoToProfile(d profileDTO) rack.DeviceProfile {
  203. return rack.DeviceProfile{
  204. MAC: d.MAC, FaceplateID: d.FaceplateID, UHeight: d.UHeight,
  205. ColSpan: d.ColSpan, Color: d.Color, Ports: d.Ports,
  206. }
  207. }
  208. // --- Handlers ---
  209. // handleRacksGet: bundle completo del canvas en una sola petición
  210. // (offline-first: racks + montajes con huella + cables + perfiles).
  211. func (s *server) handleRacksGet(w http.ResponseWriter, r *http.Request) {
  212. racks, err := rack.ListRacks(s.db.DB)
  213. if err != nil {
  214. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  215. return
  216. }
  217. mounts, err := rack.ListMountRows(s.db.DB)
  218. if err != nil {
  219. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  220. return
  221. }
  222. // #1186: la evidencia FDB manda sobre los cables detectados. Con datos
  223. // se reconcilian (altas y bajas); sin evidencia (demo, primer arranque)
  224. // no se toca nada. Los manuales nunca se tocan.
  225. hints := s.buildRackHints(r.Context(), mounts)
  226. if s.adapter.Mode() == "live" {
  227. if res, err := rack.SyncDetectedCables(s.db.DB, hints); err != nil {
  228. log.Printf("[netpulse:rack] sync detected cables: %v", err)
  229. } else if res.Removed > 0 || len(res.Created) > 0 {
  230. log.Printf("[netpulse:rack] sync detected cables: %d created, %d removed", len(res.Created), res.Removed)
  231. }
  232. }
  233. cables, err := rack.ListCables(s.db.DB)
  234. if err != nil {
  235. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  236. return
  237. }
  238. profiles, err := rack.ListProfiles(s.db.DB)
  239. if err != nil {
  240. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  241. return
  242. }
  243. racksOut := make([]rackDTO, 0, len(racks))
  244. for _, r := range racks {
  245. racksOut = append(racksOut, rackToDTO(r))
  246. }
  247. mountsOut := make([]mountDTO, 0, len(mounts))
  248. for _, m := range mounts {
  249. mountsOut = append(mountsOut, mountRowToDTO(m))
  250. }
  251. cablesOut := make([]cableDTO, 0, len(cables))
  252. for _, c := range cables {
  253. cablesOut = append(cablesOut, cableToDTO(c))
  254. }
  255. profilesOut := make([]profileDTO, 0, len(profiles))
  256. for _, p := range profiles {
  257. profilesOut = append(profilesOut, profileToDTO(p))
  258. }
  259. // Auditoría dibujado vs detectado: cada cable lleva su estado (hints ya
  260. // computados arriba para el sync #1186).
  261. writeJSON(w, http.StatusOK, map[string]any{
  262. "racks": racksOut, "mounts": mountsOut, "cables": cablesOut, "profiles": profilesOut,
  263. "audit": rack.AuditCables(cables, hints, mounts),
  264. })
  265. }
  266. // handleRackImportCables: siembra cables desde la topología detectada.
  267. // Idempotente por construcción: re-ejecutar solo hace la mitad útil.
  268. func (s *server) handleRackImportCables(w http.ResponseWriter, r *http.Request) {
  269. mounts, err := rack.ListMountRows(s.db.DB)
  270. if err != nil {
  271. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  272. return
  273. }
  274. hints := s.buildRackHints(r.Context(), mounts)
  275. res, err := rack.ImportCables(s.db.DB, hints)
  276. if err != nil {
  277. writeRackStoreError(w, err)
  278. return
  279. }
  280. writeJSON(w, http.StatusOK, map[string]any{
  281. "hints": len(hints),
  282. "created": len(res.Created),
  283. "skipped": res.Skipped,
  284. "noFreePort": len(res.NoFreePort),
  285. })
  286. }
  287. func (s *server) handleRackCreate(w http.ResponseWriter, r *http.Request) {
  288. var d rackDTO
  289. if st := readJSONBody(w, r, &d); st != 0 {
  290. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  291. return
  292. }
  293. created, err := rack.CreateRack(s.db.DB, dtoToRack(d))
  294. if err != nil {
  295. writeError(w, http.StatusBadRequest, "invalid_rack", err.Error())
  296. return
  297. }
  298. writeJSON(w, http.StatusOK, rackToDTO(created))
  299. }
  300. func (s *server) handleRackUpdate(w http.ResponseWriter, r *http.Request) {
  301. var d rackDTO
  302. if st := readJSONBody(w, r, &d); st != 0 {
  303. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  304. return
  305. }
  306. d.ID = r.PathValue("id")
  307. if err := rack.UpdateRack(s.db.DB, dtoToRack(d)); err != nil {
  308. writeRackStoreError(w, err)
  309. return
  310. }
  311. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  312. }
  313. func (s *server) handleRackDelete(w http.ResponseWriter, r *http.Request) {
  314. if err := rack.DeleteRack(s.db.DB, r.PathValue("id")); err != nil {
  315. writeRackStoreError(w, err)
  316. return
  317. }
  318. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  319. }
  320. // handleRackLayoutPut: guardada atómica de montajes de un rack. Body:
  321. // {"rack_id": "...", "upsert": [mount...], "delete": ["id"...]}.
  322. func (s *server) handleRackLayoutPut(w http.ResponseWriter, r *http.Request) {
  323. var body struct {
  324. RackID string `json:"rack_id"`
  325. Upsert []mountDTO `json:"upsert"`
  326. Delete []string `json:"delete"`
  327. }
  328. if st := readJSONBody(w, r, &body); st != 0 {
  329. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  330. return
  331. }
  332. if body.RackID == "" {
  333. writeError(w, http.StatusBadRequest, "invalid_input", "rack_id is required")
  334. return
  335. }
  336. change := rack.LayoutChange{RackID: body.RackID, Delete: body.Delete}
  337. for _, d := range body.Upsert {
  338. change.Upsert = append(change.Upsert, dtoToMount(d))
  339. }
  340. if err := rack.SaveLayout(s.db.DB, change); err != nil {
  341. writeRackStoreError(w, err)
  342. return
  343. }
  344. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  345. }
  346. func (s *server) handleRackCableAdd(w http.ResponseWriter, r *http.Request) {
  347. var d cableDTO
  348. if st := readJSONBody(w, r, &d); st != 0 {
  349. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  350. return
  351. }
  352. created, err := rack.AddCable(s.db.DB, dtoToCable(d))
  353. if err != nil {
  354. writeRackStoreError(w, err)
  355. return
  356. }
  357. writeJSON(w, http.StatusOK, cableToDTO(created))
  358. }
  359. func (s *server) handleRackCableDelete(w http.ResponseWriter, r *http.Request) {
  360. if err := rack.DeleteCable(s.db.DB, r.PathValue("id")); err != nil {
  361. writeRackStoreError(w, err)
  362. return
  363. }
  364. writeJSON(w, http.StatusOK, map[string]any{"ok": true})
  365. }
  366. func (s *server) handleRackProfilePut(w http.ResponseWriter, r *http.Request) {
  367. var d profileDTO
  368. if st := readJSONBody(w, r, &d); st != 0 {
  369. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  370. return
  371. }
  372. d.MAC = macaddr.Normalize(r.PathValue("mac"))
  373. if err := rack.UpsertProfile(s.db.DB, dtoToProfile(d)); err != nil {
  374. writeError(w, http.StatusBadRequest, "invalid_profile", err.Error())
  375. return
  376. }
  377. writeJSON(w, http.StatusOK, profileToDTO(dtoToProfile(d)))
  378. }
  379. // writeRackStoreError mapea los errores del store a códigos HTTP estables.
  380. func writeRackStoreError(w http.ResponseWriter, err error) {
  381. switch {
  382. case errors.Is(err, rack.ErrOverlap), errors.Is(err, rack.ErrPortBusy):
  383. writeError(w, http.StatusConflict, "conflict", err.Error())
  384. case errors.Is(err, rack.ErrUnknownMount), errors.Is(err, sql.ErrNoRows):
  385. writeError(w, http.StatusNotFound, "not_found", err.Error())
  386. case errors.Is(err, rack.ErrInvalidMAC):
  387. writeError(w, http.StatusBadRequest, "invalid_mac", err.Error())
  388. case errors.Is(err, rack.ErrUnknownPort):
  389. writeError(w, http.StatusBadRequest, "unknown_port", err.Error())
  390. default:
  391. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  392. }
  393. }