inbound_node.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/clause"
  17. )
  18. var reportedRemoteTagConflict sync.Map
  19. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  20. // stream to a remote node. Above it, the panel marks the node dirty instead and
  21. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  22. // sequential round-trips. Small ops stay on the live per-client path.
  23. const nodeBulkPushThreshold = 32
  24. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  25. mgr := runtime.GetManager()
  26. if mgr == nil {
  27. return nil, fmt.Errorf("runtime manager not initialised")
  28. }
  29. return mgr.RuntimeFor(ib.NodeID)
  30. }
  31. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  32. if ib.NodeID == nil {
  33. rt, err := s.runtimeFor(ib)
  34. if err != nil {
  35. return nil, false, false, nil
  36. }
  37. return rt, true, false, nil
  38. }
  39. nodeSvc := NodeService{}
  40. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  41. if err != nil {
  42. return nil, false, false, err
  43. }
  44. if !enabled || status == "offline" {
  45. return nil, false, true, nil
  46. }
  47. rt, err := s.runtimeFor(ib)
  48. if err != nil {
  49. return nil, false, true, nil
  50. }
  51. return rt, true, false, nil
  52. }
  53. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  54. if nodeID == nil {
  55. return false
  56. }
  57. return (&NodeService{}).IsNodePending(*nodeID)
  58. }
  59. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  60. if len(inboundIds) == 0 {
  61. return false
  62. }
  63. nodeSvc := NodeService{}
  64. for _, id := range inboundIds {
  65. ib, err := s.GetInbound(id)
  66. if err != nil || ib.NodeID == nil {
  67. continue
  68. }
  69. if nodeSvc.IsNodePending(*ib.NodeID) {
  70. return true
  71. }
  72. }
  73. return false
  74. }
  75. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  76. if rt == nil || n == nil || n.Id <= 0 {
  77. return nil
  78. }
  79. nodeID := n.Id
  80. db := database.GetDB()
  81. var inbounds []*model.Inbound
  82. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  83. return err
  84. }
  85. remoteTags, err := rt.ListRemoteTags(ctx)
  86. if err != nil {
  87. return err
  88. }
  89. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  90. for _, tag := range remoteTags {
  91. remoteTagSet[tag] = struct{}{}
  92. }
  93. prefix := nodeTagPrefix(&nodeID)
  94. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  95. for _, ib := range inbounds {
  96. desiredTags[ib.Tag] = struct{}{}
  97. // existsOnNode: does the node already report this inbound under any of the
  98. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  99. _, existsOnNode := remoteTagSet[ib.Tag]
  100. if prefix != "" {
  101. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  102. desiredTags[stripped] = struct{}{}
  103. if _, ok := remoteTagSet[stripped]; ok {
  104. existsOnNode = true
  105. }
  106. } else {
  107. desiredTags[prefix+ib.Tag] = struct{}{}
  108. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  109. existsOnNode = true
  110. }
  111. }
  112. }
  113. if _, err := rt.ReconcileInbound(ctx, ib, existsOnNode); err != nil {
  114. return fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err)
  115. }
  116. }
  117. // In "selected" sync mode the panel only manages the selected tags: the
  118. // rest were never imported, so their absence from the local DB must not
  119. // delete them from the node. Only a selected tag missing locally (the
  120. // panel deleted it while the node was unreachable) may be swept.
  121. var selected map[string]struct{}
  122. if n.InboundSyncMode == "selected" {
  123. selected = make(map[string]struct{}, len(n.InboundTags))
  124. for _, tag := range n.InboundTags {
  125. selected[tag] = struct{}{}
  126. }
  127. }
  128. for _, tag := range remoteTags {
  129. if _, want := desiredTags[tag]; want {
  130. continue
  131. }
  132. if selected != nil {
  133. if _, managed := selected[tag]; !managed {
  134. continue
  135. }
  136. }
  137. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  138. return fmt.Errorf("reconcile delete %q: %w", tag, err)
  139. }
  140. }
  141. return nil
  142. }
  143. const resetGracePeriodMs int64 = 30000
  144. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  145. // Xray's stats counters often report a zero delta for an active session across
  146. // a single poll, so a 5s grace would still drop the client on the next tick.
  147. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  148. // long after a real disconnect.
  149. const onlineGracePeriodMs int64 = 20000
  150. type nodeTrafficCounter struct {
  151. Up int64
  152. Down int64
  153. }
  154. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  155. return tx.Clauses(clause.OnConflict{
  156. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  157. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  158. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  159. }
  160. // mergeActivationExpiry reconciles a node-reported client expiry with the value
  161. // already stored on the master. "Start after first connect" persists a negative
  162. // duration that each node converts to an absolute deadline (now+duration) the
  163. // first time the client connects there. The per-email client_traffics row is
  164. // shared across every node, so a node that has not yet seen a first connection
  165. // keeps reporting the negative duration — which must never reset a deadline
  166. // another node already activated.
  167. //
  168. // A node may legitimately move an already-activated deadline forward (traffic
  169. // reset / auto-renew extends it), so any positive node value is still adopted —
  170. // only an un-activated (<= 0) value is rejected once an absolute deadline
  171. // exists. Kept in lockstep with the SQL CASE in setRemoteTrafficLocked.
  172. func mergeActivationExpiry(existing, node int64) int64 {
  173. if existing > 0 && node <= 0 {
  174. return existing
  175. }
  176. return node
  177. }
  178. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  179. var structuralChange bool
  180. err := submitTrafficWrite(func() error {
  181. var inner error
  182. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  183. return inner
  184. })
  185. return structuralChange, err
  186. }
  187. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  188. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  189. // this to derive per-inbound speed for the dashboard — node inbounds have no
  190. // local Xray poll to produce live deltas the way local inbounds do.
  191. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  192. var rows []struct {
  193. Tag string
  194. Up int64
  195. Down int64
  196. }
  197. if err := database.GetDB().Table("inbounds").
  198. Select("tag, up, down").
  199. Where("node_id IS NOT NULL").
  200. Scan(&rows).Error; err != nil {
  201. return nil, err
  202. }
  203. out := make(map[string][2]int64, len(rows))
  204. for _, r := range rows {
  205. out[r.Tag] = [2]int64{r.Up, r.Down}
  206. }
  207. return out, nil
  208. }
  209. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  210. if snap == nil || nodeID <= 0 {
  211. return false, nil
  212. }
  213. db := database.GetDB()
  214. now := time.Now().UnixMilli()
  215. // originGuidFor attributes a synced inbound to the panel that physically
  216. // hosts it. A node's OWN inbounds report either an empty origin or — on
  217. // builds that set it locally — the node's own panelGuid; both resolve to
  218. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  219. // (shared with another node or the master, i.e. a cloned server), in which
  220. // case it falls back to the node-unique id so #4983 attribution doesn't
  221. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  222. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  223. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  224. var nodeRow model.Node
  225. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  226. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  227. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  228. originGuidFor := func(snapIb *model.Inbound) string {
  229. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  230. return snapIb.OriginNodeGuid
  231. }
  232. return selfKey
  233. }
  234. var central []model.Inbound
  235. if err := db.Model(model.Inbound{}).
  236. Where("node_id = ?", nodeID).
  237. Find(&central).Error; err != nil {
  238. return false, err
  239. }
  240. // Index under the stored tag and its prefix-flipped form so a snap matches
  241. // whether the n<id>- prefix lives on the node side, the central side, or
  242. // neither — a mismatch must never spawn a duplicate central inbound.
  243. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  244. prefix := nodeTagPrefix(&nodeID)
  245. for i := range central {
  246. tagToCentral[central[i].Tag] = &central[i]
  247. if prefix != "" {
  248. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  249. tagToCentral[stripped] = &central[i]
  250. } else {
  251. tagToCentral[prefix+central[i].Tag] = &central[i]
  252. }
  253. }
  254. }
  255. var centralClientStats []xray.ClientTraffic
  256. if len(central) > 0 {
  257. ids := make([]int, 0, len(central))
  258. for i := range central {
  259. ids = append(ids, central[i].Id)
  260. }
  261. if err := db.Model(xray.ClientTraffic{}).
  262. Where("inbound_id IN ?", ids).
  263. Find(&centralClientStats).Error; err != nil {
  264. return false, err
  265. }
  266. }
  267. type csKey struct {
  268. inboundID int
  269. email string
  270. }
  271. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  272. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  273. for i := range centralClientStats {
  274. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  275. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  276. }
  277. nodeBaselines := make(map[string]nodeTrafficCounter)
  278. var baselineRows []model.NodeClientTraffic
  279. if err := db.Model(&model.NodeClientTraffic{}).
  280. Where("node_id = ?", nodeID).
  281. Find(&baselineRows).Error; err != nil {
  282. return false, err
  283. }
  284. for i := range baselineRows {
  285. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  286. }
  287. var defaultUserId int
  288. if len(central) > 0 {
  289. defaultUserId = central[0].UserId
  290. } else {
  291. var u model.User
  292. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  293. defaultUserId = u.Id
  294. } else {
  295. defaultUserId = 1
  296. }
  297. }
  298. // Union of every email the snapshot still reports, across all inbounds.
  299. // The (node, email) baseline rows are keyed per node, not per inbound, so
  300. // the sweeps below must only drop one when the email left the node
  301. // entirely — an email whose stats moved to (or always lived under) a
  302. // sibling inbound still needs its baseline for the sibling's delta
  303. // computation (#5202).
  304. //
  305. // Xray counts traffic per email, not per inbound, so a multi-attached
  306. // client's shared counter is copied onto every inbound it's on. Fold each
  307. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  308. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  309. snapEmailsAll := make(map[string]struct{})
  310. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  311. for _, snapIb := range snap.Inbounds {
  312. if snapIb == nil {
  313. continue
  314. }
  315. for i := range snapIb.ClientStats {
  316. email := snapIb.ClientStats[i].Email
  317. snapEmailsAll[email] = struct{}{}
  318. cur := nodeEmailTotals[email]
  319. if snapIb.ClientStats[i].Up > cur.Up {
  320. cur.Up = snapIb.ClientStats[i].Up
  321. }
  322. if snapIb.ClientStats[i].Down > cur.Down {
  323. cur.Down = snapIb.ClientStats[i].Down
  324. }
  325. nodeEmailTotals[email] = cur
  326. }
  327. }
  328. // Membership set for the rowExists checks below. Only the snapshot's emails
  329. // are ever probed, so scope the lookup to those instead of plucking the whole
  330. // client_traffics table (50k+ rows) on every node poll.
  331. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  332. if len(snapEmailsAll) > 0 {
  333. snapEmailList := make([]string, 0, len(snapEmailsAll))
  334. for email := range snapEmailsAll {
  335. snapEmailList = append(snapEmailList, email)
  336. }
  337. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  338. var found []string
  339. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  340. return false, err
  341. }
  342. for _, e := range found {
  343. existingEmails[e] = struct{}{}
  344. }
  345. }
  346. }
  347. tx := db.Begin()
  348. committed := false
  349. defer func() {
  350. if !committed {
  351. tx.Rollback()
  352. }
  353. }()
  354. structuralChange := false
  355. newInboundIDs := make(map[int]struct{})
  356. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  357. for _, snapIb := range snap.Inbounds {
  358. if snapIb == nil {
  359. continue
  360. }
  361. snapTags[snapIb.Tag] = struct{}{}
  362. // Record the prefix-flipped form too so the orphan sweep below keeps a
  363. // central inbound whether its tag carries the n<id>- prefix or not.
  364. if prefix != "" {
  365. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  366. snapTags[stripped] = struct{}{}
  367. } else {
  368. snapTags[prefix+snapIb.Tag] = struct{}{}
  369. }
  370. }
  371. c, ok := tagToCentral[snapIb.Tag]
  372. if !ok {
  373. if dirty {
  374. continue
  375. }
  376. // Try snap.Tag first; on collision fall back to the n<id>-
  377. // prefixed form so local+node can both own the same port.
  378. pickFreeTag := func() (string, error) {
  379. candidates := []string{snapIb.Tag}
  380. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  381. candidates = append(candidates, prefix+snapIb.Tag)
  382. }
  383. for _, t := range candidates {
  384. var owner model.Inbound
  385. err := tx.Where("tag = ?", t).First(&owner).Error
  386. if errors.Is(err, gorm.ErrRecordNotFound) {
  387. return t, nil
  388. }
  389. if err != nil {
  390. return "", err
  391. }
  392. }
  393. return "", nil
  394. }
  395. chosenTag, err := pickFreeTag()
  396. if err != nil {
  397. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  398. continue
  399. }
  400. if chosenTag == "" {
  401. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  402. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  403. logger.Warningf(
  404. "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)",
  405. snapIb.Tag, nodeID, nodeID,
  406. )
  407. }
  408. continue
  409. }
  410. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  411. newIb := model.Inbound{
  412. UserId: defaultUserId,
  413. NodeID: &nodeID,
  414. OriginNodeGuid: originGuidFor(snapIb),
  415. Tag: chosenTag,
  416. Listen: snapIb.Listen,
  417. Port: snapIb.Port,
  418. Protocol: snapIb.Protocol,
  419. Settings: snapIb.Settings,
  420. StreamSettings: snapIb.StreamSettings,
  421. Sniffing: snapIb.Sniffing,
  422. TrafficReset: snapIb.TrafficReset,
  423. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  424. Enable: snapIb.Enable,
  425. Remark: snapIb.Remark,
  426. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  427. Total: snapIb.Total,
  428. ExpiryTime: snapIb.ExpiryTime,
  429. Up: snapIb.Up,
  430. Down: snapIb.Down,
  431. ShareAddrStrategy: "node",
  432. }
  433. if err := tx.Create(&newIb).Error; err != nil {
  434. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  435. continue
  436. }
  437. tagToCentral[snapIb.Tag] = &newIb
  438. if newIb.Tag != snapIb.Tag {
  439. tagToCentral[newIb.Tag] = &newIb
  440. }
  441. newInboundIDs[newIb.Id] = struct{}{}
  442. structuralChange = true
  443. continue
  444. }
  445. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  446. updates := map[string]any{}
  447. if !dirty {
  448. updates["enable"] = snapIb.Enable
  449. updates["remark"] = snapIb.Remark
  450. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  451. updates["listen"] = snapIb.Listen
  452. updates["port"] = snapIb.Port
  453. updates["protocol"] = snapIb.Protocol
  454. updates["total"] = snapIb.Total
  455. updates["expiry_time"] = snapIb.ExpiryTime
  456. updates["settings"] = snapIb.Settings
  457. updates["stream_settings"] = snapIb.StreamSettings
  458. updates["sniffing"] = snapIb.Sniffing
  459. updates["traffic_reset"] = snapIb.TrafficReset
  460. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  461. }
  462. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  463. updates["up"] = snapIb.Up
  464. updates["down"] = snapIb.Down
  465. }
  466. // Physical-home attribution is independent of config-dirty state, so
  467. // keep it current even while the node has pending offline edits. Writes
  468. // once to backfill an existing row, then stays equal (#4983).
  469. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  470. updates["origin_node_guid"] = og
  471. }
  472. if !dirty && (c.Settings != snapIb.Settings ||
  473. c.Remark != snapIb.Remark ||
  474. c.Listen != snapIb.Listen ||
  475. c.Port != snapIb.Port ||
  476. c.Total != snapIb.Total ||
  477. c.ExpiryTime != snapIb.ExpiryTime ||
  478. c.Enable != snapIb.Enable) {
  479. structuralChange = true
  480. }
  481. if len(updates) > 0 {
  482. if err := tx.Model(model.Inbound{}).
  483. Where("id = ?", c.Id).
  484. Updates(updates).Error; err != nil {
  485. return false, err
  486. }
  487. }
  488. }
  489. for _, c := range central {
  490. if dirty {
  491. continue
  492. }
  493. if len(snapTags) == 0 {
  494. // A node mid-restart or with a transient DB error can return an empty
  495. // inbound list with success=true. Treat "zero inbounds reported" as
  496. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  497. // wipes the node's central inbounds and every client on them (and
  498. // resets traffic history on re-create). A real per-inbound deletion
  499. // still sweeps, because the node keeps reporting its other inbounds.
  500. continue
  501. }
  502. if _, kept := snapTags[c.Tag]; kept {
  503. continue
  504. }
  505. var goneEmails []string
  506. if err := tx.Model(xray.ClientTraffic{}).
  507. Where("inbound_id = ?", c.Id).
  508. Pluck("email", &goneEmails).Error; err != nil {
  509. return false, err
  510. }
  511. if len(goneEmails) > 0 {
  512. // Baselines are per (node, email), not per inbound: keep them for
  513. // emails the snapshot still reports under a sibling inbound (#5202).
  514. baselineGone := make([]string, 0, len(goneEmails))
  515. for _, e := range goneEmails {
  516. if _, still := snapEmailsAll[e]; !still {
  517. baselineGone = append(baselineGone, e)
  518. }
  519. }
  520. // Chunk to avoid SQLite bind var limit when a node has many clients
  521. // removed (e.g. after API bulk delete or structural change on node inbound).
  522. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  523. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  524. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  525. return false, err
  526. }
  527. }
  528. // The per-email row is the shared accumulator across every inbound
  529. // (and node) the email is attached to. Only drop it when this was the
  530. // email's last inbound — wiping it while a sibling still feeds it
  531. // loses the summed history, and the next node sync would re-seed the
  532. // row with that node's counter alone.
  533. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  534. if sErr != nil {
  535. return false, sErr
  536. }
  537. delEmails := make([]string, 0, len(goneEmails))
  538. for _, e := range goneEmails {
  539. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  540. delEmails = append(delEmails, e)
  541. }
  542. }
  543. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  544. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  545. Delete(&xray.ClientTraffic{}).Error; err != nil {
  546. return false, err
  547. }
  548. }
  549. }
  550. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  551. return false, err
  552. }
  553. if err := tx.Where("id = ?", c.Id).
  554. Delete(&model.Inbound{}).Error; err != nil {
  555. return false, err
  556. }
  557. delete(tagToCentral, c.Tag)
  558. structuralChange = true
  559. }
  560. for _, snapIb := range snap.Inbounds {
  561. if snapIb == nil {
  562. continue
  563. }
  564. c, ok := tagToCentral[snapIb.Tag]
  565. if !ok {
  566. continue
  567. }
  568. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  569. for _, cs := range snapIb.ClientStats {
  570. snapEmails[cs.Email] = struct{}{}
  571. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  572. canon := nodeEmailTotals[cs.Email]
  573. base, seen := nodeBaselines[cs.Email]
  574. var deltaUp, deltaDown int64
  575. if seen {
  576. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  577. deltaUp = 0
  578. }
  579. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  580. deltaDown = 0
  581. }
  582. }
  583. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  584. if dirty {
  585. continue
  586. }
  587. var seedUp, seedDown int64
  588. if _, isNewInbound := newInboundIDs[c.Id]; isNewInbound && !isClientEmailTombstoned(cs.Email) {
  589. seedUp, seedDown = canon.Up, canon.Down
  590. }
  591. row := &xray.ClientTraffic{
  592. InboundId: c.Id,
  593. Email: cs.Email,
  594. Enable: cs.Enable,
  595. Total: cs.Total,
  596. ExpiryTime: cs.ExpiryTime,
  597. Reset: cs.Reset,
  598. Up: seedUp,
  599. Down: seedDown,
  600. LastOnline: cs.LastOnline,
  601. }
  602. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  603. Create(row).Error; err != nil {
  604. return false, err
  605. }
  606. centralCS[csKey{c.Id, cs.Email}] = row
  607. centralCSByEmail[cs.Email] = row
  608. existingEmails[cs.Email] = struct{}{}
  609. structuralChange = true
  610. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  611. return false, err
  612. }
  613. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  614. continue
  615. }
  616. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  617. (existing.Enable != cs.Enable ||
  618. existing.Total != cs.Total ||
  619. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  620. existing.Reset != cs.Reset) {
  621. structuralChange = true
  622. }
  623. enableExpr := database.ClientTrafficEnableMergeExpr()
  624. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  625. // yet seen the client's first connection keeps reporting the negative
  626. // "start after first connect" duration, which must never reset the
  627. // absolute deadline another node already activated. A positive node
  628. // value is still adopted (e.g. auto-renew moves the deadline forward).
  629. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  630. // infer int4 from the literal and overflow on real expiry values.
  631. if err := tx.Exec(
  632. fmt.Sprintf(
  633. `UPDATE client_traffics
  634. SET up = up + ?, down = down + ?, enable = %s, total = ?,
  635. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  636. reset = ?, last_online = %s
  637. WHERE email = ?`,
  638. enableExpr,
  639. database.GreatestExpr("last_online", "?"),
  640. ),
  641. deltaUp, deltaDown, cs.Enable, cs.Total,
  642. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  643. cs.LastOnline, cs.Email,
  644. ).Error; err != nil {
  645. return false, err
  646. }
  647. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  648. return false, err
  649. }
  650. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  651. }
  652. for k, existing := range centralCS {
  653. if dirty {
  654. continue
  655. }
  656. if k.inboundID != c.Id {
  657. continue
  658. }
  659. if _, kept := snapEmails[k.email]; kept {
  660. continue
  661. }
  662. // Gone from this inbound's stats but still reported by the node under
  663. // a sibling inbound: both the shared accumulator row and the (node,
  664. // email) baseline must survive, or the sibling's next delta would
  665. // compute against nothing and freeze the counter (#5202).
  666. if _, still := snapEmailsAll[k.email]; still {
  667. continue
  668. }
  669. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  670. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  671. return false, err
  672. }
  673. // Same shared-accumulator rule as the inbound-removal sweep above:
  674. // keep the row while another inbound still references the email.
  675. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  676. if uErr != nil {
  677. return false, uErr
  678. }
  679. if !stillUsed {
  680. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  681. Delete(&xray.ClientTraffic{}).Error; err != nil {
  682. return false, err
  683. }
  684. }
  685. structuralChange = true
  686. }
  687. }
  688. type oldSet struct {
  689. inboundID int
  690. emails map[string]struct{}
  691. }
  692. var perInboundOld []oldSet
  693. for _, snapIb := range snap.Inbounds {
  694. if snapIb == nil {
  695. continue
  696. }
  697. c, ok := tagToCentral[snapIb.Tag]
  698. if !ok {
  699. continue
  700. }
  701. if dirty {
  702. continue
  703. }
  704. var oldEmailsRows []string
  705. if err := tx.Table("clients").
  706. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  707. Where("client_inbounds.inbound_id = ?", c.Id).
  708. Pluck("email", &oldEmailsRows).Error; err == nil {
  709. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  710. for _, e := range oldEmailsRows {
  711. if e != "" {
  712. oldEmails[e] = struct{}{}
  713. }
  714. }
  715. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  716. }
  717. clients, gcErr := s.GetClients(snapIb)
  718. if gcErr != nil {
  719. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  720. continue
  721. }
  722. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  723. for _, cs := range snapIb.ClientStats {
  724. csEnableByEmail[cs.Email] = cs.Enable
  725. }
  726. filtered := clients[:0]
  727. for i := range clients {
  728. if isClientEmailTombstoned(clients[i].Email) {
  729. continue
  730. }
  731. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  732. clients[i].Enable = false
  733. }
  734. filtered = append(filtered, clients[i])
  735. }
  736. localEmails := make([]string, 0, len(filtered))
  737. for i := range filtered {
  738. if filtered[i].Email != "" {
  739. localEmails = append(localEmails, filtered[i].Email)
  740. }
  741. }
  742. if len(localEmails) > 0 {
  743. var localMeta []struct {
  744. Email string
  745. Comment string `gorm:"column:comment"`
  746. }
  747. if err := tx.Table("clients").
  748. Select("email, comment").
  749. Where("email IN ?", localEmails).
  750. Find(&localMeta).Error; err == nil {
  751. commentByEmail := make(map[string]string, len(localMeta))
  752. for _, m := range localMeta {
  753. commentByEmail[m.Email] = m.Comment
  754. }
  755. for i := range filtered {
  756. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  757. filtered[i].Comment = cmt
  758. }
  759. }
  760. }
  761. }
  762. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  763. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  764. }
  765. }
  766. for _, old := range perInboundOld {
  767. var stillAttached []string
  768. if err := tx.Table("clients").
  769. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  770. Where("client_inbounds.inbound_id = ?", old.inboundID).
  771. Pluck("email", &stillAttached).Error; err != nil {
  772. continue
  773. }
  774. stillSet := make(map[string]struct{}, len(stillAttached))
  775. for _, e := range stillAttached {
  776. stillSet[e] = struct{}{}
  777. }
  778. for email := range old.emails {
  779. if _, kept := stillSet[email]; kept {
  780. continue
  781. }
  782. var attachmentCount int64
  783. if err := tx.Table("client_inbounds").
  784. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  785. Where("clients.email = ?", email).
  786. Count(&attachmentCount).Error; err != nil {
  787. continue
  788. }
  789. if attachmentCount > 0 {
  790. continue
  791. }
  792. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  793. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  794. }
  795. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  796. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  797. }
  798. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  799. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  800. }
  801. structuralChange = true
  802. }
  803. }
  804. if err := tx.Commit().Error; err != nil {
  805. return false, err
  806. }
  807. committed = true
  808. if p != nil {
  809. tree := snap.OnlineTree
  810. switch {
  811. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  812. // Old-build node (no GUID tree): key its flat online list under its
  813. // own effective identity so attribution still works for that branch.
  814. tree = map[string][]string{selfKey: snap.OnlineEmails}
  815. case guidShared && len(tree) > 0:
  816. // Newer cloned node: its own clients arrive keyed under the shared
  817. // panelGuid. Remap just that entry to the node-unique key so the
  818. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  819. if _, ok := tree[nodeRow.Guid]; ok {
  820. remapped := make(map[string][]string, len(tree))
  821. for g, emails := range tree {
  822. if g == nodeRow.Guid {
  823. g = selfKey
  824. }
  825. remapped[g] = emails
  826. }
  827. tree = remapped
  828. }
  829. }
  830. p.SetNodeOnlineTree(nodeID, tree)
  831. }
  832. return structuralChange, nil
  833. }
  834. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  835. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  836. if err != nil {
  837. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  838. return
  839. }
  840. if !restartOnDisable {
  841. return
  842. }
  843. for _, nodeID := range nodeIDs {
  844. nodeIDCopy := nodeID
  845. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  846. if rtErr != nil {
  847. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  848. continue
  849. }
  850. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  851. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  852. }
  853. }
  854. }
  855. func (s *InboundService) GetOnlineClients() []string {
  856. if p == nil {
  857. return []string{}
  858. }
  859. return p.GetOnlineClients()
  860. }
  861. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  862. // node that physically hosts each set: this panel's own clients under its own
  863. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  864. // node-id keying so a client three hops down is attributed to its real node,
  865. // not the intermediate one it was synced through.
  866. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  867. if p == nil {
  868. return map[string][]string{}
  869. }
  870. out := p.GetMergedNodeTrees()
  871. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  872. if guid := s.panelGuid(); guid != "" {
  873. out[guid] = mergeEmails(out[guid], local)
  874. }
  875. }
  876. return out
  877. }
  878. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  879. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  880. // report per-inbound activity, so a GUID missing from the map means "don't
  881. // gate" for that node's inbounds.
  882. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  883. if p == nil {
  884. return map[string][]string{}
  885. }
  886. active := p.GetLocalActiveInbounds()
  887. if len(active) == 0 {
  888. return map[string][]string{}
  889. }
  890. guid := s.panelGuid()
  891. if guid == "" {
  892. return map[string][]string{}
  893. }
  894. return map[string][]string{guid: active}
  895. }
  896. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  897. if p != nil {
  898. p.SetNodeOnlineTree(nodeID, tree)
  899. }
  900. }
  901. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  902. if p != nil {
  903. p.ClearNodeOnlineClients(nodeID)
  904. }
  905. }
  906. // panelGuid returns this panel's stable self-identifier, used to key the local
  907. // panel's own clients in the per-node online maps (#4983).
  908. func (s *InboundService) panelGuid() string {
  909. guid, _ := (&SettingService{}).GetPanelGuid()
  910. return guid
  911. }
  912. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  913. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  914. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  915. // flat-topology case where an old-build node appears.
  916. func synthNodeGuid(nodeID int) string {
  917. return fmt.Sprintf("node:%d", nodeID)
  918. }
  919. // mergeEmails returns the deduped union of two email slices.
  920. func mergeEmails(a, b []string) []string {
  921. if len(a) == 0 {
  922. return b
  923. }
  924. seen := make(map[string]struct{}, len(a)+len(b))
  925. out := make([]string, 0, len(a)+len(b))
  926. for _, e := range a {
  927. if _, ok := seen[e]; !ok {
  928. seen[e] = struct{}{}
  929. out = append(out, e)
  930. }
  931. }
  932. for _, e := range b {
  933. if _, ok := seen[e]; !ok {
  934. seen[e] = struct{}{}
  935. out = append(out, e)
  936. }
  937. }
  938. return out
  939. }
  940. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  941. db := database.GetDB()
  942. var rows []xray.ClientTraffic
  943. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  944. if err != nil && err != gorm.ErrRecordNotFound {
  945. return nil, err
  946. }
  947. result := make(map[string]int64, len(rows))
  948. for _, r := range rows {
  949. result[r.Email] = r.LastOnline
  950. }
  951. return result, nil
  952. }
  953. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  954. // panel's own xray this poll into the local online/active sets, applying the
  955. // grace window and pruning stale entries. Pass nil to only prune. See
  956. // xray.Process for why the local sets are kept separate from the shared
  957. // last_online column.
  958. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  959. if p != nil {
  960. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  961. }
  962. }
  963. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  964. db := database.GetDB()
  965. // Step 1: Get ClientTraffic records for emails in the input list.
  966. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  967. uniqEmails := uniqueNonEmptyStrings(emails)
  968. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  969. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  970. var page []xray.ClientTraffic
  971. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  972. return nil, nil, err
  973. }
  974. clients = append(clients, page...)
  975. }
  976. // Step 2: Sort clients by (Up + Down) descending
  977. sort.Slice(clients, func(i, j int) bool {
  978. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  979. })
  980. // Step 3: Extract sorted valid emails and track found ones
  981. validEmails := make([]string, 0, len(clients))
  982. found := make(map[string]bool)
  983. for _, client := range clients {
  984. validEmails = append(validEmails, client.Email)
  985. found[client.Email] = true
  986. }
  987. // Step 4: Identify emails that were not found in the database
  988. extraEmails := make([]string, 0)
  989. for _, email := range emails {
  990. if !found[email] {
  991. extraEmails = append(extraEmails, email)
  992. }
  993. }
  994. return validEmails, extraEmails, nil
  995. }