mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-28 13:34:50 +03:00
perf(nodes): list nodes without the dashboard statistics in background jobs (#7235)
The node traffic sync and heartbeat jobs run every 5 seconds and listed nodes through GetAll, which also built the Nodes page statistics: a distinct-client count and a join over every client on a node-hosted inbound with its traffic row. Neither job reads those numbers, and neither do the Xray config build or the reset-all fan-out. With sub-nodes present the Nodes tree ran the same classification twice. Those callers now take ListOperational, a plain ordered node list with decrypted tokens. GetNodeTree adds the statistics once, and only the client count when a transitive tree recounts the rest itself. GetAll is gone, since nothing reads it any more. The Nodes page shows the same counts. On a master with 20,000 clients across eight node inbounds (SQLite), idle master CPU went from about 13.1 s to 12.3 s per minute. Closes #7232
This commit is contained in:
@@ -53,7 +53,7 @@ func (j *NodeHeartbeatJob) Run() {
|
||||
}
|
||||
defer j.running.Unlock()
|
||||
|
||||
nodes, err := j.nodeService.GetAll()
|
||||
nodes, err := j.nodeService.ListOperational()
|
||||
if err != nil {
|
||||
logger.Warning("node heartbeat: load nodes failed:", err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"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"
|
||||
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestBackgroundNodeJobs_SkipNodeDashboardStatQueries(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) })
|
||||
|
||||
db := database.GetDB()
|
||||
disabled := &model.Node{Name: "disabled", Address: "127.0.0.1", Port: 2053, ApiToken: "tok", Enable: true, Status: "offline"}
|
||||
if err := db.Create(disabled).Error; err != nil {
|
||||
t.Fatalf("create node: %v", err)
|
||||
}
|
||||
if err := db.Model(disabled).Update("enable", false).Error; err != nil {
|
||||
t.Fatalf("disable node: %v", err)
|
||||
}
|
||||
nid := disabled.Id
|
||||
ib := &model.Inbound{Tag: "n-in", Enable: true, Port: 443, Protocol: model.VLESS, Settings: `{"clients":[]}`, NodeID: &nid}
|
||||
if err := db.Create(ib).Error; err != nil {
|
||||
t.Fatalf("create inbound: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ClientRecord{Id: 1, Email: "c@example.com", Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ClientInbound{ClientId: 1, InboundId: ib.Id}).Error; err != nil {
|
||||
t.Fatalf("create client_inbound: %v", err)
|
||||
}
|
||||
if err := db.Create(&xray.ClientTraffic{InboundId: ib.Id, Email: "c@example.com", Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client_traffic: %v", err)
|
||||
}
|
||||
|
||||
var queries []string
|
||||
recordSQL := func(tx *gorm.DB) {
|
||||
if sql := tx.Statement.SQL.String(); sql != "" {
|
||||
queries = append(queries, sql)
|
||||
}
|
||||
}
|
||||
const cbName = "test:job-node-enum-sql"
|
||||
if err := db.Callback().Query().After("gorm:query").Register(cbName, recordSQL); err != nil {
|
||||
t.Fatalf("register query callback: %v", err)
|
||||
}
|
||||
if err := db.Callback().Row().After("gorm:row").Register(cbName, recordSQL); err != nil {
|
||||
t.Fatalf("register row callback: %v", err)
|
||||
}
|
||||
if err := db.Callback().Raw().After("gorm:raw").Register(cbName, recordSQL); err != nil {
|
||||
t.Fatalf("register raw callback: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = db.Callback().Query().Remove(cbName)
|
||||
_ = db.Callback().Row().Remove(cbName)
|
||||
_ = db.Callback().Raw().Remove(cbName)
|
||||
})
|
||||
|
||||
NewNodeTrafficSyncJob().Run()
|
||||
NewNodeHeartbeatJob().Run()
|
||||
|
||||
for _, q := range queries {
|
||||
lower := strings.ToLower(q)
|
||||
if strings.Contains(lower, "inbounds.node_id is not null") ||
|
||||
strings.Contains(lower, "count(distinct client_inbounds.client_id)") ||
|
||||
strings.Contains(lower, "join client_traffics ct") {
|
||||
t.Errorf("background node job executed dashboard node-stats query: %s", q)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func (j *NodeTrafficSyncJob) Run() {
|
||||
return
|
||||
}
|
||||
|
||||
nodes, err := j.nodeService.GetAll()
|
||||
nodes, err := j.nodeService.ListOperational()
|
||||
if err != nil {
|
||||
logger.Warning("node traffic sync: load nodes failed:", err)
|
||||
return
|
||||
|
||||
@@ -982,7 +982,7 @@ func (s *InboundService) resetAllTrafficsLocked() error {
|
||||
// remoteHTTPTimeout, and holding the single serial writer across N such calls
|
||||
// stalls traffic accounting and drops the deltas of every concurrent poll.
|
||||
func (s *InboundService) propagateResetAllTrafficsToNodes() {
|
||||
nodes, err := (&NodeService{}).GetAll()
|
||||
nodes, err := (&NodeService{}).ListOperational()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -123,7 +123,9 @@ func decryptToken(n *model.Node) {
|
||||
n.ApiToken = pt
|
||||
}
|
||||
|
||||
func (s *NodeService) GetAll() ([]*model.Node, error) {
|
||||
// ListOperational returns nodes ordered by id with decrypted API tokens,
|
||||
// skipping dashboard inbound and client statistics queries.
|
||||
func (s *NodeService) ListOperational() ([]*model.Node, error) {
|
||||
db := database.GetDB()
|
||||
var nodes []*model.Node
|
||||
err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
|
||||
@@ -133,26 +135,10 @@ func (s *NodeService) GetAll() ([]*model.Node, error) {
|
||||
for _, n := range nodes {
|
||||
decryptToken(n)
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
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 nodes, nil
|
||||
}
|
||||
if len(inboundRows) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
inboundsByNode := make(map[int][]int, len(nodes))
|
||||
for _, row := range inboundRows {
|
||||
inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
|
||||
}
|
||||
|
||||
func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) {
|
||||
type clientCountRow struct {
|
||||
NodeID int `gorm:"column:node_id"`
|
||||
Count int `gorm:"column:count"`
|
||||
@@ -174,6 +160,29 @@ func (s *NodeService) GetAll() ([]*model.Node, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) {
|
||||
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)
|
||||
@@ -214,8 +223,6 @@ func (s *NodeService) GetAll() ([]*model.Node, error) {
|
||||
// the intermediate node it syncs through (#4983).
|
||||
n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
|
||||
}
|
||||
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// nodeClientStatus is one node-hosted client's classification, carrying enough
|
||||
|
||||
@@ -8,12 +8,9 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
// The node-page client breakdown must classify by EMAIL, not by
|
||||
// client_traffics.inbound_id — that column goes stale after an inbound is
|
||||
// delete+recreated, so filtering by it drops almost every row and undercounts
|
||||
// active/disabled/ended. Here the traffic rows carry a bogus inbound_id (999)
|
||||
// yet must still be matched to the node's clients by email.
|
||||
func TestGetAll_ClientBreakdownMatchesByEmailNotStaleInboundId(t *testing.T) {
|
||||
// client_traffics.inbound_id goes stale after an inbound is deleted and recreated,
|
||||
// so the node-page breakdown must match a node's clients by email.
|
||||
func TestGetNodeTree_ClientBreakdownMatchesByEmailNotStaleInboundId(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
db := database.GetDB()
|
||||
svc := NodeService{}
|
||||
@@ -59,9 +56,9 @@ func TestGetAll_ClientBreakdownMatchesByEmailNotStaleInboundId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
nodes, err := svc.GetAll()
|
||||
nodes, err := svc.GetNodeTree()
|
||||
if err != nil {
|
||||
t.Fatalf("GetAll: %v", err)
|
||||
t.Fatalf("GetNodeTree: %v", err)
|
||||
}
|
||||
var n *model.Node
|
||||
for _, x := range nodes {
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func recordExecutedSQL(t *testing.T, db *gorm.DB) *[]string {
|
||||
t.Helper()
|
||||
var queries []string
|
||||
appendSQL := func(tx *gorm.DB) {
|
||||
if sql := tx.Statement.SQL.String(); sql != "" {
|
||||
queries = append(queries, sql)
|
||||
}
|
||||
}
|
||||
const cbName = "test:record-executed-sql"
|
||||
if err := db.Callback().Query().After("gorm:query").Register(cbName, appendSQL); err != nil {
|
||||
t.Fatalf("register query callback: %v", err)
|
||||
}
|
||||
if err := db.Callback().Row().After("gorm:row").Register(cbName, appendSQL); err != nil {
|
||||
t.Fatalf("register row callback: %v", err)
|
||||
}
|
||||
if err := db.Callback().Raw().After("gorm:raw").Register(cbName, appendSQL); err != nil {
|
||||
t.Fatalf("register raw callback: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = db.Callback().Query().Remove(cbName)
|
||||
_ = db.Callback().Row().Remove(cbName)
|
||||
_ = db.Callback().Raw().Remove(cbName)
|
||||
})
|
||||
return &queries
|
||||
}
|
||||
|
||||
func TestListOperational_SkipsDashboardQueriesAndPreservesOrderAndTokens(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
enableNodeTokenEncryption(t)
|
||||
db := database.GetDB()
|
||||
svc := NodeService{}
|
||||
|
||||
// Insert higher id before lower id so ordering by id asc is verified.
|
||||
n2 := &model.Node{Id: 2, Name: "second", Address: "10.0.0.2", Port: 2053, ApiToken: "secret-two", Guid: "guid-2"}
|
||||
n1 := &model.Node{Id: 1, Name: "first", Address: "10.0.0.1", Port: 2053, ApiToken: "secret-one", Guid: "guid-1"}
|
||||
for _, n := range []*model.Node{n2, n1} {
|
||||
if err := svc.Create(n); err != nil {
|
||||
t.Fatalf("create node %d: %v", n.Id, err)
|
||||
}
|
||||
}
|
||||
// An undecryptable token must keep its node row and surface as LastError.
|
||||
n3 := &model.Node{Id: 3, Name: "broken", Address: "10.0.0.3", Port: 2053, ApiToken: "secret-three", Guid: "guid-3"}
|
||||
if err := svc.Create(n3); err != nil {
|
||||
t.Fatalf("create broken token node: %v", err)
|
||||
}
|
||||
stored := rawStoredToken(t, n3.Id)
|
||||
body := strings.LastIndexByte(stored, ':') + 1
|
||||
replacement := byte('A')
|
||||
if stored[body] == replacement {
|
||||
replacement = 'B'
|
||||
}
|
||||
corrupt := stored[:body] + string(replacement) + stored[body+1:]
|
||||
if err := db.Model(&model.Node{}).Where("id = ?", n3.Id).Update("api_token", corrupt).Error; err != nil {
|
||||
t.Fatalf("corrupt broken token node: %v", err)
|
||||
}
|
||||
|
||||
nid := 1
|
||||
ib := &model.Inbound{Tag: "n1-in", Enable: true, Port: 443, Protocol: model.VLESS, Settings: `{"clients":[]}`, NodeID: &nid}
|
||||
if err := db.Create(ib).Error; err != nil {
|
||||
t.Fatalf("create inbound: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ClientRecord{Id: 1, Email: "user@example.com", Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ClientInbound{ClientId: 1, InboundId: ib.Id}).Error; err != nil {
|
||||
t.Fatalf("create client_inbound: %v", err)
|
||||
}
|
||||
if err := db.Create(&xray.ClientTraffic{InboundId: ib.Id, Email: "user@example.com", Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client_traffic: %v", err)
|
||||
}
|
||||
|
||||
queries := recordExecutedSQL(t, db)
|
||||
|
||||
nodes, err := svc.ListOperational()
|
||||
if err != nil {
|
||||
t.Fatalf("ListOperational: %v", err)
|
||||
}
|
||||
if len(nodes) != 3 {
|
||||
t.Fatalf("len(nodes) = %d, want 3", len(nodes))
|
||||
}
|
||||
if nodes[0].Id != 1 || nodes[1].Id != 2 || nodes[2].Id != 3 {
|
||||
t.Fatalf("node order = [%d, %d, %d], want [1, 2, 3]", nodes[0].Id, nodes[1].Id, nodes[2].Id)
|
||||
}
|
||||
if nodes[0].ApiToken != "secret-one" || nodes[1].ApiToken != "secret-two" {
|
||||
t.Errorf("decrypted tokens = [%q, %q], want [secret-one, secret-two]", nodes[0].ApiToken, nodes[1].ApiToken)
|
||||
}
|
||||
if nodes[2].ApiToken != "" || !strings.Contains(nodes[2].LastError, "token decrypt failed") {
|
||||
t.Errorf("broken token node = (token=%q, lastError=%q), want empty token and decrypt error", nodes[2].ApiToken, nodes[2].LastError)
|
||||
}
|
||||
if nodes[0].InboundCount != 0 || nodes[0].ClientCount != 0 || nodes[0].ActiveCount != 0 {
|
||||
t.Errorf("ListOperational should leave dashboard stats at zero, got %+v", nodes[0])
|
||||
}
|
||||
for _, q := range *queries {
|
||||
lower := strings.ToLower(q)
|
||||
if strings.Contains(lower, "inbounds") || strings.Contains(lower, "client_inbounds") || strings.Contains(lower, "client_traffics") {
|
||||
t.Errorf("ListOperational executed unexpected dashboard SQL: %s", q)
|
||||
}
|
||||
}
|
||||
|
||||
enriched, err := svc.GetNodeTree()
|
||||
if err != nil {
|
||||
t.Fatalf("GetNodeTree: %v", err)
|
||||
}
|
||||
if enriched[0].InboundCount != 1 || enriched[0].ClientCount != 1 || enriched[0].ActiveCount != 1 {
|
||||
t.Errorf("GetNodeTree stats = (inbound=%d, client=%d, active=%d), want (1, 1, 1)",
|
||||
enriched[0].InboundCount, enriched[0].ClientCount, enriched[0].ActiveCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNodeTree_TransitiveSkipsDuplicateStatusClassification(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
db := database.GetDB()
|
||||
svc := NodeService{}
|
||||
|
||||
if err := db.Create(&model.Node{
|
||||
Id: 1, Name: "Node2", Address: "10.0.0.2", Port: 2053,
|
||||
ApiToken: "t", Guid: "node2-guid", Status: "online",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create node: %v", err)
|
||||
}
|
||||
nid := 1
|
||||
ib := &model.Inbound{
|
||||
Tag: "n1-own", Enable: true, Port: 443, Protocol: model.VLESS,
|
||||
Settings: `{"clients":[]}`, NodeID: &nid, OriginNodeGuid: "node2-guid",
|
||||
}
|
||||
if err := db.Create(ib).Error; err != nil {
|
||||
t.Fatalf("create inbound: %v", err)
|
||||
}
|
||||
for i, email := range []string{"a@example.com", "b@example.com"} {
|
||||
cid := i + 1
|
||||
if err := db.Create(&model.ClientRecord{Id: cid, Email: email, Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ClientInbound{ClientId: cid, InboundId: ib.Id}).Error; err != nil {
|
||||
t.Fatalf("create client_inbound: %v", err)
|
||||
}
|
||||
if err := db.Create(&xray.ClientTraffic{InboundId: ib.Id, Email: email, Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client_traffic: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
nodeDescendantsMu.Lock()
|
||||
nodeDescendantsCache[1] = []model.NodeSummary{{
|
||||
Guid: "node3-guid", ParentGuid: "node2-guid", Name: "Node3", Address: "10.0.0.3", Status: "online",
|
||||
}}
|
||||
nodeDescendantsMu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
nodeDescendantsMu.Lock()
|
||||
nodeDescendantsCache = map[int][]model.NodeSummary{}
|
||||
nodeDescendantsMu.Unlock()
|
||||
})
|
||||
|
||||
queries := recordExecutedSQL(t, db)
|
||||
tree, err := svc.GetNodeTree()
|
||||
if err != nil {
|
||||
t.Fatalf("GetNodeTree: %v", err)
|
||||
}
|
||||
statusJoinCalls := 0
|
||||
for _, q := range *queries {
|
||||
if strings.Contains(strings.ToLower(q), "client_traffics") {
|
||||
statusJoinCalls++
|
||||
}
|
||||
}
|
||||
if statusJoinCalls != 1 {
|
||||
t.Errorf("client_traffics status join count = %d, want 1", statusJoinCalls)
|
||||
}
|
||||
var node2 *model.Node
|
||||
for _, n := range tree {
|
||||
if n.Guid == "node2-guid" {
|
||||
node2 = n
|
||||
break
|
||||
}
|
||||
}
|
||||
if node2 == nil {
|
||||
t.Fatal("node2 missing from tree")
|
||||
return
|
||||
}
|
||||
if node2.ClientCount != 2 || node2.ActiveCount != 2 || node2.InboundCount != 1 {
|
||||
t.Errorf("node2 counts = (client=%d, active=%d, inbound=%d), want (2, 2, 1)",
|
||||
node2.ClientCount, node2.ActiveCount, node2.InboundCount)
|
||||
}
|
||||
}
|
||||
@@ -117,9 +117,9 @@ func cachedDescendants() []model.NodeSummary {
|
||||
// it physically hosts (#4983). Direct nodes carry the master's own GUID as
|
||||
// ParentGuid; a transitive node carries its parent node's GUID. Transitive
|
||||
// nodes are read-only projections (Id == 0). Used by the Nodes page and the
|
||||
// heartbeat broadcast — never for probing/syncing, which stay on GetAll.
|
||||
// heartbeat broadcast — never for probing/syncing, which stay on ListOperational.
|
||||
func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
|
||||
nodes, err := s.GetAll()
|
||||
nodes, err := s.ListOperational()
|
||||
if err != nil {
|
||||
return nodes, err
|
||||
}
|
||||
@@ -163,9 +163,15 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
|
||||
})
|
||||
}
|
||||
if len(transitive) == 0 {
|
||||
if len(nodes) > 0 {
|
||||
s.enrichDashboardStats(database.GetDB(), nodes)
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
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...)
|
||||
|
||||
@@ -491,7 +491,7 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
|
||||
injectPanelEgress(xrayConfig, egressTag)
|
||||
}
|
||||
|
||||
nodes, err := s.nodeService.GetAll()
|
||||
nodes, err := s.nodeService.ListOperational()
|
||||
if err != nil {
|
||||
logger.Warning("read nodes for egress injection failed:", err)
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user