facet.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // facet.go - the "facet" topology-override kind (NETPULSE-ONE-LEGION).
  2. //
  3. // An external agent push is contractually a router, so a pusher that
  4. // describes an EXISTING host (the RKE2 agent on the legion box) mints a
  5. // box for a machine the fleet already draws - two representations of one
  6. // host is a lie on the map. A facet override says: the target row (agent
  7. // slug, non-MAC ids accepted per the #1485 precedent) is not a new box
  8. // but another face of the device whose MAC is the parent.
  9. //
  10. // The fold is a projection, not a data migration: polled state, alerts
  11. // and the agent ledger keep the full fleet; only the boxes the map and
  12. // the router list show drop the faceted row, and the parent device
  13. // carries a DeviceFacet pointer so the frontend renders the agent's
  14. // panels (system vitals + workloads) inside the device's detail view.
  15. //
  16. // Graceful-degradation rule: a facet only folds when BOTH ends are
  17. // present - the target router in the list and the parent device in the
  18. // census. A facet that cannot render leaves the box standing (a box is
  19. // honest; a swallowed row is not), and no ghost box can reappear while
  20. // the override is enabled: staleness rides on DeviceFacet.Online, which
  21. // tracks the row's own status, so an offline agent badges the device
  22. // instead of resurrecting a second box.
  23. package adapters
  24. import (
  25. "strings"
  26. "github.com/gnacho/netpulse/agent/probe"
  27. )
  28. // facetWorkloadItemCap bounds the workload ITEMS projected into the facet
  29. // pointer. The topology payload ships one facet per faceted device on
  30. // every device list; 100+ pod names per host would ride every response.
  31. // Workloads keeps the true total; the canvas only ever grids a dozen.
  32. const facetWorkloadItemCap = 64
  33. // DeviceFacet is the facet pointer a parent device carries: which agent
  34. // row folds into it, under which label, and whether that agent is
  35. // currently pushing.
  36. type DeviceFacet struct {
  37. RouterID string `json:"routerId"`
  38. // Label is the panel header: the override's name when the admin set
  39. // one, otherwise the agent row's own display name.
  40. Label string `json:"label"`
  41. // Online mirrors the faceted router row's status so a stopped pusher
  42. // badges the device instead of drawing a box.
  43. Online bool `json:"online"`
  44. // Workloads is the agent's last reported guest census (count only -
  45. // the full list is detail data, fetched from the router's detail
  46. // endpoint when the panel opens). 0 with WorkloadsKnown false means
  47. // the agent never reported the section.
  48. Workloads int `json:"workloadCount,omitempty"`
  49. WorkloadsKnown bool `json:"workloadsKnown,omitempty"`
  50. // WorkloadItems is the bounded sample of the census the canvas grids
  51. // as CT chips under the host (the facet→hypervisor bridge,
  52. // FACET-TOPOLOGY-CANVAS). Capped at facetWorkloadItemCap - Workloads
  53. // stays the true total. Non-running items always survive the cap:
  54. // a down guest must stay findable in the sample, so the fill order
  55. // keeps every not-running item before trimming running ones.
  56. WorkloadItems []probe.WorkloadItem `json:"workloadItems,omitempty"`
  57. }
  58. // censusFunc reports, per agent id, the last workload census the polled
  59. // state holds: the raw items, their true count, and whether the agent
  60. // ever reported the section.
  61. type censusFunc func(routerID string) (items []probe.WorkloadItem, count int, ok bool)
  62. // foldFacetRouters applies enabled facet overrides to the view lists.
  63. // routers/devices may be nil (fold only the half the caller has).
  64. // census reports, per agent id, the last workload census the polled
  65. // state holds (ok=false = the agent never reported workloads).
  66. //
  67. // Returns NEW slices (never rewrites shared backing arrays, #1378 law):
  68. // routers without the folded targets, devices with Facet set on folded
  69. // parents. When nothing folds, the inputs are returned untouched.
  70. func foldFacetRouters(routers []Router, devices []Device, overrides []TopologyOverride,
  71. census censusFunc) ([]Router, []Device) {
  72. // Index enabled facets: target id (lowercased - targets may be router
  73. // slugs, and the #1485 lane already matches those case-insensitively)
  74. // → override. First enabled row per target wins (List is ordered by
  75. // enabled DESC, created ASC).
  76. facets := map[string]TopologyOverride{}
  77. for _, o := range overrides {
  78. if !o.Enabled || o.Kind != "facet" {
  79. continue
  80. }
  81. t := strings.ToLower(strings.TrimSpace(o.MAC))
  82. if t == "" || strings.TrimSpace(o.Parent) == "" {
  83. continue
  84. }
  85. if _, dup := facets[t]; !dup {
  86. facets[t] = o
  87. }
  88. }
  89. if len(facets) == 0 {
  90. return routers, devices
  91. }
  92. // A facet only folds onto a device that exists right now: parents
  93. // indexed by normalized MAC. When devices is nil (router-list-only
  94. // call) the caller has already resolved presence, so accept the fold.
  95. parentMACs := map[string]bool{}
  96. if devices != nil {
  97. for _, d := range devices {
  98. parentMACs[NormalizeMAC(d.MAC)] = true
  99. }
  100. }
  101. folded := map[string]*DeviceFacet{} // parent MAC → facet pointer
  102. kept := make([]Router, 0, len(routers))
  103. for _, r := range routers {
  104. ov, isTarget := facets[strings.ToLower(r.ID)]
  105. parent := NormalizeMAC(strings.TrimSpace(ov.Parent))
  106. if isTarget && (devices == nil || parentMACs[parent]) {
  107. online := r.Status == "online"
  108. f := &DeviceFacet{RouterID: r.ID, Label: ov.Name, Online: online}
  109. if f.Label == "" {
  110. f.Label = r.Name
  111. }
  112. if census != nil {
  113. if items, n, ok := census(r.ID); ok {
  114. f.Workloads, f.WorkloadsKnown = n, true
  115. f.WorkloadItems = capWorkloadSample(items, facetWorkloadItemCap)
  116. }
  117. }
  118. folded[parent] = f
  119. continue // folded: the box is not drawn
  120. }
  121. kept = append(kept, r)
  122. }
  123. if len(folded) == 0 {
  124. return routers, devices
  125. }
  126. var devOut []Device
  127. if devices != nil {
  128. devOut = make([]Device, len(devices))
  129. copy(devOut, devices)
  130. for i := range devOut {
  131. if f, ok := folded[NormalizeMAC(devOut[i].MAC)]; ok {
  132. cp := *f
  133. devOut[i].Facet = &cp
  134. }
  135. }
  136. }
  137. if len(routers) == len(kept) {
  138. return routers, devOut
  139. }
  140. return kept, devOut
  141. }
  142. // censusOfLastPolled reports the last workload census an agent pushed
  143. // (live state; ok=false when the agent never reported the section or the
  144. // census is older than the #2236 TTL - a dead pusher must not keep painting
  145. // facet counts and CT chips, only its offline badge).
  146. func (l *Live) censusOfLastPolled(id string) ([]probe.WorkloadItem, int, bool) {
  147. l.mu.Lock()
  148. defer l.mu.Unlock()
  149. p := l.lastPolled[id]
  150. if p == nil {
  151. return nil, 0, false
  152. }
  153. w := freshWorkloads(p.workloads, p.polledAt, l.nowMillis())
  154. if w == nil {
  155. return nil, 0, false
  156. }
  157. return w.Items, len(w.Items), true
  158. }
  159. // capWorkloadSample trims a census to `cap` items for the facet pointer
  160. // without hiding a problem: every not-running item is kept first (the
  161. // down-state needle must survive the cut - the canvas paints it in warn
  162. // and the tooltip counts it), then running ones fill the rest in census
  163. // order. The copy never aliases the polled slice's backing array (#1378
  164. // law: projections do not share live state).
  165. func capWorkloadSample(items []probe.WorkloadItem, max int) []probe.WorkloadItem {
  166. if len(items) <= max {
  167. out := make([]probe.WorkloadItem, len(items))
  168. copy(out, items)
  169. return out
  170. }
  171. out := make([]probe.WorkloadItem, 0, max)
  172. for _, w := range items {
  173. if !workloadRunning(w.State) {
  174. out = append(out, w)
  175. }
  176. }
  177. for _, w := range items {
  178. if len(out) >= max {
  179. break
  180. }
  181. if workloadRunning(w.State) {
  182. out = append(out, w)
  183. }
  184. }
  185. return out
  186. }
  187. // workloadRunning is the canvas honesty rule: anything the pusher did
  188. // not report as running (case-insensitive; "Up"/"ok" accepted for
  189. // producers that speak docker) is a warning chip.
  190. func workloadRunning(state string) bool {
  191. switch strings.ToLower(state) {
  192. case "running", "up", "ok":
  193. return true
  194. }
  195. return false
  196. }
  197. // foldFacetedRouters drops agent rows the fleet declared as facets of an
  198. // existing device from a router list, checking parent presence against
  199. // the attributed device census (a facet whose host is gone keeps its
  200. // box - the fold never swallows a row it cannot render).
  201. func (l *Live) foldFacetedRouters(routers []Router) []Router {
  202. if l.db == nil {
  203. return routers
  204. }
  205. ov := loadTopologyOverrides(l.db)
  206. if len(ov) == 0 {
  207. return routers
  208. }
  209. r, _ := foldFacetRouters(routers, l.attributedDevices(), ov, l.censusOfLastPolled)
  210. return r
  211. }
  212. // foldFacetedDevices hangs the facet pointer on parent devices (the
  213. // router half is the caller's business).
  214. func (l *Live) foldFacetedDevices(devices []Device) []Device {
  215. if l.db == nil {
  216. return devices
  217. }
  218. ov := loadTopologyOverrides(l.db)
  219. if len(ov) == 0 {
  220. return devices
  221. }
  222. // The fold learns the facet's status and census from the ROUTER rows,
  223. // so the device half needs them too: pass the unfolded base list (the
  224. // nil-routers call would fold nothing - there would be no target).
  225. _, d := foldFacetRouters(l.routerRows(), devices, ov, l.censusOfLastPolled)
  226. return d
  227. }