inbound_node.go 33 KB

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