mtproto_job.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package job
  2. import (
  3. "github.com/mhsanaei/3x-ui/v3/database/model"
  4. "github.com/mhsanaei/3x-ui/v3/logger"
  5. "github.com/mhsanaei/3x-ui/v3/mtproto"
  6. "github.com/mhsanaei/3x-ui/v3/web/service"
  7. "github.com/mhsanaei/3x-ui/v3/xray"
  8. )
  9. // MtprotoJob reconciles the running mtg sidecar processes against the enabled
  10. // mtproto inbounds in the database, restarts any that crashed, and folds the
  11. // per-inbound traffic scraped from each mtg metrics endpoint into the usual
  12. // inbound traffic accounting.
  13. type MtprotoJob struct {
  14. inboundService service.InboundService
  15. }
  16. // NewMtprotoJob creates a new mtproto reconcile/traffic job instance.
  17. func NewMtprotoJob() *MtprotoJob {
  18. return new(MtprotoJob)
  19. }
  20. // Run reconciles desired mtproto inbounds with running mtg processes and
  21. // records traffic deltas.
  22. func (j *MtprotoJob) Run() {
  23. inbounds, err := j.inboundService.GetAllInbounds()
  24. if err != nil {
  25. logger.Warning("mtproto job: get inbounds failed:", err)
  26. return
  27. }
  28. var desired []mtproto.Instance
  29. for _, ib := range inbounds {
  30. if ib.Protocol != model.MTProto || !ib.Enable || ib.NodeID != nil {
  31. continue
  32. }
  33. if inst, ok := mtproto.InstanceFromInbound(ib); ok {
  34. desired = append(desired, inst)
  35. }
  36. }
  37. mgr := mtproto.GetManager()
  38. mgr.Reconcile(desired)
  39. deltas := mgr.CollectTraffic()
  40. if len(deltas) == 0 {
  41. return
  42. }
  43. traffics := make([]*xray.Traffic, 0, len(deltas))
  44. for _, d := range deltas {
  45. traffics = append(traffics, &xray.Traffic{
  46. IsInbound: true,
  47. Tag: d.Tag,
  48. Up: d.Up,
  49. Down: d.Down,
  50. })
  51. }
  52. if _, _, err := j.inboundService.AddTraffic(traffics, nil); err != nil {
  53. logger.Warning("mtproto job: add traffic failed:", err)
  54. }
  55. }