Files
mirror-3x-ui/internal/web/service/node_fleet.go
T
Hamed ef99e67507 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
2026-12-03 04:19:48 +03:30

163 lines
5.7 KiB
Go

package service
import (
"encoding/json"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
type NodeFleetCounts struct {
InboundCount int `json:"inboundCount" example:"8"`
ClientCount int `json:"clientCount" example:"100"`
ActiveCount int `json:"activeCount" example:"90"`
DisabledCount int `json:"disabledCount" example:"8"`
DepletedCount int `json:"depletedCount" example:"2"`
OnlineCount int `json:"onlineCount" example:"20"`
}
type NodeMasterView struct {
Counts NodeFleetCounts `json:"counts"`
Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
XrayVersion string `json:"xrayVersion,omitempty" example:"26.1.1"`
PanelVersion string `json:"panelVersion,omitempty" example:"v3.12.0"`
XrayState string `json:"xrayState,omitempty" example:"running"`
XrayError string `json:"xrayError,omitempty"`
}
type NodeOverview struct {
Nodes []*NodeView `json:"nodes"`
Master NodeMasterView `json:"master"`
Fleet NodeFleetCounts `json:"fleet"`
}
func (s *NodeService) GetNodeOverview(local *Status) (*NodeOverview, error) {
nodes, master, fleet, err := s.getNodeTreeWithCounts(true)
if err != nil {
return nil, err
}
overview := &NodeOverview{Nodes: nodeTreeViews(nodes), Master: NodeMasterView{Counts: master}, Fleet: fleet}
if len(nodes) > 0 && local != nil {
overview.Master.XrayVersion = local.Xray.Version
overview.Master.PanelVersion = local.PanelVersion
overview.Master.XrayState = string(local.Xray.State)
overview.Master.XrayError = local.Xray.ErrorMsg
// Use the same typed projection and availability checks as remote heartbeats.
if payload, err := json.Marshal(local); err == nil {
var metrics nodeStatusMetrics
if json.Unmarshal(payload, &metrics) == nil && !local.T.IsZero() {
overview.Master.Telemetry = liveNodeTelemetry(&model.Node{
Enable: true, Status: "online", Telemetry: metrics.telemetry(local.T),
}, time.Now())
}
}
}
return overview, nil
}
type nodeFleetStatsRow struct {
Fleet int
Host string
NodeFleetCounts
}
func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string, overview bool) (NodeFleetCounts, NodeFleetCounts, error) {
ambiguous := ambiguousNodeGuids(nodes, selfGUID)
// Always reserve the local GUID, including when an old topology advertises a loop.
ambiguous[selfGUID] = struct{}{}
ambiguous[""] = struct{}{}
ambiguousGUIDs := make([]string, 0, len(ambiguous))
for guid := range ambiguous {
ambiguousGUIDs = append(ambiguousGUIDs, guid)
}
slices.Sort(ambiguousGUIDs)
fleetClients, fleetInbounds := "", ""
if overview {
fleetClients = "UNION ALL SELECT 1, '', id FROM clients"
fleetInbounds = "UNION ALL SELECT 1, '', COUNT(*) FROM hosted"
}
var rows []nodeFleetStatsRow
err := database.GetDB().Raw(`
WITH hosted AS (
SELECT i.id, CASE
WHEN i.node_id IS NULL THEN ''
WHEN COALESCE(i.origin_node_guid, '') NOT IN ? THEN i.origin_node_guid
WHEN COALESCE(i.origin_node_guid, '') = '' AND COALESCE(n.guid, '') NOT IN ? THEN n.guid
ELSE 'node:' || CAST(i.node_id AS TEXT)
END AS host
FROM inbounds i LEFT JOIN nodes n ON n.id = i.node_id
WHERE (? OR i.node_id IS NOT NULL)
), memberships AS (
SELECT DISTINCT hosted.host, ci.client_id
FROM hosted JOIN client_inbounds ci ON ci.inbound_id = hosted.id
), scoped AS (
SELECT 0 AS fleet, host, client_id FROM memberships
`+fleetClients+`
), classified AS (
SELECT s.fleet, s.host, CASE
WHEN (ct.expiry_time > 0 AND ct.expiry_time <= ?)
OR (ct.total > 0 AND ct.up + ct.down >= ct.total) THEN 'depleted'
WHEN COALESCE(c.enable, FALSE) = FALSE THEN 'disabled'
ELSE 'active' END AS state
FROM scoped s JOIN clients c ON c.id = s.client_id
LEFT JOIN client_traffics ct ON ct.email = c.email
), clients_by_host AS (
SELECT fleet, host, COUNT(*) AS client_count,
COUNT(*) FILTER (WHERE state = 'active') AS active_count,
COUNT(*) FILTER (WHERE state = 'disabled') AS disabled_count,
COUNT(*) FILTER (WHERE state = 'depleted') AS depleted_count
FROM classified GROUP BY fleet, host
), inbound_counts AS (
SELECT 0 AS fleet, host, COUNT(*) AS inbound_count FROM hosted GROUP BY host
`+fleetInbounds+`
)
SELECT i.fleet, i.host, i.inbound_count, c.client_count, c.active_count, c.disabled_count, c.depleted_count
FROM inbound_counts i LEFT JOIN clients_by_host c ON c.fleet = i.fleet AND c.host = i.host
`, ambiguousGUIDs, ambiguousGUIDs, overview, time.Now().UnixMilli()).Scan(&rows).Error
if err != nil {
return NodeFleetCounts{}, NodeFleetCounts{}, err
}
byHost := make(map[string]NodeFleetCounts, len(rows))
var fleet NodeFleetCounts
for _, row := range rows {
if row.Fleet == 1 {
fleet = row.NodeFleetCounts
} else {
byHost[row.Host] = row.NodeFleetCounts
}
}
master := byHost[""]
online := s.onlineEmailsByGuid()
uniqueOnline := make(map[string]struct{})
if overview {
if process := currentXrayProcess(); process != nil {
for _, email := range process.GetLocalOnlineClients() {
uniqueOnline[email] = struct{}{}
}
}
}
master.OnlineCount = len(uniqueOnline)
totalOnline := (&InboundService{}).GetNodeOnlineTotals()
for _, node := range nodes {
guid := effectiveNodeGuid(node, ambiguous)
stats := byHost[guid]
node.InboundCount = stats.InboundCount
node.ClientCount = stats.ClientCount
node.ActiveCount = stats.ActiveCount
node.DisabledCount = stats.DisabledCount
node.DepletedCount = stats.DepletedCount
node.OnlineCount = len(online[guid])
node.OnlineTotalCount = totalOnline[node.Id]
if overview {
for email := range online[guid] {
uniqueOnline[email] = struct{}{}
}
}
}
fleet.OnlineCount = len(uniqueOnline)
return master, fleet, nil
}