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
+12
View File
@@ -141,6 +141,15 @@ func migrateNodeClientTrafficDippedWhileFrozenColumn(tx *gorm.DB) error {
return migrator.AddColumn(&model.NodeClientTraffic{}, "DippedWhileFrozen")
}
// Existing nodes start with NULL telemetry until their next successful heartbeat.
func migrateNodeTelemetryColumn(tx *gorm.DB) error {
migrator := tx.Migrator()
if !migrator.HasTable(&model.Node{}) || migrator.HasColumn(&model.Node{}, "telemetry") {
return nil
}
return migrator.AddColumn(&model.Node{}, "Telemetry")
}
func migrateClientKeepAliveRangeColumn() error {
migrator := db.Migrator()
if !migrator.HasTable(&model.ClientRecord{}) || migrator.HasColumn(&model.ClientRecord{}, "wg_keep_alive_range") {
@@ -171,6 +180,9 @@ func initModels() error {
if err := migrateNodeClientTrafficDippedWhileFrozenColumn(db); err != nil {
return err
}
if err := migrateNodeTelemetryColumn(db); err != nil {
return err
}
models := allModels()
for _, mdl := range models {
if IsPostgres() && postgresModelSettled(mdl) {
+10 -6
View File
@@ -922,10 +922,11 @@ type Node struct {
MemPct float64 `json:"memPct" example:"45.1"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
// Nil on legacy rows and responses: zero remains a valid measured value.
UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
LastError string `json:"lastError"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
Telemetry *NodeTelemetry `json:"telemetry,omitempty" gorm:"serializer:json;type:text"`
NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
LastError string `json:"lastError"`
// XrayState and XrayError are captured from the remote node's /panel/api/server/status
// during heartbeats. They let the central panel distinguish "panel API reachable"
@@ -980,8 +981,11 @@ type NodeSummary struct {
PanelVersion string `json:"panelVersion"`
XrayVersion string `json:"xrayVersion"`
// XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
XrayState string `json:"xrayState"`
XrayError string `json:"xrayError,omitempty"`
XrayState string `json:"xrayState"`
XrayError string `json:"xrayError,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
BasePath string `json:"basePath,omitempty"`
Telemetry *NodeTelemetry `json:"telemetry,omitempty"`
}
type ClientReverse struct {
+22
View File
@@ -0,0 +1,22 @@
package model
// NodeTelemetry describes one host sample. Nil metrics were not measured.
type NodeTelemetry struct {
SampledAt int64 `json:"sampledAt" example:"1700000000000"`
SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
ResourceScope string `json:"resourceScope,omitempty" example:"container"`
CpuPct *float64 `json:"cpuPct,omitempty" example:"12.5"`
PhysicalCores *int `json:"physicalCores,omitempty" example:"4"`
LogicalCores *int `json:"logicalCores,omitempty" example:"8"`
MemUsedBytes *uint64 `json:"memUsedBytes,omitempty" example:"2147483648"`
MemTotalBytes *uint64 `json:"memTotalBytes,omitempty" example:"4294967296"`
MemAvailableBytes *uint64 `json:"memAvailableBytes,omitempty" example:"1073741824"`
TCPCount *int `json:"tcpCount,omitempty" example:"75"`
UDPCount *int `json:"udpCount,omitempty" example:"12"`
Load1 *float64 `json:"load1,omitempty" example:"0.25"`
Load5 *float64 `json:"load5,omitempty" example:"0.18"`
Load15 *float64 `json:"load15,omitempty" example:"0.12"`
UptimeSecs *uint64 `json:"uptimeSecs,omitempty" example:"3600"`
NetUp *uint64 `json:"netUp,omitempty" example:"1024"`
NetDown *uint64 `json:"netDown,omitempty" example:"2048"`
}
@@ -0,0 +1,42 @@
package database
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestMigrateNodeTelemetryColumn(t *testing.T) {
initMigrateDB(t)
tx := GetDB().Begin()
if tx.Error != nil {
t.Fatal(tx.Error)
}
t.Cleanup(func() { tx.Rollback() })
node := model.Node{Name: "legacy", Address: "192.0.2.1", Port: 2053}
if err := tx.Create(&node).Error; err != nil {
t.Fatal(err)
}
if err := tx.Exec("ALTER TABLE nodes DROP COLUMN telemetry").Error; err != nil {
t.Fatal(err)
}
if err := migrateNodeTelemetryColumn(tx); err != nil {
t.Fatal(err)
}
var stored model.Node
if err := tx.First(&stored, node.Id).Error; err != nil || stored.Telemetry != nil || stored.Name != node.Name {
t.Fatalf("legacy row after migration: %+v, %v", stored, err)
}
sample := model.Node{Telemetry: &model.NodeTelemetry{SampledAt: 123, LogicalCores: new(8)}}
if err := tx.Model(&stored).Updates(sample).Error; err != nil {
t.Fatal(err)
}
if err := migrateNodeTelemetryColumn(tx); err != nil {
t.Fatal(err)
}
stored = model.Node{}
if err := tx.First(&stored, node.Id).Error; err != nil ||
stored.Telemetry == nil || stored.Telemetry.LogicalCores == nil || *stored.Telemetry.LogicalCores != 8 {
t.Fatalf("repeat migration lost saved telemetry: %+v, %v", stored.Telemetry, err)
}
}
+5
View File
@@ -38,6 +38,10 @@ func NewAPIController(g *gin.RouterGroup, router http.Handler) *APIController {
return a
}
func (a *APIController) LastStatus() *service.Status {
return a.serverController.serverService.LastStatus()
}
// requireMCPEnabled hides the MCP endpoint until the operator turns it on: it hands
// a token's whole API reach to whatever agent holds that token.
func (a *APIController) requireMCPEnabled(c *gin.Context) {
@@ -237,6 +241,7 @@ func (a *APIController) initRouter(g *gin.RouterGroup, router http.Handler) {
// Nodes API — multi-panel management
nodes := api.Group("/nodes")
a.nodeController = NewNodeController(nodes)
a.nodeController.localStatus = a.LastStatus
// Hosts API — per-inbound override endpoints for subscription links
hosts := api.Group("/hosts")
+11
View File
@@ -18,6 +18,7 @@ import (
type NodeController struct {
nodeService service.NodeService
xrayService service.XrayService
localStatus func() *service.Status
}
func NewNodeController(g *gin.RouterGroup) *NodeController {
@@ -28,6 +29,7 @@ func NewNodeController(g *gin.RouterGroup) *NodeController {
func (a *NodeController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/overview", a.overview)
g.GET("/get/:id", a.get)
g.GET("/webCert/:id", a.webCert)
@@ -112,6 +114,15 @@ func (a *NodeController) get(c *gin.Context) {
jsonObj(c, n, nil)
}
func (a *NodeController) overview(c *gin.Context) {
var local *service.Status
if a.localStatus != nil {
local = a.localStatus()
}
view, err := a.nodeService.GetNodeOverview(local)
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.list"), view, err)
}
// webCert returns the node's own web TLS certificate/key file paths so the
// inbound form's "Set Cert from Panel" can fill paths that exist on the node.
func (a *NodeController) webCert(c *gin.Context) {
+3 -1
View File
@@ -110,7 +110,9 @@ func (a *ServerController) startTask() {
}
// status returns the current server status information.
func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.serverService.CurrentStatus(), nil) }
func (a *ServerController) status(c *gin.Context) {
jsonObj(c, service.StatusWithSampleAge(a.serverService.CurrentStatus()), nil)
}
func (a *ServerController) getFail2banStatus(c *gin.Context) {
jsonObj(c, a.serverService.GetFail2banStatus(), nil)
@@ -6,6 +6,7 @@ import (
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/op/go-logging"
@@ -18,53 +19,43 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func transitiveGuids(t *testing.T) []string {
func transitiveNodes(t *testing.T) []*model.Node {
t.Helper()
tree, err := (&service.NodeService{}).GetNodeTree()
if err != nil {
t.Fatalf("GetNodeTree: %v", err)
}
var out []string
var out []*model.Node
for _, n := range tree {
if n.Transitive {
out = append(out, n.Guid)
out = append(out, n)
}
}
return out
}
// The heartbeat skips a disabled node and never sees a deleted one, so the
// sub-nodes it had learned from them stayed on the Nodes page for good.
func TestHeartbeatDropsSubNodesOfNodesItNoLongerProbes(t *testing.T) {
cases := []struct {
name string
retire func(t *testing.T, nodeID int)
}{
{"disabled", func(t *testing.T, nodeID int) {
if err := (&service.NodeService{}).SetEnable(nodeID, false); err != nil {
t.Fatalf("SetEnable: %v", err)
}
}},
{"deleted", func(t *testing.T, nodeID int) {
if err := (&service.NodeService{}).Delete(nodeID); err != nil {
t.Fatalf("Delete: %v", err)
}
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
func TestHeartbeatPreservesUnavailableDescendantsUntilParentIsDeleted(t *testing.T) {
for _, state := range []string{"offline", "disabled", "deleted"} {
t.Run(state, func(t *testing.T) {
xuilogger.InitLogger(logging.ERROR)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}}))
t.Cleanup(func() { runtime.SetManager(nil) })
svc := &service.NodeService{}
t.Cleanup(func() { svc.PruneNodeDescendants(nil) })
var offline atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "server/status"):
if offline.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
_, _ = w.Write([]byte(`{"success":true,"obj":{"panelGuid":"direct-guid","xray":{"state":"running"}}}`))
case strings.HasSuffix(r.URL.Path, "server/descendants"):
_, _ = w.Write([]byte(`{"success":true,"obj":[{"guid":"sub-guid","parentGuid":"direct-guid","name":"sub","status":"online"}]}`))
_, _ = w.Write([]byte(`{"success":true,"obj":[{"guid":"sub-guid","parentGuid":"direct-guid","name":"sub","status":"online","telemetry":{"sampledAt":1,"sampleAgeMillis":0,"cpuPct":25}}]}`))
default:
_, _ = w.Write([]byte(`{"success":true}`))
}
@@ -82,14 +73,30 @@ func TestHeartbeatDropsSubNodesOfNodesItNoLongerProbes(t *testing.T) {
hb := NewNodeHeartbeatJob()
hb.Run()
if got := transitiveGuids(t); len(got) != 1 || got[0] != "sub-guid" {
t.Fatalf("sub-nodes after first heartbeat = %v, want [sub-guid]", got)
if got := transitiveNodes(t); len(got) != 1 || got[0].Guid != "sub-guid" || got[0].Telemetry == nil {
t.Fatalf("missing live sub-node after first heartbeat: %v", got)
}
tc.retire(t, node.Id)
switch state {
case "offline":
offline.Store(true)
case "disabled":
if err := svc.SetEnable(node.Id, false); err != nil {
t.Fatal(err)
}
case "deleted":
if err := svc.Delete(node.Id); err != nil {
t.Fatal(err)
}
}
hb.Run()
if got := transitiveGuids(t); len(got) != 0 {
t.Fatalf("sub-nodes after the node was %s = %v, want none", tc.name, got)
got := transitiveNodes(t)
if state == "deleted" {
if len(got) != 0 {
t.Fatalf("deleted parent left sub-nodes: %v", got)
}
} else if len(got) != 1 || got[0].Guid != "sub-guid" || got[0].Status != "unknown" || got[0].Telemetry != nil {
t.Fatalf("%s parent should retain an unavailable sub-node: %+v", state, got)
}
})
}
+7 -7
View File
@@ -58,10 +58,7 @@ func (j *NodeHeartbeatJob) Run() {
logger.Warning("node heartbeat: load nodes failed:", err)
return
}
j.nodeService.RetainEnabledNodeDescendants(nodes)
if len(nodes) == 0 {
return
}
j.nodeService.PruneNodeDescendants(nodes)
sem := make(chan struct{}, nodeHeartbeatConcurrency)
var wg sync.WaitGroup
@@ -89,6 +86,10 @@ func (j *NodeHeartbeatJob) Run() {
if !websocket.HasClients() {
return
}
if len(nodes) == 0 {
websocket.BroadcastNodes([]*service.NodeView{})
return
}
updated, err := j.nodeService.GetNodeTreeView()
if err != nil {
logger.Warning("node heartbeat: load nodes for broadcast failed:", err)
@@ -110,14 +111,13 @@ func (j *NodeHeartbeatJob) probeOne(n *model.Node) service.HeartbeatPatch {
logger.Warning("node heartbeat: update node", n.Id, "failed:", updErr)
}
// Learn the nodes this node manages so the panel can surface them as
// transitive sub-nodes (#4983). Fresh context — the probe budget above may
// be spent. Drop them when the node is unreachable.
// transitive sub-nodes (#4983). Use a fresh context after the status probe.
if patch.Status == "online" {
dctx, dcancel := context.WithTimeout(context.Background(), nodeHeartbeatRequestTimeout)
j.nodeService.RefreshDescendants(dctx, n)
dcancel()
} else {
j.nodeService.ClearDescendants(n.Id)
j.nodeService.MarkDescendantsUnreachable(n.Id)
}
return patch
}
+25 -171
View File
@@ -43,6 +43,7 @@ type HeartbeatPatch struct {
MemPct float64
UptimeSecs uint64
UnavailableMetrics []string
Telemetry *model.NodeTelemetry
// NetUp/NetDown are the node's current interface throughput (bytes/sec),
// summed over non-virtual interfaces, read from its status response.
NetUp uint64
@@ -139,154 +140,6 @@ func (s *NodeService) ListOperational() ([]*model.Node, error) {
return nodes, nil
}
func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) {
type clientCountRow struct {
NodeID int `gorm:"column:node_id"`
Count int `gorm:"column:count"`
}
var clientCounts []clientCountRow
if err := db.Raw(`
SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
FROM inbounds
JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
WHERE inbounds.node_id IS NOT NULL
GROUP BY inbounds.node_id
`).Scan(&clientCounts).Error; err == nil {
for _, row := range clientCounts {
for _, n := range nodes {
if n.Id == row.NodeID {
n.ClientCount = row.Count
break
}
}
}
}
}
func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) {
// Set before the early returns: a node with nothing synced still has clients online.
onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
for _, n := range nodes {
n.OnlineTotalCount = onlineTotals[n.Id]
}
type inboundRow struct {
Id int
NodeID int `gorm:"column:node_id"`
}
var inboundRows []inboundRow
if err := db.Table("inbounds").
Select("id, node_id").
Where("node_id IS NOT NULL").
Scan(&inboundRows).Error; err != nil {
return
}
if len(inboundRows) == 0 {
return
}
inboundsByNode := make(map[int][]int, len(nodes))
for _, row := range inboundRows {
inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
}
s.populateClientCounts(db, nodes)
depletedByNode := make(map[int]int)
disabledByNode := make(map[int]int)
activeByNode := make(map[int]int)
statuses, _ := s.nodeClientStatuses()
seen := make(map[int]map[int]struct{}, len(nodes))
for _, st := range statuses {
clientsSeen := seen[st.NodeID]
if clientsSeen == nil {
clientsSeen = make(map[int]struct{})
seen[st.NodeID] = clientsSeen
}
if _, dup := clientsSeen[st.ClientID]; dup {
// A client attached to several inbounds of one node counts once,
// matching the distinct ClientCount above.
continue
}
clientsSeen[st.ClientID] = struct{}{}
switch {
case st.Depleted:
depletedByNode[st.NodeID]++
case st.Disabled:
disabledByNode[st.NodeID]++
default:
activeByNode[st.NodeID]++
}
}
onlineByGuid := s.onlineEmailsByGuid()
selfGuid, _ := (&SettingService{}).GetPanelGuid()
ambiguous := ambiguousNodeGuids(nodes, selfGuid)
for _, n := range nodes {
n.InboundCount = len(inboundsByNode[n.Id])
n.DepletedCount = depletedByNode[n.Id]
n.DisabledCount = disabledByNode[n.Id]
n.ActiveCount = activeByNode[n.Id]
// Online is attributed to the node that physically hosts the client
// (by GUID): a client on a sub-node counts under the sub-node, not
// the intermediate node it syncs through (#4983).
n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
}
}
// nodeClientStatus is one node-hosted client's classification, carrying enough
// identity for callers to bucket it by node id or by attribution GUID.
type nodeClientStatus struct {
InboundID int
NodeID int
ClientID int
Depleted bool
Disabled bool
}
// nodeClientStatuses classifies every client attached to a node-hosted inbound as
// depleted / disabled / active, matching client_traffics by EMAIL rather than by
// inbound_id. client_traffics.inbound_id goes stale after an inbound is
// delete+recreated, so filtering by it silently drops most rows; the
// client_inbounds -> clients join is the reliable client set and the email join
// pulls each client's live counters. Precedence matches the inbound page:
// depleted (expired/exhausted) wins over disabled.
func (s *NodeService) nodeClientStatuses() ([]nodeClientStatus, error) {
type row struct {
InboundID int `gorm:"column:inbound_id"`
NodeID int `gorm:"column:node_id"`
ClientID int `gorm:"column:client_id"`
Enable bool `gorm:"column:enable"`
Total int64 `gorm:"column:total"`
Up int64 `gorm:"column:up"`
Down int64 `gorm:"column:down"`
ExpiryTime int64 `gorm:"column:expiry_time"`
}
var rows []row
if err := database.GetDB().Table("inbounds").
Select("inbounds.id AS inbound_id, inbounds.node_id AS node_id, clients.id AS client_id, " +
"clients.enable AS enable, ct.total AS total, ct.up AS up, ct.down AS down, ct.expiry_time AS expiry_time").
Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
Joins("LEFT JOIN client_traffics ct ON ct.email = clients.email").
Where("inbounds.node_id IS NOT NULL").
Scan(&rows).Error; err != nil {
return nil, err
}
now := time.Now().UnixMilli()
out := make([]nodeClientStatus, 0, len(rows))
for _, r := range rows {
st := nodeClientStatus{InboundID: r.InboundID, NodeID: r.NodeID, ClientID: r.ClientID}
expired := r.ExpiryTime > 0 && r.ExpiryTime <= now
exhausted := r.Total > 0 && r.Up+r.Down >= r.Total
switch {
case expired || exhausted:
st.Depleted = true
case !r.Enable:
st.Disabled = true
}
out = append(out, st)
}
return out, nil
}
func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
svc := InboundService{}
byGuid := svc.GetOnlineClientsByGuid()
@@ -997,8 +850,13 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
if err != nil {
return err
}
telemetry, err := json.Marshal(p.Telemetry)
if err != nil {
return err
}
updates := map[string]any{
"unavailable_metrics": string(unavailable),
"telemetry": string(telemetry),
"status": p.Status,
"last_heartbeat": p.LastHeartbeat,
"latency_ms": p.LatencyMs,
@@ -1024,7 +882,7 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
}
if p.Status == "online" {
now := time.Unix(p.LastHeartbeat, 0)
if !slices.Contains(p.UnavailableMetrics, "cpu") {
if !slices.Contains(p.UnavailableMetrics, "cpu") && (p.Telemetry == nil || p.Telemetry.CpuPct != nil) {
nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
}
nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
@@ -1366,21 +1224,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
Success bool `json:"success"`
Msg string `json:"msg"`
Obj *struct {
CpuPct float64 `json:"cpu"`
UnavailableMetrics []string `json:"unavailableMetrics"`
Mem struct {
Current uint64 `json:"current"`
Total uint64 `json:"total"`
} `json:"mem"`
nodeStatusMetrics
Xray struct {
Version string `json:"version"`
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
} `json:"xray"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
Uptime uint64 `json:"uptime"`
NetIO json.RawMessage `json:"netIO"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
} `json:"obj"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
@@ -1398,10 +1249,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
o := envelope.Obj
patch.CpuPct = o.CpuPct
patch.UnavailableMetrics = o.UnavailableMetrics
if o.Mem.Total > 0 {
patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
sample := o.telemetry(time.Now())
patch.Telemetry = sample
if sample.CpuPct != nil {
patch.CpuPct = *sample.CpuPct
}
if sample.MemTotalBytes != nil && sample.MemUsedBytes != nil {
patch.MemPct = float64(*sample.MemUsedBytes) * 100 / float64(*sample.MemTotalBytes)
}
patch.XrayVersion = o.Xray.Version
patch.XrayState = o.Xray.State
@@ -1412,16 +1267,15 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
patch.Guid = o.PanelGuid
patch.UptimeSecs = o.Uptime
var network map[string]json.RawMessage
_ = json.Unmarshal(o.NetIO, &network)
if sample.UptimeSecs != nil {
patch.UptimeSecs = *sample.UptimeSecs
}
for _, metric := range []struct {
key, direction string
value *uint64
}{{"netUp", "up", &patch.NetUp}, {"netDown", "down", &patch.NetDown}} {
var value *uint64
if json.Unmarshal(network[metric.direction], &value) == nil && value != nil {
*metric.value = *value
key string
value, measured *uint64
}{{"netUp", &patch.NetUp, sample.NetUp}, {"netDown", &patch.NetDown, sample.NetDown}} {
if metric.measured != nil {
*metric.value = *metric.measured
} else if !slices.Contains(patch.UnavailableMetrics, metric.key) {
patch.UnavailableMetrics = append(patch.UnavailableMetrics, metric.key)
}
+47 -44
View File
@@ -2,6 +2,7 @@ package service
import (
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
@@ -10,50 +11,51 @@ import (
// NodeView is the browser/API read contract for nodes. Credentials are
// write-only: responses expose only whether a node has a token configured.
type NodeView struct {
Id int `json:"id" example:"1"`
Name string `json:"name" example:"edge-1"`
Remark string `json:"remark" example:"Primary edge"`
Scheme string `json:"scheme" example:"https"`
Address string `json:"address" example:"node.example.com"`
Port int `json:"port" example:"2053"`
BasePath string `json:"basePath" example:"/"`
HasApiToken bool `json:"hasApiToken" example:"true"`
Enable bool `json:"enable" example:"true"`
AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
InboundSyncMode string `json:"inboundSyncMode" example:"all"`
InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
OutboundTag string `json:"outboundTag" example:"direct"`
Guid string `json:"guid" example:"node-guid"`
Status string `json:"status" example:"online"`
LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
LatencyMs int `json:"latencyMs" example:"42"`
XrayVersion string `json:"xrayVersion" example:"25.10.31"`
PanelVersion string `json:"panelVersion" example:"v3.x.x"`
CpuPct float64 `json:"cpuPct" example:"12.5"`
MemPct float64 `json:"memPct" example:"45.2"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
NetUp uint64 `json:"netUp" example:"2097152"`
NetDown uint64 `json:"netDown" example:"1048576"`
LastError string `json:"lastError" example:""`
XrayState string `json:"xrayState" example:"running"`
XrayError string `json:"xrayError" example:""`
ConfigDirty bool `json:"configDirty" example:"false"`
ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
InboundCount int `json:"inboundCount" example:"3"`
ClientCount int `json:"clientCount" example:"25"`
OnlineCount int `json:"onlineCount" example:"5"`
OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
ActiveCount int `json:"activeCount" example:"20"`
DisabledCount int `json:"disabledCount" example:"2"`
DepletedCount int `json:"depletedCount" example:"1"`
ParentGuid string `json:"parentGuid,omitempty" example:""`
Transitive bool `json:"transitive,omitempty" example:"false"`
CreatedAt int64 `json:"createdAt" example:"1700000000"`
UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
Id int `json:"id" example:"1"`
Name string `json:"name" example:"edge-1"`
Remark string `json:"remark" example:"Primary edge"`
Scheme string `json:"scheme" example:"https"`
Address string `json:"address" example:"node.example.com"`
Port int `json:"port" example:"2053"`
BasePath string `json:"basePath" example:"/"`
HasApiToken bool `json:"hasApiToken" example:"true"`
Enable bool `json:"enable" example:"true"`
AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
InboundSyncMode string `json:"inboundSyncMode" example:"all"`
InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
OutboundTag string `json:"outboundTag" example:"direct"`
Guid string `json:"guid" example:"node-guid"`
Status string `json:"status" example:"online"`
LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
LatencyMs int `json:"latencyMs" example:"42"`
XrayVersion string `json:"xrayVersion" example:"25.10.31"`
PanelVersion string `json:"panelVersion" example:"v3.x.x"`
CpuPct float64 `json:"cpuPct" example:"12.5"`
MemPct float64 `json:"memPct" example:"45.2"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
NetUp uint64 `json:"netUp" example:"2097152"`
NetDown uint64 `json:"netDown" example:"1048576"`
LastError string `json:"lastError" example:""`
XrayState string `json:"xrayState" example:"running"`
XrayError string `json:"xrayError" example:""`
ConfigDirty bool `json:"configDirty" example:"false"`
ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
InboundCount int `json:"inboundCount" example:"3"`
ClientCount int `json:"clientCount" example:"25"`
OnlineCount int `json:"onlineCount" example:"5"`
OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
ActiveCount int `json:"activeCount" example:"20"`
DisabledCount int `json:"disabledCount" example:"2"`
DepletedCount int `json:"depletedCount" example:"1"`
ParentGuid string `json:"parentGuid,omitempty" example:""`
Transitive bool `json:"transitive,omitempty" example:"false"`
CreatedAt int64 `json:"createdAt" example:"1700000000"`
UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
}
func toNodeView(n *model.Node) *NodeView {
@@ -86,6 +88,7 @@ func toNodeView(n *model.Node) *NodeView {
MemPct: n.MemPct,
UptimeSecs: n.UptimeSecs,
UnavailableMetrics: n.UnavailableMetrics,
Telemetry: liveNodeTelemetry(n, time.Now()),
NetUp: n.NetUp,
NetDown: n.NetDown,
LastError: n.LastError,
+162
View File
@@ -0,0 +1,162 @@
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
}
+343
View File
@@ -0,0 +1,343 @@
package service
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
)
func TestNodeOverviewWithoutNodesSkipsFleetReads(t *testing.T) {
setupConflictDB(t)
db := database.GetDB()
if err := db.Create(&model.ClientRecord{Email: "standalone@example.test"}).Error; err != nil {
t.Fatal(err)
}
queries := recordExecutedSQL(t, db)
view, err := (&NodeService{}).GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
if err != nil {
t.Fatal(err)
}
if len(*queries) != 1 {
t.Fatalf("standalone overview should only read the nodes table, queried %v", *queries)
}
if view.Nodes == nil || len(view.Nodes) != 0 ||
view.Master != (NodeMasterView{}) || view.Fleet != (NodeFleetCounts{}) {
t.Fatalf("standalone overview should be empty: %+v", view)
}
}
func TestNodeHeartbeatPublishesTelemetry(t *testing.T) {
svc, node, response := availabilityNodeFixture(t, `{"success":true,"obj":{"cpu":0,"cpuCores":4,"logicalPro":8,"mem":{"current":0,"total":4294967296},"tcpCount":0,"udpCount":7,"loads":[0,0.25,1.5],"netIO":{"up":0,"down":100}}}`)
read := func() map[string]any {
t.Helper()
patch, err := svc.Probe(t.Context(), node)
if err != nil {
t.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(node.Id, patch); err != nil {
t.Fatal(err)
}
nodes, err := svc.GetNodeTreeView()
if err != nil || len(nodes) != 1 {
t.Fatalf("views: %v, %v", nodes, err)
}
data, err := json.Marshal(nodes[0])
if err != nil {
t.Fatal(err)
}
var view struct{ Telemetry map[string]any }
if err := json.Unmarshal(data, &view); err != nil {
t.Fatal(err)
}
return view.Telemetry
}
first := read()
for key, want := range map[string]float64{"cpuPct": 0, "physicalCores": 4, "logicalCores": 8, "memUsedBytes": 0, "memTotalBytes": 4294967296, "tcpCount": 0, "udpCount": 7, "load1": 0, "load5": 0.25, "load15": 1.5, "netUp": 0, "netDown": 100} {
if got := first[key]; got != want {
t.Errorf("%s = %v, want %v", key, got, want)
}
}
response(`{"success":true,"obj":{"cpu":0,"resourceScope":"container","cpuCores":4,"logicalPro":2,"unavailableMetrics":["cpu","tcpCount"],"tcpCount":0,"loads":[1e999,-1,0]}}`)
partial := read()
for _, field := range []string{"cpuPct", "physicalCores", "tcpCount", "udpCount", "memUsedBytes", "load1", "load5", "netUp"} {
if got := partial[field]; got != nil {
t.Errorf("unavailable %s = %v", field, got)
}
}
if partial["logicalCores"] != float64(2) || partial["load15"] != float64(0) {
t.Fatalf("lost valid partial metrics: %v", partial)
}
if err := svc.UpdateHeartbeat(node.Id, HeartbeatPatch{Status: "offline", LastHeartbeat: time.Now().Unix()}); err != nil {
t.Fatal(err)
}
view, err := svc.GetViewById(node.Id)
if err != nil || view.Status != "offline" || view.Telemetry != nil {
t.Fatalf("offline transition: %+v, %v", view, err)
}
response(`{"success":true,"obj":{"sampleAgeMillis":31000,"cpu":5}}`)
if stale := read(); stale != nil {
t.Fatalf("stale sample treated as live: %v", stale)
}
response(`{"success":true,"obj":{"cpu":5}}`)
if recovered := read(); recovered["cpuPct"] != float64(5) || recovered["tcpCount"] != nil {
t.Fatalf("legacy node recovery: %v", recovered)
}
}
func TestNodeOverviewCountsHostMembershipsAndUniqueFleetClients(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_counts")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet.db"))
db := database.GetDB()
self, err := (&SettingService{}).GetPanelGuid()
if err != nil {
t.Fatal(err)
}
nodes := []model.Node{
{Name: "direct", Address: "192.0.2.1", Port: 2053, Guid: "direct"},
{Name: "cloned", Address: "192.0.2.2", Port: 2053, Guid: self},
}
if err := db.Create(&nodes).Error; err != nil {
t.Fatal(err)
}
nodeDescendantsMu.Lock()
nodeDescendantsCache[nodes[0].Id] = []model.NodeSummary{
{
Guid: "child", ParentGuid: "direct", Name: "child", Status: "online",
Telemetry: &model.NodeTelemetry{SampledAt: time.Now().UnixMilli(), UDPCount: new(0)},
},
}
nodeDescendantsMu.Unlock()
t.Cleanup(func() { (&NodeService{}).PruneNodeDescendants(nil) })
createInbound := func(tag string, nodeID *int, guid string) model.Inbound {
t.Helper()
ib := model.Inbound{Tag: tag, Port: 443, NodeID: nodeID, OriginNodeGuid: guid, Settings: `{"clients":[]}`}
if err := db.Create(&ib).Error; err != nil {
t.Fatal(err)
}
return ib
}
local := createInbound("local", nil, self)
direct := createInbound("direct", &nodes[0].Id, "direct")
child := createInbound("child", &nodes[0].Id, "child")
clone := createInbound("clone", &nodes[1].Id, self)
clients := []model.ClientRecord{{Email: "shared@test"}, {Email: "child@test"}, {Email: "orphan@test"}}
if err := db.Create(&clients).Error; err != nil {
t.Fatal(err)
}
links := []model.ClientInbound{
{ClientId: clients[0].Id, InboundId: local.Id},
{ClientId: clients[0].Id, InboundId: direct.Id},
{ClientId: clients[0].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: clone.Id},
}
if err := db.Create(&links).Error; err != nil {
t.Fatal(err)
}
status := &Status{T: time.Now(), LogicalPro: 8, CpuCores: 4, Cpu: 31, Loads: []float64{1, 2, 3}}
status.Mem.Total, status.Mem.Current = 8<<30, 2<<30
overview, err := (&NodeService{}).GetNodeOverview(status)
if err != nil {
t.Fatal(err)
}
if overview.Fleet.ClientCount != 3 || overview.Fleet.InboundCount != 4 ||
overview.Master.Counts.ClientCount != 1 || overview.Master.Counts.InboundCount != 1 {
t.Fatalf("wrong host counts: %+v", overview)
}
want := map[string]int{"direct": 1, "cloned": 1, "child": 2}
for _, node := range overview.Nodes {
if node.ClientCount != want[node.Name] || node.InboundCount != 1 {
t.Errorf("wrong placement for %s: %+v", node.Name, node)
}
if node.Transitive && (node.Telemetry == nil || node.Telemetry.UDPCount == nil || *node.Telemetry.UDPCount != 0) {
t.Fatalf("missing descendant's own sample: %+v", node)
}
delete(want, node.Name)
}
if len(want) != 0 || overview.Master.Telemetry == nil || *overview.Master.Telemetry.Load15 != 3 {
t.Fatalf("missing view rows or master sample: %+v, missing=%v", overview.Master, want)
}
queries := recordExecutedSQL(t, db)
tree, err := (&NodeService{}).GetNodeTree()
if err != nil || len(tree) != 3 {
t.Fatalf("unexpected node tree: %v, %v", tree, err)
}
if strings.Contains(strings.Join(*queries, "\n"), "id FROM clients") {
t.Fatalf("node listing should skip the fleet aggregate: %v", *queries)
}
for i, node := range tree {
if node.ClientCount != overview.Nodes[i].ClientCount {
t.Errorf("wrong list count for %s: %d", node.Name, node.ClientCount)
}
}
}
func TestNodeOverviewUsesBestDescendantObservation(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_descendants")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet-descendants.db"))
db := database.GetDB()
svc := &NodeService{}
t.Cleanup(func() { svc.PruneNodeDescendants(nil) })
parents := []model.Node{
{Name: "parent-a", Address: "192.0.2.1", Port: 2053, Guid: "parent-a", Enable: true},
{Name: "parent-b", Address: "192.0.2.2", Port: 2053, Guid: "parent-b", Enable: true},
}
if err := db.Create(&parents).Error; err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
status [2]string
age [2]time.Duration
wantParent int
wantStatus string
}{
{"lower ID offline", [2]string{"offline", "online"}, [2]time.Duration{}, 1, "online"},
{"higher ID offline", [2]string{"online", "offline"}, [2]time.Duration{}, 0, "online"},
{"lower ID disabled", [2]string{"disabled", "online"}, [2]time.Duration{}, 1, "online"},
{"higher ID disabled", [2]string{"online", "disabled"}, [2]time.Duration{}, 0, "online"},
{"both unavailable", [2]string{"offline", "disabled"}, [2]time.Duration{}, 0, "unknown"},
{"first sample stale", [2]string{"online", "online"}, [2]time.Duration{time.Minute, 0}, 1, "online"},
{"newer sample preferred", [2]string{"online", "online"}, [2]time.Duration{time.Second, 0}, 1, "online"},
{"equal samples keep lower ID", [2]string{"online", "online"}, [2]time.Duration{}, 0, "online"},
} {
t.Run(tc.name, func(t *testing.T) {
now := time.Now()
for i, parent := range parents {
if err := db.Model(&parent).Updates(map[string]any{
"enable": tc.status[i] != "disabled", "status": tc.status[i],
}).Error; err != nil {
t.Fatal(err)
}
nodeDescendantsMu.Lock()
nodeDescendantsCache[parent.Id] = []model.NodeSummary{{
Guid: "shared-child", Name: "shared-child", ParentGuid: parent.Guid, Status: "online",
Telemetry: &model.NodeTelemetry{SampledAt: now.Add(-tc.age[i]).UnixMilli(), CpuPct: new(float64(20 + i))},
}}
nodeDescendantsMu.Unlock()
}
view, err := svc.GetNodeOverview(nil)
if err != nil || len(view.Nodes) != 3 {
t.Fatalf("expected two parents and one child: %+v, %v", view, err)
}
child := view.Nodes[2]
if !child.Transitive || child.Guid != "shared-child" || child.ParentGuid != parents[tc.wantParent].Guid || child.Status != tc.wantStatus {
t.Fatalf("unexpected descendant observation: %+v", child)
}
if tc.wantStatus == "unknown" {
if child.Telemetry != nil {
t.Fatalf("unavailable descendant has telemetry: %+v", child.Telemetry)
}
} else if child.Telemetry == nil || child.Telemetry.CpuPct == nil || *child.Telemetry.CpuPct != float64(20+tc.wantParent) {
t.Fatalf("wrong descendant telemetry: %+v", child.Telemetry)
}
})
}
}
func BenchmarkNodeOverviewFleetScale(b *testing.B) {
dbtest.InitDB(b, filepath.Join(b.TempDir(), "fleet-scale.db"))
db := database.GetDB()
statusJSON := `{"success":true,"obj":{"cpu":25,"cpuCores":4,"logicalPro":8,"mem":{"current":2147483648,"total":8589934592,"available":6442450944},"tcpCount":132,"udpCount":22,"loads":[0.2,0.3,0.4],"uptime":90000,"netIO":{"up":12582912,"down":512}}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(statusJSON))
}))
b.Cleanup(server.Close)
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
nodes := make([]model.Node, 4)
for i := range nodes {
nodes[i] = model.Node{
Name: fmt.Sprint("remote-", i), Guid: fmt.Sprint("remote-guid-", i),
Scheme: "http", Address: u.Hostname(), Port: port, AllowPrivateAddress: true,
}
}
if err := db.Create(&nodes).Error; err != nil {
b.Fatal(err)
}
inbounds := make([]model.Inbound, 40)
for i := range inbounds {
inbounds[i] = model.Inbound{Tag: fmt.Sprint("inbound-", i), Port: 2000 + i, Settings: `{"clients":[]}`}
if i%5 != 0 {
node := &nodes[i%5-1]
inbounds[i].NodeID, inbounds[i].OriginNodeGuid = &node.Id, node.Guid
}
}
if err := db.CreateInBatches(&inbounds, 40).Error; err != nil {
b.Fatal(err)
}
clients := make([]model.ClientRecord, 7100)
for i := range clients {
clients[i].Email = fmt.Sprintf("client-%05d@test", i)
}
if err := db.CreateInBatches(&clients, 100).Error; err != nil {
b.Fatal(err)
}
links := make([]model.ClientInbound, 115000)
for i := range links {
client := clients[i%len(clients)]
ib := inbounds[(i/len(clients)+i)%len(inbounds)]
links[i] = model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}
}
if err := db.CreateInBatches(&links, 250).Error; err != nil {
b.Fatal(err)
}
svc := &NodeService{}
cycle := func() {
for i := range nodes {
patch, err := svc.Probe(b.Context(), &nodes[i])
if err != nil {
b.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(nodes[i].Id, patch); err != nil {
b.Fatal(err)
}
}
}
cycle()
b.Run("FourHeartbeatProbesAndWrites", func(b *testing.B) {
for b.Loop() {
cycle()
}
b.ReportMetric(float64(4*len(statusJSON)), "status-wire-B/cycle")
})
b.Run("OverviewAndJSON", func(b *testing.B) {
var payload []byte
for b.Loop() {
result, err := svc.GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
if err != nil {
b.Fatal(err)
}
payload, err = json.Marshal(result)
if err != nil || result.Fleet.ClientCount != 7100 {
b.Fatalf("fixture: %v", err)
}
}
b.ReportMetric(float64(len(payload)), "overview-wire-B/op")
})
}
@@ -117,7 +117,9 @@ func TestRecountByGuid_SplitsClonedNodesWithSharedGuid(t *testing.T) {
}
nodes := []*model.Node{n1, n2, n3}
svc.recountByGuid(nodes, selfGuid)
if _, _, err := svc.countNodeFleet(nodes, selfGuid, false); err != nil {
t.Fatal(err)
}
if n1.InboundCount != 1 || n2.InboundCount != 1 {
t.Errorf("cloned nodes must not share inbound counts: n1=%d n2=%d, want 1,1", n1.InboundCount, n2.InboundCount)
+123
View File
@@ -0,0 +1,123 @@
package service
import (
"encoding/json"
"math"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const nodeTelemetryFreshness = 30 * time.Second
func validNodeLoad(load float64) bool {
return load >= 0 && !math.IsInf(load, 0)
}
type nodeStatusMetrics struct {
Cpu json.RawMessage `json:"cpu"`
CpuCores json.RawMessage `json:"cpuCores"`
LogicalPro json.RawMessage `json:"logicalPro"`
Mem json.RawMessage `json:"mem"`
TcpCount json.RawMessage `json:"tcpCount"`
UdpCount json.RawMessage `json:"udpCount"`
Loads json.RawMessage `json:"loads"`
Uptime json.RawMessage `json:"uptime"`
NetIO json.RawMessage `json:"netIO"`
ResourceScope string `json:"resourceScope"`
SampleAgeMillis *int64 `json:"sampleAgeMillis"`
UnavailableMetrics []string `json:"unavailableMetrics"`
}
type nodeMetricNumber interface {
int | uint64 | float64
}
func readNodeMetric[T nodeMetricNumber](raw json.RawMessage, unavailable []string, key string) *T {
var v *T
if slices.Contains(unavailable, key) || json.Unmarshal(raw, &v) != nil || v == nil || *v < 0 {
return nil
}
return v
}
func (m nodeStatusMetrics) telemetry(received time.Time) *model.NodeTelemetry {
unavailable := m.UnavailableMetrics
var memory struct {
Current json.RawMessage `json:"current"`
Total json.RawMessage `json:"total"`
Available json.RawMessage `json:"available"`
}
var network struct {
Up json.RawMessage `json:"up"`
Down json.RawMessage `json:"down"`
}
var loads [3]json.RawMessage
_ = json.Unmarshal(m.Mem, &memory)
_ = json.Unmarshal(m.NetIO, &network)
_ = json.Unmarshal(m.Loads, &loads)
age := int64(0)
if m.SampleAgeMillis != nil {
age = min(max(0, *m.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
}
sample := &model.NodeTelemetry{
SampledAt: received.UnixMilli() - age,
ResourceScope: m.ResourceScope,
CpuPct: readNodeMetric[float64](m.Cpu, unavailable, "cpu"),
PhysicalCores: readNodeMetric[int](m.CpuCores, unavailable, "cpuCores"),
LogicalCores: readNodeMetric[int](m.LogicalPro, unavailable, "logicalPro"),
MemUsedBytes: readNodeMetric[uint64](memory.Current, unavailable, "mem"),
MemTotalBytes: readNodeMetric[uint64](memory.Total, unavailable, "mem"),
MemAvailableBytes: readNodeMetric[uint64](memory.Available, unavailable, "mem"),
TCPCount: readNodeMetric[int](m.TcpCount, unavailable, "tcpCount"),
UDPCount: readNodeMetric[int](m.UdpCount, unavailable, "udpCount"),
Load1: readNodeMetric[float64](loads[0], unavailable, "loads"),
Load5: readNodeMetric[float64](loads[1], unavailable, "loads"),
Load15: readNodeMetric[float64](loads[2], unavailable, "loads"),
UptimeSecs: readNodeMetric[uint64](m.Uptime, unavailable, "uptime"),
NetUp: readNodeMetric[uint64](network.Up, unavailable, "netUp"),
NetDown: readNodeMetric[uint64](network.Down, unavailable, "netDown"),
}
if sample.CpuPct != nil && *sample.CpuPct > 100 {
sample.CpuPct = nil
}
if sample.ResourceScope != "" || (sample.PhysicalCores != nil && *sample.PhysicalCores == 0) {
sample.PhysicalCores = nil
}
if sample.LogicalCores != nil && *sample.LogicalCores == 0 {
sample.LogicalCores = nil
}
if sample.MemTotalBytes == nil || *sample.MemTotalBytes == 0 ||
sample.MemUsedBytes == nil || *sample.MemUsedBytes > *sample.MemTotalBytes {
sample.MemUsedBytes, sample.MemTotalBytes, sample.MemAvailableBytes = nil, nil, nil
} else if sample.MemAvailableBytes != nil && *sample.MemAvailableBytes > *sample.MemTotalBytes {
sample.MemAvailableBytes = nil
}
return sample
}
func liveNodeTelemetry(node *model.Node, now time.Time) *model.NodeTelemetry {
sample := node.Telemetry
if sample == nil || !node.Enable || node.Status != "online" {
return nil
}
age := now.UnixMilli() - sample.SampledAt
if age < 0 || age >= nodeTelemetryFreshness.Milliseconds() {
return nil
}
view := *sample
view.SampleAgeMillis = &age
return &view
}
// StatusWithSampleAge publishes age relative to the sampler's clock.
func StatusWithSampleAge(status *Status) *Status {
if status == nil {
return nil
}
result := *status
result.SampleAgeMillis = new(max(0, time.Since(status.T).Milliseconds()))
return &result
}
+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
}
+10 -3
View File
@@ -71,6 +71,7 @@ type Status struct {
networkTrafficSample *networkTrafficSample `json:"-"`
ResourceScope string `json:"resourceScope,omitempty"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
T time.Time `json:"-"`
Cpu float64 `json:"cpu"`
@@ -78,8 +79,9 @@ type Status struct {
LogicalPro int `json:"logicalPro"`
CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
Mem struct {
Current uint64 `json:"current"`
Total uint64 `json:"total"`
Current uint64 `json:"current"`
Total uint64 `json:"total"`
Available *uint64 `json:"available,omitempty"`
} `json:"mem"`
Swap struct {
Current uint64 `json:"current"`
@@ -675,6 +677,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
util, err := s.sampleCPUUtilization()
if err != nil {
logger.Warning("get cpu percent failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "cpu")
} else {
status.Cpu = util
}
@@ -716,6 +719,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
upTime, err := host.Uptime()
if err != nil {
logger.Warning("get uptime failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "uptime")
} else {
status.Uptime = upTime
}
@@ -728,6 +732,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
} else {
status.Mem.Current = memInfo.Used
status.Mem.Total = memInfo.Total
status.Mem.Available = new(memInfo.Available)
}
if scoped == nil {
@@ -777,7 +782,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
avgState, err := load.Avg()
if err != nil {
logger.Warning("get load avg failed:", err)
} else {
} else if validNodeLoad(avgState.Load1) && validNodeLoad(avgState.Load5) && validNodeLoad(avgState.Load15) {
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
}
@@ -787,11 +792,13 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
status.TcpCount, err = sys.GetTCPCount()
if err != nil {
logger.Warning("get tcp connections failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "tcpCount")
}
status.UdpCount, err = sys.GetUDPCount()
if err != nil {
logger.Warning("get udp connections failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "udpCount")
}
s.resolvePublicIPsInBackground()
+2 -2
View File
@@ -51,7 +51,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
if got.ResourceScope != "container" || got.CpuCores != 2 || got.LogicalPro != 2 || got.CpuSpeedMhz != 0 || got.Swap.Total != 512<<20 || got.Swap.Current != 19357696 || got.Uptime != 52624 {
t.Fatalf("incorrect corrected resources: %+v", got)
}
if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || got.Mem.Available == nil || *got.Mem.Available != 1966080<<10 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
t.Fatalf("unrelated metric path changed: %+v", got)
}
if !slices.Equal(got.UnavailableMetrics, []string{"cpu"}) {
@@ -74,7 +74,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
t.Fatal(err)
}
native := svc.GetStatus(previous)
if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || native.Mem != got.Mem || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || !reflect.DeepEqual(native.Mem, got.Mem) || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
t.Fatalf("native regression: %+v", native)
}
}
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "ستتم إعادة تشغيل لوحة العقدة وخدمات الاشتراك وقد تتوقف مؤقتًا. يتطلب رمز API بصلاحية node-admin أو admin على العقدة.",
"addNode": "إضافة نود",
"editNode": "تحرير العقدة",
"totalNodes": "إجمالي النودز",
"onlineNodes": "متصل",
"offlineNodes": "غير متصل",
"avgLatency": "متوسط الكمون",
"onlineOnNode": "{synced} متصل على الاتصالات الواردة المستوردة إلى هذه اللوحة، و{total} متصل على العقدة إجمالاً",
"name": "الاسم",
"namePlaceholder": "مثال: de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "للقراءة فقط: نود تابع يتم الوصول إليه عبر {parent}. تتم إدارته من لوحة {parent} نفسها.",
"deleteConfirmTitle": "تحذف النود \"{name}\"؟",
"deleteConfirmContent": "ده هيوقّف مراقبة النود. البانل البعيد نفسه مش هيتأثر.",
"fleet": {
"subtitle": "راقب العقدة الرئيسية وسائر العقد المتصلة في عرض واحد.",
"allNodes": "جميع العُقد",
"master": "الرئيسية",
"thisPanel": "هذه اللوحة",
"fleetScope": "الرئيسية + {remotes} عُقد بعيدة",
"reporting": "{live} من {total} ترسل بيانات",
"registered": "{remotes} عقدة بعيدة · {total} إجمالاً",
"allStatuses": "جميع الحالات",
"open": "فتح",
"hardware": "المعالج / الذاكرة",
"cpuAverage": "متوسط المعالج",
"logicalCores": "{cores} معالج منطقي",
"availableMemory": "{size} متاح",
"remainingMemory": "{size} متبقٍ",
"connections": "TCP / UDP / الحمل",
"load": "الحمل",
"loadSum": "مجموع الحمل",
"loadWindow": "حمل النظام على مدار ١ و٥ و١٥ دقيقة",
"hostMetrics": "تُجمع السرعات والاتصالات لكل مضيف.",
"runtime": "وقت التشغيل",
"mixed": "إصدارات متعددة",
"history": "السجل",
"node": "العقدة",
"searchNodes": "البحث عن العقد…",
"panel": "اللوحة",
"uptimeShort": "مدة العمل",
"uptimeVaries": "تختلف مدة العمل حسب العقدة",
"clientRecords": "{records} سجل عميل",
"acrossNodes": "عبر {total} عقدة",
"connectionDetails": "تفاصيل الاتصال",
"footnote": "تُجمع القيم من العقد التي ترسل بيانات ({coverage}). الحمل في ١ و٥ و١٥ دقيقة، ويُجمع عبر العقد المبلِّغة. مرّر المؤشر فوق الحالة لعرض آخر اتصال وزمن الاستجابة."
},
"statusValues": {
"online": "متصل",
"offline": "غير متصل",
+33 -4
View File
@@ -1339,10 +1339,6 @@
"restartPanelContent": "The node panel and subscription services will restart and may be temporarily unavailable. Requires a node-admin or admin API token on the node.",
"addNode": "Add Node",
"editNode": "Edit Node",
"totalNodes": "Total Nodes",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Avg Latency",
"onlineOnNode": "{synced} online on inbounds imported into this panel, {total} online on the node in total",
"name": "Name",
"namePlaceholder": "e.g. de-frankfurt-1",
@@ -1400,6 +1396,39 @@
"subNodeTip": "Read-only: a downstream node reached through {parent}. Manage it from {parent}'s own panel.",
"deleteConfirmTitle": "Delete node \"{name}\"?",
"deleteConfirmContent": "This stops monitoring the node. The remote panel itself is unaffected.",
"fleet": {
"subtitle": "Monitor the master and every connected node in one view.",
"allNodes": "All nodes",
"master": "Master",
"thisPanel": "This panel",
"fleetScope": "Master + {remotes} remote nodes",
"reporting": "{live}/{total} reporting",
"registered": "{remotes} remote nodes · {total} total",
"allStatuses": "All statuses",
"open": "Open",
"hardware": "CPU / RAM",
"cpuAverage": "Avg CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} available",
"remainingMemory": "{size} remaining",
"connections": "TCP / UDP / Load",
"load": "Load",
"loadSum": "Load sum",
"loadWindow": "System load over 1, 5 and 15 minutes",
"hostMetrics": "Rates and connections are summed per host.",
"runtime": "Runtime",
"mixed": "Versions vary",
"history": "History",
"node": "Node",
"searchNodes": "Search nodes…",
"panel": "Panel",
"uptimeShort": "Up",
"uptimeVaries": "Uptime varies by node",
"clientRecords": "{records} client records",
"acrossNodes": "Across {total} nodes",
"connectionDetails": "Connection details",
"footnote": "Fleet totals use reporting nodes only ({coverage}). Load values are 1 / 5 / 15 min; fleet values sum the reporting nodes. Hover status for heartbeat and latency."
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "El panel y los servicios de suscripción del nodo se reiniciarán y podrían dejar de estar disponibles temporalmente. Requiere un token API node-admin o admin en el nodo.",
"addNode": "Agregar nodo",
"editNode": "Editar nodo",
"totalNodes": "Total de nodos",
"onlineNodes": "En línea",
"offlineNodes": "Sin conexión",
"avgLatency": "Latencia media",
"onlineOnNode": "{synced} en línea en los inbounds importados a este panel, {total} en línea en total en el nodo",
"name": "Nombre",
"namePlaceholder": "p. ej. de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Solo lectura: un nodo descendente al que se llega a través de {parent}. Gestiónalo desde el propio panel de {parent}.",
"deleteConfirmTitle": "¿Eliminar el nodo \"{name}\"?",
"deleteConfirmContent": "Esto detiene la monitorización del nodo. El panel remoto en sí no se ve afectado.",
"fleet": {
"subtitle": "Supervisa el nodo principal y todos los nodos conectados en una vista.",
"allNodes": "Todos los nodos",
"master": "Principal",
"thisPanel": "Este panel",
"fleetScope": "Principal + {remotes} nodos remotos",
"reporting": "{live}/{total} con datos",
"registered": "{remotes} remotos · {total} en total",
"allStatuses": "Todos los estados",
"open": "Abrir",
"hardware": "CPU / RAM",
"cpuAverage": "CPU media",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} disponibles",
"remainingMemory": "{size} restantes",
"connections": "TCP / UDP / Carga",
"load": "Carga",
"loadSum": "Suma de cargas",
"loadWindow": "Carga del sistema en 1, 5 y 15 minutos",
"hostMetrics": "Las tasas y conexiones se suman por servidor.",
"runtime": "Ejecución",
"mixed": "Mixto",
"history": "Historial",
"node": "Nodo",
"searchNodes": "Buscar nodos…",
"panel": "Panel",
"uptimeShort": "Activo",
"uptimeVaries": "El tiempo activo varía por nodo",
"clientRecords": "{records} clientes registrados",
"acrossNodes": "En {total} nodos",
"connectionDetails": "Detalles de conexión",
"footnote": "Los totales usan los nodos que informan ({coverage}). Las cargas son de 1, 5 y 15 min y se suman entre nodos. Pasa el cursor por el estado para ver latencia y último contacto."
},
"statusValues": {
"online": "En línea",
"offline": "Sin conexión",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "پنل و سرویس اشتراک نود مجدداً راه‌اندازی می‌شوند و ممکن است موقتاً در دسترس نباشند. توکن API نود باید دسترسی node-admin یا admin داشته باشد.",
"addNode": "افزودن نود",
"editNode": "ویرایش نود",
"totalNodes": "کل نودها",
"onlineNodes": "آنلاین",
"offlineNodes": "آفلاین",
"avgLatency": "میانگین تاخیر",
"onlineOnNode": "{synced} آنلاین روی اینباندهای واردشده به این پنل، {total} آنلاین در کل نود",
"name": "نام",
"namePlaceholder": "مثلاً de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "فقط‌خواندنی: یک نود پایین‌دستی که از طریق {parent} در دسترس است. آن را از پنل خودِ {parent} مدیریت کنید.",
"deleteConfirmTitle": "نود «{name}» حذف شود؟",
"deleteConfirmContent": "نظارت روی این نود متوقف می‌شود. خود پنل ریموت تغییری نمی‌کند.",
"fleet": {
"subtitle": "مستر و همهٔ نودهای متصل را در یک نما پایش کنید.",
"allNodes": "همهٔ نودها",
"master": "مستر",
"thisPanel": "این پنل",
"fleetScope": "مستر + {remotes} نود راه دور",
"reporting": "{live} از {total} در حال گزارش",
"registered": "{remotes} نود راه دور · {total} در مجموع",
"allStatuses": "همهٔ وضعیت‌ها",
"open": "باز کردن",
"hardware": "پردازنده / حافظه",
"cpuAverage": "میانگین CPU",
"logicalCores": "{cores} پردازندهٔ منطقی",
"availableMemory": "{size} در دسترس",
"remainingMemory": "{size} باقی‌مانده",
"connections": "TCP / UDP / بار",
"load": "بار سیستم",
"loadSum": "مجموع بار",
"loadWindow": "بار سیستم در بازه‌های ۱، ۵ و ۱۵ دقیقه",
"hostMetrics": "نرخ‌ها و اتصال‌ها به تفکیک میزبان جمع می‌شوند.",
"runtime": "زمان اجرا",
"mixed": "چند نسخه",
"history": "تاریخچه",
"node": "نود",
"searchNodes": "جست‌وجوی نودها…",
"panel": "پنل",
"uptimeShort": "زمان کار",
"uptimeVaries": "زمان کار به نود بستگی دارد",
"clientRecords": "{records} کلاینت ثبت‌شده",
"acrossNodes": "در {total} نود",
"connectionDetails": "جزئیات اتصال",
"footnote": "جمع کل از نودهای در حال گزارش محاسبه می‌شود ({coverage}). بار در بازه‌های ۱، ۵ و ۱۵ دقیقه نمایش داده می‌شود و در نمای کل، مجموع نودهای گزارش‌دهنده است. برای دیدن ضربان و تأخیر روی وضعیت مکث کنید."
},
"statusValues": {
"online": "آنلاین",
"offline": "آفلاین",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Panel node dan layanan langganan akan dimulai ulang dan mungkin tidak tersedia sementara. Memerlukan token API node-admin atau admin pada node.",
"addNode": "Tambah Node",
"editNode": "Edit node",
"totalNodes": "Total Node",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Latensi Rata-rata",
"onlineOnNode": "{synced} online pada inbound yang diimpor ke panel ini, total {total} online di node",
"name": "Nama",
"namePlaceholder": "mis. de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Hanya-baca: node turunan yang dijangkau melalui {parent}. Kelola dari panel {parent} sendiri.",
"deleteConfirmTitle": "Hapus node \"{name}\"?",
"deleteConfirmContent": "Ini menghentikan pemantauan node. Panel jarak jauh itu sendiri tidak terpengaruh.",
"fleet": {
"subtitle": "Pantau node utama dan semua node terhubung dalam satu tampilan.",
"allNodes": "Semua node",
"master": "Utama",
"thisPanel": "Panel ini",
"fleetScope": "Utama + {remotes} node jarak jauh",
"reporting": "{live}/{total} melapor",
"registered": "{remotes} node jarak jauh · {total} total",
"allStatuses": "Semua status",
"open": "Buka",
"hardware": "CPU / RAM",
"cpuAverage": "Rata-rata CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} tersedia",
"remainingMemory": "{size} tersisa",
"connections": "TCP / UDP / Beban",
"load": "Beban",
"loadSum": "Total beban",
"loadWindow": "Beban sistem selama 1, 5, dan 15 menit",
"hostMetrics": "Laju dan koneksi dijumlahkan per host.",
"runtime": "Runtime",
"mixed": "Campuran",
"history": "Riwayat",
"node": "Node",
"searchNodes": "Cari node…",
"panel": "Panel",
"uptimeShort": "Aktif",
"uptimeVaries": "Waktu aktif berbeda menurut node",
"clientRecords": "{records} catatan klien",
"acrossNodes": "Di {total} node",
"connectionDetails": "Detail koneksi",
"footnote": "Total berasal dari node yang melapor ({coverage}). Beban 1, 5, dan 15 menit dijumlahkan antar node. Arahkan ke status untuk melihat heartbeat dan latensi."
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "ノードのパネルとサブスクリプションサービスを再起動するため、一時的に利用できなくなる場合があります。ノードのnode-adminまたはadmin APIトークンが必要です。",
"addNode": "ノードを追加",
"editNode": "ノード編集",
"totalNodes": "ノード総数",
"onlineNodes": "オンライン",
"offlineNodes": "オフライン",
"avgLatency": "平均レイテンシ",
"onlineOnNode": "このパネルにインポートしたインバウンドでオンライン: {synced}、ノード全体でオンライン: {total}",
"name": "名前",
"namePlaceholder": "例: de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "読み取り専用: {parent} を経由して到達する下位ノードです。{parent} 自身のパネルから管理してください。",
"deleteConfirmTitle": "ノード「{name}」を削除しますか?",
"deleteConfirmContent": "ノードの監視を停止します。リモートパネル自体には影響しません。",
"fleet": {
"subtitle": "マスターと接続中の全ノードをまとめて監視します。",
"allNodes": "全ノード",
"master": "マスター",
"thisPanel": "このパネル",
"fleetScope": "マスターとリモート {remotes} 台",
"reporting": "{live}/{total} 台が報告中",
"registered": "リモート {remotes} 台 · 合計 {total} 台",
"allStatuses": "すべての状態",
"open": "開く",
"hardware": "CPU / RAM",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} 利用可能",
"remainingMemory": "{size} 残り",
"connections": "TCP / UDP / 負荷",
"load": "負荷",
"loadSum": "負荷合計",
"loadWindow": "1 分・5 分・15 分のシステム負荷",
"hostMetrics": "転送速度と接続数はホストごとの値を合計しています。",
"runtime": "実行環境",
"mixed": "混在",
"history": "履歴",
"node": "ノード",
"searchNodes": "ノードを検索…",
"panel": "パネル",
"uptimeShort": "稼働",
"uptimeVaries": "稼働時間はノードによって異なります",
"clientRecords": "クライアント登録数 {records}",
"acrossNodes": "{total} 台のノード",
"connectionDetails": "接続の詳細",
"footnote": "集計対象は報告中のノードです ({coverage})。1、5、15 分の負荷は報告中のノードの合計です。状態にカーソルを合わせると最終応答と遅延を確認できます。"
},
"statusValues": {
"online": "オンライン",
"offline": "オフライン",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "O painel e os serviços de assinatura do nó serão reiniciados e poderão ficar indisponíveis temporariamente. Requer um token de API node-admin ou admin no nó.",
"addNode": "Adicionar nó",
"editNode": "Editar nó",
"totalNodes": "Total de nós",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Latência média",
"onlineOnNode": "{synced} online nos inbounds importados para este painel, {total} online no nó no total",
"name": "Nome",
"namePlaceholder": "ex.: de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Somente leitura: um nó descendente acessado através de {parent}. Gerencie-o pelo próprio painel de {parent}.",
"deleteConfirmTitle": "Excluir o nó \"{name}\"?",
"deleteConfirmContent": "Isso interrompe o monitoramento do nó. O painel remoto em si não é afetado.",
"fleet": {
"subtitle": "Monitore o nó principal e todos os nós conectados em uma única tela.",
"allNodes": "Todos os nós",
"master": "Principal",
"thisPanel": "Este painel",
"fleetScope": "Principal + {remotes} nós remotos",
"reporting": "{live}/{total} enviando dados",
"registered": "{remotes} remotos · {total} no total",
"allStatuses": "Todos os estados",
"open": "Abrir",
"hardware": "CPU / RAM",
"cpuAverage": "CPU média",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} disponíveis",
"remainingMemory": "{size} restantes",
"connections": "TCP / UDP / Carga",
"load": "Carga",
"loadSum": "Soma das cargas",
"loadWindow": "Carga do sistema em 1, 5 e 15 minutos",
"hostMetrics": "As taxas e conexões são somadas por host.",
"runtime": "Execução",
"mixed": "Misto",
"history": "Histórico",
"node": "Nó",
"searchNodes": "Pesquisar nós…",
"panel": "Painel",
"uptimeShort": "Ativo",
"uptimeVaries": "O tempo ativo varia por nó",
"clientRecords": "{records} clientes registrados",
"acrossNodes": "Em {total} nós",
"connectionDetails": "Detalhes da conexão",
"footnote": "Os totais usam os nós que enviam dados ({coverage}). As cargas de 1, 5 e 15 min são somadas. Passe o cursor pelo status para ver latência e último contato."
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Панель узла и службы подписки будут перезапущены и могут быть временно недоступны. Требуется API-токен node-admin или admin на узле.",
"addNode": "Добавить узел",
"editNode": "Изменить узел",
"totalNodes": "Всего узлов",
"onlineNodes": "В сети",
"offlineNodes": "Не в сети",
"avgLatency": "Средняя задержка",
"onlineOnNode": "В сети на инбаундах, импортированных в эту панель: {synced}; всего в сети на узле: {total}",
"name": "Имя",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Только для чтения: подчинённый узел, доступный через {parent}. Управляйте им из собственной панели {parent}.",
"deleteConfirmTitle": "Удалить узел \"{name}\"?",
"deleteConfirmContent": "Это остановит мониторинг узла. Сама удалённая панель не будет затронута.",
"fleet": {
"subtitle": "Следите за главным и всеми подключёнными узлами на одной странице.",
"allNodes": "Все узлы",
"master": "Главный",
"thisPanel": "Эта панель",
"fleetScope": "Главный + удалённых узлов: {remotes}",
"reporting": "Передают данные: {live}/{total}",
"registered": "Удалённых: {remotes} · Всего: {total}",
"allStatuses": "Все статусы",
"open": "Открыть",
"hardware": "ЦП / ОЗУ",
"cpuAverage": "Средняя загрузка ЦП",
"logicalCores": "{cores} vCPU",
"availableMemory": "Доступно {size}",
"remainingMemory": "Осталось {size}",
"connections": "TCP / UDP / Нагрузка",
"load": "Нагрузка",
"loadSum": "Суммарная нагрузка",
"loadWindow": "Нагрузка системы за 1, 5 и 15 минут",
"hostMetrics": "Скорости и соединения суммируются по хостам.",
"runtime": "Среда выполнения",
"mixed": "Разные версии",
"history": "История",
"node": "Узел",
"searchNodes": "Поиск узлов…",
"panel": "Панель",
"uptimeShort": "Работа",
"uptimeVaries": "Время работы различается по узлам",
"clientRecords": "Клиентских записей: {records}",
"acrossNodes": "На {total} узлах",
"connectionDetails": "Сведения о подключении",
"footnote": "Итоги учитывают узлы, передающие данные ({coverage}). Нагрузка за 1, 5 и 15 минут суммируется. Наведите курсор на статус, чтобы увидеть задержку и последнюю проверку."
},
"statusValues": {
"online": "В сети",
"offline": "Не в сети",
+33 -4
View File
@@ -1339,10 +1339,6 @@
"restartPanelContent": "Panel uzla a služby odberov sa reštartujú a môžu byť dočasne nedostupné. Vyžaduje sa API token node-admin alebo admin na uzle.",
"addNode": "Pridať server",
"editNode": "Upraviť server",
"totalNodes": "Počet serverov",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Priemerná odozva",
"onlineOnNode": "{synced} online na vstupoch importovaných do tohto panela, celkovo {total} online na uzle",
"name": "Názov",
"namePlaceholder": "napr. de-frankfurt-1",
@@ -1400,6 +1396,39 @@
"subNodeTip": "Iba na čítanie: podriadený server dostupný cez {parent}. Spravujte ho z panelu servera {parent}.",
"deleteConfirmTitle": "Odstrániť server „{name}“?",
"deleteConfirmContent": "Prestane sa sledovať tento server. Samotný vzdialený panel sa nezmení.",
"fleet": {
"subtitle": "Monitorujte hlavný uzol a všetky pripojené uzly v jednom zobrazení.",
"allNodes": "Všetky uzly",
"master": "Hlavný uzol",
"thisPanel": "Tento panel",
"fleetScope": "Hlavný uzol + {remotes} vzdialených uzlov",
"reporting": "{live}/{total} hlási údaje",
"registered": "{remotes} vzdialených · {total} spolu",
"allStatuses": "Všetky stavy",
"open": "Otvoriť",
"hardware": "CPU / RAM",
"cpuAverage": "Priemer CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} dostupných",
"remainingMemory": "{size} zostáva",
"connections": "TCP / UDP / Záťaž",
"load": "Záťaž",
"loadSum": "Súčet záťaže",
"loadWindow": "Systémová záťaž za 1, 5 a 15 minút",
"hostMetrics": "Rýchlosti a spojenia sa sčítavajú za jednotlivé hostitele.",
"runtime": "Beh",
"mixed": "Rôzne verzie",
"history": "História",
"node": "Uzol",
"searchNodes": "Vyhľadať uzly…",
"panel": "Panel",
"uptimeShort": "Beh",
"uptimeVaries": "Čas prevádzky sa líši podľa uzla",
"clientRecords": "{records} záznamov klientov",
"acrossNodes": "Na {total} uzloch",
"connectionDetails": "Podrobnosti pripojenia",
"footnote": "Súčty zahŕňajú uzly, ktoré hlásia údaje ({coverage}). Záťaž za 1, 5 a 15 minút sa sčítava. Pre posledný kontakt a odozvu ukážte na stav."
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Düğüm paneli ve abonelik hizmetleri yeniden başlatılacak ve geçici olarak kullanılamayabilir. Düğümde node-admin veya admin API belirteci gerekir.",
"addNode": "Düğüm Ekle",
"editNode": "Düğümü Düzenle",
"totalNodes": "Toplam Düğüm",
"onlineNodes": "Çevrimiçi",
"offlineNodes": "Çevrimdışı",
"avgLatency": "Ortalama Gecikme",
"onlineOnNode": "Bu panele içe aktarılan inbound'larda {synced} çevrimiçi, düğümde toplam {total} çevrimiçi",
"name": "Ad",
"namePlaceholder": "ör. de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Salt okunur: {parent} üzerinden erişilen bir alt düğüm. Bunu {parent} panelinden yönetin.",
"deleteConfirmTitle": "\"{name}\" düğümü silinsin mi?",
"deleteConfirmContent": "Bu işlem düğüm izlemeyi durdurur. Uzak panelin kendisi etkilenmez.",
"fleet": {
"subtitle": "Ana düğümü ve bağlı tüm düğümleri tek bir görünümde izleyin.",
"allNodes": "Tüm düğümler",
"master": "Ana düğüm",
"thisPanel": "Bu panel",
"fleetScope": "Ana düğüm + {remotes} uzak düğüm",
"reporting": "{live}/{total} veri gönderiyor",
"registered": "{remotes} uzak düğüm · {total} toplam",
"allStatuses": "Tüm durumlar",
"open": "Aç",
"hardware": "CPU / RAM",
"cpuAverage": "Ort. CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} kullanılabilir",
"remainingMemory": "{size} kalan",
"connections": "TCP / UDP / Yük",
"load": "Yük",
"loadSum": "Toplam yük",
"loadWindow": "1, 5 ve 15 dakikalık sistem yükü",
"hostMetrics": "Hızlar ve bağlantılar ana makine bazında toplanır.",
"runtime": "Çalışma zamanı",
"mixed": "Karma",
"history": "Geçmiş",
"node": "Düğüm",
"searchNodes": "Düğüm ara…",
"panel": "Panel",
"uptimeShort": "Çalışma",
"uptimeVaries": "Çalışma süresi düğüme göre değişir",
"clientRecords": "{records} istemci kaydı",
"acrossNodes": "{total} düğümde",
"connectionDetails": "Bağlantı ayrıntıları",
"footnote": "Toplamlara veri gönderen düğümler dahildir ({coverage}). 1, 5 ve 15 dakikalık yükler toplanır. Son sinyali ve gecikmeyi görmek için durumun üzerine gelin."
},
"statusValues": {
"online": "Çevrimiçi",
"offline": "Çevrimdışı",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Панель вузла та служби підписки буде перезапущено, і вони можуть бути тимчасово недоступні. Потрібен API-токен node-admin або admin на вузлі.",
"addNode": "Додати вузол",
"editNode": "Змінити вузол",
"totalNodes": "Усього вузлів",
"onlineNodes": "У мережі",
"offlineNodes": "Не в мережі",
"avgLatency": "Середня затримка",
"onlineOnNode": "У мережі на інбаундах, імпортованих у цю панель: {synced}; усього в мережі на вузлі: {total}",
"name": "Назва",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Лише для читання: підлеглий вузол, доступний через {parent}. Керуйте ним із власної панелі {parent}.",
"deleteConfirmTitle": "Видалити вузол \"{name}\"?",
"deleteConfirmContent": "Це зупинить моніторинг вузла. Сама віддалена панель не зазнає змін.",
"fleet": {
"subtitle": "Стежте за головним і всіма підключеними вузлами на одній сторінці.",
"allNodes": "Усі вузли",
"master": "Головний",
"thisPanel": "Ця панель",
"fleetScope": "Головний + віддалених вузлів: {remotes}",
"reporting": "Передають дані: {live}/{total}",
"registered": "Віддалених: {remotes} · Усього: {total}",
"allStatuses": "Усі стани",
"open": "Відкрити",
"hardware": "ЦП / ОЗП",
"cpuAverage": "Середнє ЦП",
"logicalCores": "{cores} vCPU",
"availableMemory": "Доступно {size}",
"remainingMemory": "Залишилося {size}",
"connections": "TCP / UDP / Навантаження",
"load": "Навантаження",
"loadSum": "Сумарне навантаження",
"loadWindow": "Навантаження системи за 1, 5 та 15 хвилин",
"hostMetrics": "Швидкості та з’єднання підсумовуються за хостами.",
"runtime": "Середовище виконання",
"mixed": "Різні версії",
"history": "Історія",
"node": "Вузол",
"searchNodes": "Пошук вузлів…",
"panel": "Панель",
"uptimeShort": "Робота",
"uptimeVaries": "Час роботи залежить від вузла",
"clientRecords": "Записів клієнтів: {records}",
"acrossNodes": "На {total} вузлах",
"connectionDetails": "Відомості про з’єднання",
"footnote": "Підсумки враховують вузли, які передають дані ({coverage}). Навантаження за 1, 5 і 15 хвилин підсумовується. Наведіть курсор на стан для відомостей про затримку й останню перевірку."
},
"statusValues": {
"online": "У мережі",
"offline": "Не в мережі",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Bảng điều khiển và dịch vụ đăng ký của nút sẽ khởi động lại và có thể tạm thời không khả dụng. Yêu cầu mã API node-admin hoặc admin trên nút.",
"addNode": "Thêm nút",
"editNode": "Sửa node",
"totalNodes": "Tổng số nút",
"onlineNodes": "Trực tuyến",
"offlineNodes": "Ngoại tuyến",
"avgLatency": "Độ trễ trung bình",
"onlineOnNode": "{synced} trực tuyến trên các inbound đã nhập vào bảng điều khiển này, tổng cộng {total} trực tuyến trên nút",
"name": "Tên",
"namePlaceholder": "vd: de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "Chỉ đọc: một nút phía dưới được kết nối qua {parent}. Quản lý nó từ bảng điều khiển của chính {parent}.",
"deleteConfirmTitle": "Xóa nút \"{name}\"?",
"deleteConfirmContent": "Việc này dừng giám sát nút. Panel từ xa không bị ảnh hưởng.",
"fleet": {
"subtitle": "Giám sát nút chính và tất cả các nút đã kết nối trong một chế độ xem.",
"allNodes": "Tất cả nút",
"master": "Nút chính",
"thisPanel": "Bảng điều khiển này",
"fleetScope": "Nút chính + {remotes} nút từ xa",
"reporting": "{live}/{total} đang báo cáo",
"registered": "{remotes} nút từ xa · {total} tổng cộng",
"allStatuses": "Mọi trạng thái",
"open": "Mở",
"hardware": "CPU / RAM",
"cpuAverage": "CPU trung bình",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} khả dụng",
"remainingMemory": "Còn lại {size}",
"connections": "TCP / UDP / Tải",
"load": "Tải",
"loadSum": "Tổng tải",
"loadWindow": "Tải hệ thống trong 1, 5 và 15 phút",
"hostMetrics": "Tốc độ và kết nối được cộng theo từng máy chủ.",
"runtime": "Môi trường chạy",
"mixed": "Nhiều phiên bản",
"history": "Lịch sử",
"node": "Nút",
"searchNodes": "Tìm nút…",
"panel": "Bảng điều khiển",
"uptimeShort": "Đã chạy",
"uptimeVaries": "Thời gian chạy tùy theo nút",
"clientRecords": "{records} hồ sơ máy khách",
"acrossNodes": "Trên {total} nút",
"connectionDetails": "Chi tiết kết nối",
"footnote": "Tổng chỉ tính các nút đang báo cáo ({coverage}). Tải 1, 5 và 15 phút được cộng trên các nút. Di chuột qua trạng thái để xem lần liên lạc cuối và độ trễ."
},
"statusValues": {
"online": "Trực tuyến",
"offline": "Ngoại tuyến",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "节点面板和订阅服务将重启,并可能暂时不可用。需要节点上的 node-admin 或 admin API 令牌。",
"addNode": "添加节点",
"editNode": "编辑节点",
"totalNodes": "节点总数",
"onlineNodes": "在线",
"offlineNodes": "离线",
"avgLatency": "平均延迟",
"onlineOnNode": "导入此面板的入站上有 {synced} 个在线,该节点上共有 {total} 个在线",
"name": "名称",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "只读:通过 {parent} 接入的下游节点。请在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "删除节点 \"{name}\"?",
"deleteConfirmContent": "这将停止监控该节点。远程面板本身不受影响。",
"fleet": {
"subtitle": "集中监控主节点与所有已连接的节点。",
"allNodes": "所有节点",
"master": "主节点",
"thisPanel": "本面板",
"fleetScope": "主节点 + {remotes} 个远程节点",
"reporting": "{live}/{total} 正在上报",
"registered": "{remotes} 个远程节点 · 共 {total} 个",
"allStatuses": "所有状态",
"open": "打开",
"hardware": "CPU / 内存",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} 个逻辑核心",
"availableMemory": "可用 {size}",
"remainingMemory": "剩余 {size}",
"connections": "TCP / UDP / 负载",
"load": "负载",
"loadSum": "总负载",
"loadWindow": "1、5 和 15 分钟系统负载",
"hostMetrics": "速率和连接数按主机汇总。",
"runtime": "运行状态",
"mixed": "多个版本",
"history": "历史",
"node": "节点",
"searchNodes": "搜索节点…",
"panel": "面板",
"uptimeShort": "运行",
"uptimeVaries": "运行时长因节点而异",
"clientRecords": "{records} 条客户端记录",
"acrossNodes": "分布于 {total} 个节点",
"connectionDetails": "连接详情",
"footnote": "总计仅包括正在上报的节点 ({coverage})。负载按 1、5 和 15 分钟展示,并在上报节点之间求和。将鼠标悬停在状态上可查看心跳和延迟。"
},
"statusValues": {
"online": "在线",
"offline": "离线",
+33 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "節點面板與訂閱服務將重新啟動,可能暫時無法使用。需要節點上的 node-admin 或 admin API 權杖。",
"addNode": "新增節點",
"editNode": "編輯節點",
"totalNodes": "節點總數",
"onlineNodes": "上線",
"offlineNodes": "離線",
"avgLatency": "平均延遲",
"onlineOnNode": "匯入此面板的入站上有 {synced} 個上線,該節點上共有 {total} 個上線",
"name": "名稱",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1279,6 +1275,39 @@
"subNodeTip": "唯讀:透過 {parent} 連接的下游節點。請在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "刪除節點「{name}」?",
"deleteConfirmContent": "這將停止監控該節點。遠端面板本身不受影響。",
"fleet": {
"subtitle": "集中監控主節點和所有已連線的節點。",
"allNodes": "所有節點",
"master": "主節點",
"thisPanel": "本面板",
"fleetScope": "主節點 + {remotes} 個遠端節點",
"reporting": "{live}/{total} 正在回報",
"registered": "{remotes} 個遠端節點 · 共 {total} 個",
"allStatuses": "所有狀態",
"open": "開啟",
"hardware": "CPU / 記憶體",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} 個邏輯核心",
"availableMemory": "可用 {size}",
"remainingMemory": "剩餘 {size}",
"connections": "TCP / UDP / 負載",
"load": "負載",
"loadSum": "總負載",
"loadWindow": "1、5 和 15 分鐘系統負載",
"hostMetrics": "速率和連線數按主機加總。",
"runtime": "執行狀態",
"mixed": "多個版本",
"history": "歷史",
"node": "節點",
"searchNodes": "搜尋節點…",
"panel": "面板",
"uptimeShort": "運作",
"uptimeVaries": "運作時間依節點而異",
"clientRecords": "{records} 筆用戶端紀錄",
"acrossNodes": "分佈於 {total} 個節點",
"connectionDetails": "連線詳細資料",
"footnote": "總計僅納入回報中的節點 ({coverage})。負載以 1、5、15 分鐘表示並加總回報節點的負載。將游標停在狀態上可查看心跳和延遲。"
},
"statusValues": {
"online": "上線",
"offline": "離線",
+2 -1
View File
@@ -363,7 +363,8 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
// check client ips from log file every 10 sec
_, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
_, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
nodeHeartbeat := job.NewNodeHeartbeatJob()
_, _ = s.cron.AddJob(cadenceNodeHeartbeat, nodeHeartbeat)
s.nodeTrafficJob = job.NewNodeTrafficSyncJob()
_, _ = s.cron.AddJob(cadenceNodeTraffic, s.nodeTrafficJob)