feat(nodes): add fleet monitoring and implement the Penpot layout (#7342)

Expose sampled CPU topology, absolute RAM, TCP/UDP counts, load averages and network throughput through the existing heartbeat and descendant contracts, preserving measured zero versus unavailable values. Add an explicit nullable telemetry migration and freshness/availability checks.

Provide read-only All nodes and Master rows with deduplicated host/client totals, grouped SQL aggregation and reporting coverage. Preserve known descendants during parent outages and prefer the freshest valid observation of shared GUIDs. Keep the ordinary heartbeat broadcast free of fleet-wide totals.

Implement the approved compact Penpot-inspired Nodes layout, responsive stacked details, status diagnostics and existing remote actions. Preserve cached rows, search and controls on overview refresh failures. By maintainer decision, hide both system rows when no remote nodes are registered.

Final review of 44ed457985: no outstanding HIGH or MEDIUM findings. CI and Docs CI passed (13 jobs; 2342 frontend tests in 269 files), including Go/race and mixed-version node E2E. Feature-specific PostgreSQL regression execution was not independently verified in the selected CI logs. See https://github.com/MHSanaei/3x-ui/pull/7342#issuecomment-7363599190.

Closes #7335
Closes #7336
Closes #7337
This commit is contained in:
Hamed
2026-12-03 04:19:48 +03:30
committed by GitHub
parent 0afa11ddff
commit ef99e67507
64 changed files with 4710 additions and 1608 deletions
+87 -122
View File
@@ -42,6 +42,9 @@ func (s *NodeService) LocalDescendants() ([]model.NodeSummary, error) {
XrayVersion: n.XrayVersion,
XrayState: n.XrayState,
XrayError: n.XrayError,
BasePath: n.BasePath,
Enabled: &n.Enable,
Telemetry: liveNodeTelemetry(n, time.Now()),
})
}
return out, nil
@@ -71,6 +74,12 @@ func (s *NodeService) RefreshDescendants(ctx context.Context, n *model.Node) {
if err != nil {
return
}
now := time.Now().UnixMilli()
for i := range summaries {
if sample := summaries[i].Telemetry; sample != nil && sample.SampleAgeMillis != nil {
sample.SampledAt = now - min(max(0, *sample.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
}
}
nodeDescendantsMu.Lock()
if len(summaries) == 0 {
delete(nodeDescendantsCache, n.Id)
@@ -80,39 +89,74 @@ func (s *NodeService) RefreshDescendants(ctx context.Context, n *model.Node) {
nodeDescendantsMu.Unlock()
}
// ClearDescendants drops a node's cached sub-node summaries (its probe failed).
func (s *NodeService) ClearDescendants(nodeID int) {
// MarkDescendantsUnreachable keeps host identities while invalidating the last observations.
func (s *NodeService) MarkDescendantsUnreachable(nodeID int) {
nodeDescendantsMu.Lock()
delete(nodeDescendantsCache, nodeID)
for i := range nodeDescendantsCache[nodeID] {
nodeDescendantsCache[nodeID][i] = unavailableDescendant(nodeDescendantsCache[nodeID][i])
}
nodeDescendantsMu.Unlock()
}
// RetainEnabledNodeDescendants drops sub-nodes learned from nodes the heartbeat no
// longer probes: disabled ones it skips, deleted ones missing from nodes.
func (s *NodeService) RetainEnabledNodeDescendants(nodes []*model.Node) {
func unavailableDescendant(summary model.NodeSummary) model.NodeSummary {
summary.Status = "unknown"
summary.Telemetry = nil
summary.XrayState = ""
summary.XrayError = ""
return summary
}
// PruneNodeDescendants removes deleted branches and invalidates disabled branches' samples.
func (s *NodeService) PruneNodeDescendants(nodes []*model.Node) {
enabled := make(map[int]bool, len(nodes))
for _, n := range nodes {
enabled[n.Id] = n.Enable
}
nodeDescendantsMu.Lock()
for nodeID := range nodeDescendantsCache {
if !enabled[nodeID] {
if active, registered := enabled[nodeID]; !registered {
delete(nodeDescendantsCache, nodeID)
} else if !active {
for i, summary := range nodeDescendantsCache[nodeID] {
nodeDescendantsCache[nodeID][i] = unavailableDescendant(summary)
}
}
}
nodeDescendantsMu.Unlock()
}
func cachedDescendants() []model.NodeSummary {
func cachedDescendants(nodes []*model.Node) []model.NodeSummary {
nodeDescendantsMu.RLock()
defer nodeDescendantsMu.RUnlock()
out := make([]model.NodeSummary, 0)
for _, list := range nodeDescendantsCache {
out = append(out, list...)
for _, parent := range nodes {
for _, summary := range nodeDescendantsCache[parent.Id] {
if !parent.Enable || parent.Status == "offline" {
summary = unavailableDescendant(summary)
}
out = append(out, summary)
}
}
return out
}
func preferDescendantObservation(candidate, current *model.Node, now time.Time) bool {
next, previous := liveNodeTelemetry(candidate, now), liveNodeTelemetry(current, now)
if next != nil {
return previous == nil || next.SampledAt > previous.SampledAt
}
if previous != nil {
return false
}
candidateOnline := candidate.Enable && candidate.Status == "online"
currentOnline := current.Enable && current.Status == "online"
if candidateOnline != currentOnline {
return candidateOnline
}
// A known state is more informative than the placeholder from a lost branch.
return current.Status == "unknown" && candidate.Status != "unknown"
}
// GetNodeTree returns the direct nodes plus any transitive sub-nodes learned
// from them, with per-GUID counts so each node shows only the inbounds/online
// it physically hosts (#4983). Direct nodes carry the master's own GUID as
@@ -120,9 +164,14 @@ func cachedDescendants() []model.NodeSummary {
// nodes are read-only projections (Id == 0). Used by the Nodes page and the
// heartbeat broadcast — never for probing/syncing, which stay on ListOperational.
func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
nodes, _, _, err := s.getNodeTreeWithCounts(false)
return nodes, err
}
func (s *NodeService) getNodeTreeWithCounts(overview bool) ([]*model.Node, NodeFleetCounts, NodeFleetCounts, error) {
nodes, err := s.ListOperational()
if err != nil {
return nodes, err
if err != nil || len(nodes) == 0 {
return nodes, NodeFleetCounts{}, NodeFleetCounts{}, err
}
selfGuid, _ := (&SettingService{}).GetPanelGuid()
directGuids := make(map[string]struct{}, len(nodes))
@@ -133,20 +182,17 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
}
}
seen := make(map[string]struct{})
now := time.Now()
indexByGUID := make(map[string]int)
var transitive []*model.Node
for _, sum := range cachedDescendants() {
if sum.Guid == "" {
for _, sum := range cachedDescendants(nodes) {
if sum.Guid == "" || sum.Guid == selfGuid {
continue
}
if _, ok := directGuids[sum.Guid]; ok {
continue // already shown as a direct node
}
if _, ok := seen[sum.Guid]; ok {
continue
}
seen[sum.Guid] = struct{}{}
transitive = append(transitive, &model.Node{
descendant := &model.Node{
Guid: sum.Guid,
ParentGuid: sum.ParentGuid,
Name: sum.Name,
@@ -161,23 +207,24 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
XrayState: sum.XrayState,
XrayError: sum.XrayError,
Transitive: true,
})
}
if len(transitive) == 0 {
if len(nodes) > 0 {
s.enrichDashboardStats(database.GetDB(), nodes)
Enable: sum.Enabled == nil || *sum.Enabled,
BasePath: sum.BasePath,
Telemetry: sum.Telemetry,
}
return nodes, nil
if index, ok := indexByGUID[sum.Guid]; ok {
// Replace in place to preserve row order. Equal observations keep
// the first parent (ListOperational orders parents by ascending ID).
if preferDescendantObservation(descendant, transitive[index], now) {
transitive[index] = descendant
}
continue
}
indexByGUID[sum.Guid] = len(transitive)
transitive = append(transitive, descendant)
}
if len(nodes) > 0 {
s.populateClientCounts(database.GetDB(), nodes)
}
all := make([]*model.Node, 0, len(nodes)+len(transitive))
all = append(all, nodes...)
all = append(all, transitive...)
s.recountByGuid(all, selfGuid)
return all, nil
all := append(nodes, transitive...)
master, fleet, err := s.countNodeFleet(all, selfGuid, overview)
return all, master, fleet, err
}
func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
@@ -185,6 +232,10 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
if err != nil {
return nil, err
}
return nodeTreeViews(nodes), nil
}
func nodeTreeViews(nodes []*model.Node) []*NodeView {
views := toNodeViews(nodes)
now := time.Now()
for _, view := range views {
@@ -192,91 +243,5 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
view.HeartbeatAgeMillis = new(max(0, now.Sub(time.Unix(view.LastHeartbeat, 0)).Milliseconds()))
}
}
return views, nil
}
// recountByGuid recomputes InboundCount/OnlineCount/DepletedCount for every node
// in the tree, keyed by the GUID that physically hosts each inbound, so a direct
// node shows only its own inbounds and each transitive node shows its own
// (#4983). In a flat topology the per-GUID and per-node-id counts coincide, so
// this only changes behaviour once a transitive node exists.
func (s *NodeService) recountByGuid(nodes []*model.Node, selfGuid string) {
db := database.GetDB()
type ibRow struct {
Id int
NodeID *int `gorm:"column:node_id"`
OriginNodeGuid string `gorm:"column:origin_node_guid"`
}
var ibRows []ibRow
if err := db.Table("inbounds").Select("id, node_id, origin_node_guid").Scan(&ibRows).Error; err != nil {
return
}
ambiguous := ambiguousNodeGuids(nodes, selfGuid)
effByInbound := make(map[int]string, len(ibRows))
inboundCountByGuid := make(map[string]int)
for _, r := range ibRows {
guid := r.OriginNodeGuid
if guid == "" {
if r.NodeID != nil {
guid = synthNodeGuid(*r.NodeID)
} else {
guid = selfGuid
}
} else if r.NodeID != nil {
// Origin still holds an ambiguous GUID (cloned server / master-shared,
// not yet re-attributed): bucket under the hosting node's unique id so
// the clones don't merge.
if _, bad := ambiguous[guid]; bad {
guid = synthNodeGuid(*r.NodeID)
}
}
effByInbound[r.Id] = guid
inboundCountByGuid[guid]++
}
// Classify by EMAIL (not the stale client_traffics.inbound_id) and bucket
// each client under its inbound's effective attribution GUID, deduping a
// client attached to several inbounds under the same GUID.
depletedByGuid := make(map[string]int)
disabledByGuid := make(map[string]int)
activeByGuid := make(map[string]int)
if statuses, err := s.nodeClientStatuses(); err == nil {
seen := make(map[string]map[int]struct{})
for _, st := range statuses {
guid, ok := effByInbound[st.InboundID]
if !ok {
continue
}
clientsSeen := seen[guid]
if clientsSeen == nil {
clientsSeen = make(map[int]struct{})
seen[guid] = clientsSeen
}
if _, dup := clientsSeen[st.ClientID]; dup {
continue
}
clientsSeen[st.ClientID] = struct{}{}
switch {
case st.Depleted:
depletedByGuid[guid]++
case st.Disabled:
disabledByGuid[guid]++
default:
activeByGuid[guid]++
}
}
}
onlineByGuid := s.onlineEmailsByGuid()
onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
for _, n := range nodes {
guid := effectiveNodeGuid(n, ambiguous)
n.InboundCount = inboundCountByGuid[guid]
n.OnlineCount = len(onlineByGuid[guid])
// Keyed by node id, so a transitive sub-node (id 0) never has one.
n.OnlineTotalCount = onlineTotals[n.Id]
n.DepletedCount = depletedByGuid[guid]
n.DisabledCount = disabledByGuid[guid]
n.ActiveCount = activeByGuid[guid]
}
return views
}