| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241 |
- // facet.go - the "facet" topology-override kind (NETPULSE-ONE-LEGION).
- //
- // An external agent push is contractually a router, so a pusher that
- // describes an EXISTING host (the RKE2 agent on the legion box) mints a
- // box for a machine the fleet already draws - two representations of one
- // host is a lie on the map. A facet override says: the target row (agent
- // slug, non-MAC ids accepted per the #1485 precedent) is not a new box
- // but another face of the device whose MAC is the parent.
- //
- // The fold is a projection, not a data migration: polled state, alerts
- // and the agent ledger keep the full fleet; only the boxes the map and
- // the router list show drop the faceted row, and the parent device
- // carries a DeviceFacet pointer so the frontend renders the agent's
- // panels (system vitals + workloads) inside the device's detail view.
- //
- // Graceful-degradation rule: a facet only folds when BOTH ends are
- // present - the target router in the list and the parent device in the
- // census. A facet that cannot render leaves the box standing (a box is
- // honest; a swallowed row is not), and no ghost box can reappear while
- // the override is enabled: staleness rides on DeviceFacet.Online, which
- // tracks the row's own status, so an offline agent badges the device
- // instead of resurrecting a second box.
- package adapters
- import (
- "strings"
- "github.com/gnacho/netpulse/agent/probe"
- )
- // facetWorkloadItemCap bounds the workload ITEMS projected into the facet
- // pointer. The topology payload ships one facet per faceted device on
- // every device list; 100+ pod names per host would ride every response.
- // Workloads keeps the true total; the canvas only ever grids a dozen.
- const facetWorkloadItemCap = 64
- // DeviceFacet is the facet pointer a parent device carries: which agent
- // row folds into it, under which label, and whether that agent is
- // currently pushing.
- type DeviceFacet struct {
- RouterID string `json:"routerId"`
- // Label is the panel header: the override's name when the admin set
- // one, otherwise the agent row's own display name.
- Label string `json:"label"`
- // Online mirrors the faceted router row's status so a stopped pusher
- // badges the device instead of drawing a box.
- Online bool `json:"online"`
- // Workloads is the agent's last reported guest census (count only -
- // the full list is detail data, fetched from the router's detail
- // endpoint when the panel opens). 0 with WorkloadsKnown false means
- // the agent never reported the section.
- Workloads int `json:"workloadCount,omitempty"`
- WorkloadsKnown bool `json:"workloadsKnown,omitempty"`
- // WorkloadItems is the bounded sample of the census the canvas grids
- // as CT chips under the host (the facet→hypervisor bridge,
- // FACET-TOPOLOGY-CANVAS). Capped at facetWorkloadItemCap - Workloads
- // stays the true total. Non-running items always survive the cap:
- // a down guest must stay findable in the sample, so the fill order
- // keeps every not-running item before trimming running ones.
- WorkloadItems []probe.WorkloadItem `json:"workloadItems,omitempty"`
- }
- // censusFunc reports, per agent id, the last workload census the polled
- // state holds: the raw items, their true count, and whether the agent
- // ever reported the section.
- type censusFunc func(routerID string) (items []probe.WorkloadItem, count int, ok bool)
- // foldFacetRouters applies enabled facet overrides to the view lists.
- // routers/devices may be nil (fold only the half the caller has).
- // census reports, per agent id, the last workload census the polled
- // state holds (ok=false = the agent never reported workloads).
- //
- // Returns NEW slices (never rewrites shared backing arrays, #1378 law):
- // routers without the folded targets, devices with Facet set on folded
- // parents. When nothing folds, the inputs are returned untouched.
- func foldFacetRouters(routers []Router, devices []Device, overrides []TopologyOverride,
- census censusFunc) ([]Router, []Device) {
- // Index enabled facets: target id (lowercased - targets may be router
- // slugs, and the #1485 lane already matches those case-insensitively)
- // → override. First enabled row per target wins (List is ordered by
- // enabled DESC, created ASC).
- facets := map[string]TopologyOverride{}
- for _, o := range overrides {
- if !o.Enabled || o.Kind != "facet" {
- continue
- }
- t := strings.ToLower(strings.TrimSpace(o.MAC))
- if t == "" || strings.TrimSpace(o.Parent) == "" {
- continue
- }
- if _, dup := facets[t]; !dup {
- facets[t] = o
- }
- }
- if len(facets) == 0 {
- return routers, devices
- }
- // A facet only folds onto a device that exists right now: parents
- // indexed by normalized MAC. When devices is nil (router-list-only
- // call) the caller has already resolved presence, so accept the fold.
- parentMACs := map[string]bool{}
- if devices != nil {
- for _, d := range devices {
- parentMACs[NormalizeMAC(d.MAC)] = true
- }
- }
- folded := map[string]*DeviceFacet{} // parent MAC → facet pointer
- kept := make([]Router, 0, len(routers))
- for _, r := range routers {
- ov, isTarget := facets[strings.ToLower(r.ID)]
- parent := NormalizeMAC(strings.TrimSpace(ov.Parent))
- if isTarget && (devices == nil || parentMACs[parent]) {
- online := r.Status == "online"
- f := &DeviceFacet{RouterID: r.ID, Label: ov.Name, Online: online}
- if f.Label == "" {
- f.Label = r.Name
- }
- if census != nil {
- if items, n, ok := census(r.ID); ok {
- f.Workloads, f.WorkloadsKnown = n, true
- f.WorkloadItems = capWorkloadSample(items, facetWorkloadItemCap)
- }
- }
- folded[parent] = f
- continue // folded: the box is not drawn
- }
- kept = append(kept, r)
- }
- if len(folded) == 0 {
- return routers, devices
- }
- var devOut []Device
- if devices != nil {
- devOut = make([]Device, len(devices))
- copy(devOut, devices)
- for i := range devOut {
- if f, ok := folded[NormalizeMAC(devOut[i].MAC)]; ok {
- cp := *f
- devOut[i].Facet = &cp
- }
- }
- }
- if len(routers) == len(kept) {
- return routers, devOut
- }
- return kept, devOut
- }
- // censusOfLastPolled reports the last workload census an agent pushed
- // (live state; ok=false when the agent never reported the section or the
- // census is older than the #2236 TTL - a dead pusher must not keep painting
- // facet counts and CT chips, only its offline badge).
- func (l *Live) censusOfLastPolled(id string) ([]probe.WorkloadItem, int, bool) {
- l.mu.Lock()
- defer l.mu.Unlock()
- p := l.lastPolled[id]
- if p == nil {
- return nil, 0, false
- }
- w := freshWorkloads(p.workloads, p.polledAt, l.nowMillis())
- if w == nil {
- return nil, 0, false
- }
- return w.Items, len(w.Items), true
- }
- // capWorkloadSample trims a census to `cap` items for the facet pointer
- // without hiding a problem: every not-running item is kept first (the
- // down-state needle must survive the cut - the canvas paints it in warn
- // and the tooltip counts it), then running ones fill the rest in census
- // order. The copy never aliases the polled slice's backing array (#1378
- // law: projections do not share live state).
- func capWorkloadSample(items []probe.WorkloadItem, max int) []probe.WorkloadItem {
- if len(items) <= max {
- out := make([]probe.WorkloadItem, len(items))
- copy(out, items)
- return out
- }
- out := make([]probe.WorkloadItem, 0, max)
- for _, w := range items {
- if !workloadRunning(w.State) {
- out = append(out, w)
- }
- }
- for _, w := range items {
- if len(out) >= max {
- break
- }
- if workloadRunning(w.State) {
- out = append(out, w)
- }
- }
- return out
- }
- // workloadRunning is the canvas honesty rule: anything the pusher did
- // not report as running (case-insensitive; "Up"/"ok" accepted for
- // producers that speak docker) is a warning chip.
- func workloadRunning(state string) bool {
- switch strings.ToLower(state) {
- case "running", "up", "ok":
- return true
- }
- return false
- }
- // foldFacetedRouters drops agent rows the fleet declared as facets of an
- // existing device from a router list, checking parent presence against
- // the attributed device census (a facet whose host is gone keeps its
- // box - the fold never swallows a row it cannot render).
- func (l *Live) foldFacetedRouters(routers []Router) []Router {
- if l.db == nil {
- return routers
- }
- ov := loadTopologyOverrides(l.db)
- if len(ov) == 0 {
- return routers
- }
- r, _ := foldFacetRouters(routers, l.attributedDevices(), ov, l.censusOfLastPolled)
- return r
- }
- // foldFacetedDevices hangs the facet pointer on parent devices (the
- // router half is the caller's business).
- func (l *Live) foldFacetedDevices(devices []Device) []Device {
- if l.db == nil {
- return devices
- }
- ov := loadTopologyOverrides(l.db)
- if len(ov) == 0 {
- return devices
- }
- // The fold learns the facet's status and census from the ROUTER rows,
- // so the device half needs them too: pass the unfolded base list (the
- // nil-routers call would fold nothing - there would be no target).
- _, d := foldFacetRouters(l.routerRows(), devices, ov, l.censusOfLastPolled)
- return d
- }
|