mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 22:14:50 +03:00
feat(traffic): separate depletion restarts from client disables (#7267)
One switch decided two things: whether Xray restarts when a client is disabled or deleted by hand, and whether it restarts when a client runs out of quota or expires. A panel that takes many API deletes had to choose between a restart on each of them and leaving depleted clients' open connections alive. Add a switch for the quota and expiry case. It inherits the old switch until it is saved, and older settings clients may omit it. A depletion asks for one restart per affected running core per committed batch: the local core when a local inbound served the client, and each affected node through the node API. A master whose nodes alone served the client is not restarted. With the new switch off, a depleted client is still removed from the running core and from its config snapshot, so a later reconcile does not restart for it either. Also add a node traffic fetch timeout setting (1 to 30 seconds, default 4). Run on a panel with real cores: with the old switch off and the new one on, a stream through a client that crossed its quota was cut within one poll and the lifecycle log names client_depletion; with them swapped, the stream and the core survived. A depletion a node detects itself follows that node's own switches. Refs #7145
This commit is contained in:
@@ -27,9 +27,11 @@ inbounds** at once, with per-client traffic accounting.
|
||||
| **Comment** | all | Free-text note. |
|
||||
|
||||
<Callout type="info">
|
||||
Reaching the **traffic** or **expiry** limit disables the client, and a client
|
||||
disabled or deleted by hand counts too; the panel restarts Xray then
|
||||
(`restartXrayOnClientDisable`, on by default).
|
||||
Reaching the **traffic** or **expiry** limit disables the client.
|
||||
`restartXrayOnClientDepleted` controls whether Xray restarts to close the
|
||||
client's existing sessions. Manual disable and delete use
|
||||
`restartXrayOnClientDisable`. The new setting inherits the old value until
|
||||
explicitly configured.
|
||||
</Callout>
|
||||
|
||||
## Block a subscription device
|
||||
|
||||
@@ -172,3 +172,16 @@ a 2xx status within 3 seconds, the panel drops that batch, logs one warning
|
||||
with the reason, and logs again when deliveries resume. Deltas waiting for the
|
||||
next send are held in memory: disabling the webhook or a panel process exit
|
||||
discards them.
|
||||
|
||||
### Xray restart policy
|
||||
|
||||
**Restart Xray on client quota or expiry** is independent of the existing
|
||||
disable/delete switch. It can close already accepted sessions for clients
|
||||
disabled automatically on the panel or on a managed node. Restarts are coalesced
|
||||
per depletion batch and per affected node. Remote restart requests use a bounded
|
||||
best-effort call. If the new setting is unset, it inherits the old switch until
|
||||
saved explicitly.
|
||||
|
||||
**Node traffic fetch timeout** defaults to 4 seconds and accepts values from
|
||||
1 to 30 seconds. It applies to the snapshot fetch. Local traffic polling keeps
|
||||
its existing cadence.
|
||||
|
||||
@@ -177,6 +177,10 @@
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -211,6 +215,10 @@
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -733,6 +741,7 @@
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
@@ -1075,6 +1084,10 @@
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -1109,6 +1122,10 @@
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -1641,6 +1658,7 @@
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
|
||||
@@ -177,6 +177,10 @@
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -211,6 +215,10 @@
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -733,6 +741,7 @@
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
@@ -1075,6 +1084,10 @@
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -1109,6 +1122,10 @@
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -1641,6 +1658,7 @@
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
|
||||
@@ -44,6 +44,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"networkTrafficInterface": "eth0",
|
||||
"networkTrafficMode": "legacy",
|
||||
"nodeDownThreshold": 1,
|
||||
"nodeTrafficFetchTimeout": 4,
|
||||
"outboundDownThreshold": 1,
|
||||
"pageSize": 0,
|
||||
"panelOutbound": "",
|
||||
@@ -53,6 +54,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"publicIpv6Override": "",
|
||||
"realityScanCandidates": "",
|
||||
"remarkTemplate": "",
|
||||
"restartXrayOnClientDepleted": null,
|
||||
"restartXrayOnClientDisable": false,
|
||||
"sessionMaxAge": 1,
|
||||
"smtpCpu": 0,
|
||||
@@ -257,6 +259,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"networkTrafficInterface": "eth0",
|
||||
"networkTrafficMode": "legacy",
|
||||
"nodeDownThreshold": 1,
|
||||
"nodeTrafficFetchTimeout": 4,
|
||||
"outboundDownThreshold": 1,
|
||||
"pageSize": 0,
|
||||
"panelOutbound": "",
|
||||
@@ -266,6 +269,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"publicIpv6Override": "",
|
||||
"realityScanCandidates": "",
|
||||
"remarkTemplate": "",
|
||||
"restartXrayOnClientDepleted": null,
|
||||
"restartXrayOnClientDisable": false,
|
||||
"sessionMaxAge": 1,
|
||||
"smtpCpu": 0,
|
||||
|
||||
@@ -151,6 +151,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -185,6 +189,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -707,6 +715,7 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
@@ -1049,6 +1058,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"minimum": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"nodeTrafficFetchTimeout": {
|
||||
"example": 4,
|
||||
"type": "integer"
|
||||
},
|
||||
"outboundDownThreshold": {
|
||||
"maximum": 100,
|
||||
"minimum": 1,
|
||||
@@ -1083,6 +1096,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"remarkTemplate": {
|
||||
"type": "string"
|
||||
},
|
||||
"restartXrayOnClientDepleted": {
|
||||
"nullable": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"restartXrayOnClientDisable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -1615,6 +1632,7 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"networkTrafficInterface",
|
||||
"networkTrafficMode",
|
||||
"nodeDownThreshold",
|
||||
"nodeTrafficFetchTimeout",
|
||||
"outboundDownThreshold",
|
||||
"pageSize",
|
||||
"panelOutbound",
|
||||
|
||||
@@ -49,6 +49,7 @@ export interface AllSetting {
|
||||
networkTrafficInterface: string;
|
||||
networkTrafficMode: string;
|
||||
nodeDownThreshold: number;
|
||||
nodeTrafficFetchTimeout: number;
|
||||
outboundDownThreshold: number;
|
||||
pageSize: number;
|
||||
panelOutbound: string;
|
||||
@@ -58,6 +59,7 @@ export interface AllSetting {
|
||||
publicIpv6Override: string;
|
||||
realityScanCandidates: string;
|
||||
remarkTemplate: string;
|
||||
restartXrayOnClientDepleted?: boolean | null;
|
||||
restartXrayOnClientDisable: boolean;
|
||||
sessionMaxAge: number;
|
||||
smtpCpu: number;
|
||||
@@ -263,6 +265,7 @@ export interface AllSettingView {
|
||||
networkTrafficInterface: string;
|
||||
networkTrafficMode: string;
|
||||
nodeDownThreshold: number;
|
||||
nodeTrafficFetchTimeout: number;
|
||||
outboundDownThreshold: number;
|
||||
pageSize: number;
|
||||
panelOutbound: string;
|
||||
@@ -272,6 +275,7 @@ export interface AllSettingView {
|
||||
publicIpv6Override: string;
|
||||
realityScanCandidates: string;
|
||||
remarkTemplate: string;
|
||||
restartXrayOnClientDepleted?: boolean | null;
|
||||
restartXrayOnClientDisable: boolean;
|
||||
sessionMaxAge: number;
|
||||
smtpCpu: number;
|
||||
|
||||
@@ -59,6 +59,7 @@ export const AllSettingSchema = z.object({
|
||||
networkTrafficInterface: z.string(),
|
||||
networkTrafficMode: z.enum(['legacy', 'auto', 'manual']),
|
||||
nodeDownThreshold: z.number().int().min(1).max(100),
|
||||
nodeTrafficFetchTimeout: z.number().int(),
|
||||
outboundDownThreshold: z.number().int().min(1).max(100),
|
||||
pageSize: z.number().int().min(0).max(1000),
|
||||
panelOutbound: z.string(),
|
||||
@@ -68,6 +69,7 @@ export const AllSettingSchema = z.object({
|
||||
publicIpv6Override: z.string(),
|
||||
realityScanCandidates: z.string(),
|
||||
remarkTemplate: z.string(),
|
||||
restartXrayOnClientDepleted: z.boolean().nullable().optional(),
|
||||
restartXrayOnClientDisable: z.boolean(),
|
||||
sessionMaxAge: z.number().int().min(1).max(525600),
|
||||
smtpCpu: z.number().int().min(0).max(100),
|
||||
@@ -274,6 +276,7 @@ export const AllSettingViewSchema = z.object({
|
||||
networkTrafficInterface: z.string(),
|
||||
networkTrafficMode: z.enum(['legacy', 'auto', 'manual']),
|
||||
nodeDownThreshold: z.number().int().min(1).max(100),
|
||||
nodeTrafficFetchTimeout: z.number().int(),
|
||||
outboundDownThreshold: z.number().int().min(1).max(100),
|
||||
pageSize: z.number().int().min(0).max(1000),
|
||||
panelOutbound: z.string(),
|
||||
@@ -283,6 +286,7 @@ export const AllSettingViewSchema = z.object({
|
||||
publicIpv6Override: z.string(),
|
||||
realityScanCandidates: z.string(),
|
||||
remarkTemplate: z.string(),
|
||||
restartXrayOnClientDepleted: z.boolean().nullable().optional(),
|
||||
restartXrayOnClientDisable: z.boolean(),
|
||||
sessionMaxAge: z.number().int().min(1).max(525600),
|
||||
smtpCpu: z.number().int().min(0).max(100),
|
||||
|
||||
@@ -78,6 +78,8 @@ export class AllSetting {
|
||||
externalTrafficInformInterval = 5;
|
||||
externalTrafficInformURI = '';
|
||||
restartXrayOnClientDisable = true;
|
||||
restartXrayOnClientDepleted = true;
|
||||
nodeTrafficFetchTimeout = 4;
|
||||
mcpEnable = false;
|
||||
subCertFile = '';
|
||||
subKeyFile = '';
|
||||
|
||||
@@ -402,6 +402,26 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
|
||||
onChange={(v) => updateSetting({ restartXrayOnClientDisable: v })}
|
||||
/>
|
||||
</SettingListItem>
|
||||
<SettingListItem
|
||||
paddings="small"
|
||||
title={t('pages.settings.restartXrayOnClientDepleted')}
|
||||
>
|
||||
<Switch
|
||||
aria-label={t('pages.settings.restartXrayOnClientDepleted')}
|
||||
checked={allSetting.restartXrayOnClientDepleted}
|
||||
onChange={(v) => updateSetting({ restartXrayOnClientDepleted: v })}
|
||||
/>
|
||||
</SettingListItem>
|
||||
<SettingListItem paddings="small" title={t('pages.settings.nodeTrafficFetchTimeout')}>
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={30}
|
||||
precision={0}
|
||||
aria-label={t('pages.settings.nodeTrafficFetchTimeout')}
|
||||
value={allSetting.nodeTrafficFetchTimeout}
|
||||
onChange={onNumber((v) => updateSetting({ nodeTrafficFetchTimeout: v }))}
|
||||
/>
|
||||
</SettingListItem>
|
||||
|
||||
<SettingListItem paddings="small" title={t('pages.settings.language')}>
|
||||
<Select
|
||||
|
||||
@@ -89,6 +89,8 @@ export const AllSettingFieldsSchema = z
|
||||
externalTrafficInformURI: z.string().optional(),
|
||||
externalTrafficInformInterval: z.number().int().min(5).max(3600).optional(),
|
||||
restartXrayOnClientDisable: z.boolean().optional(),
|
||||
restartXrayOnClientDepleted: z.boolean().optional(),
|
||||
nodeTrafficFetchTimeout: z.number().int().min(1).max(30).optional(),
|
||||
mcpEnable: z.boolean().optional(),
|
||||
subCertFile: z.string().optional(),
|
||||
subKeyFile: z.string().optional(),
|
||||
|
||||
@@ -147,24 +147,28 @@ type AllSetting struct {
|
||||
ExternalTrafficInformURI string `json:"externalTrafficInformURI" form:"externalTrafficInformURI"`
|
||||
TrafficInformInterval int `json:"externalTrafficInformInterval" form:"externalTrafficInformInterval" example:"5"`
|
||||
RestartXrayOnClientDisable bool `json:"restartXrayOnClientDisable" form:"restartXrayOnClientDisable"`
|
||||
SubEncrypt bool `json:"subEncrypt" form:"subEncrypt"`
|
||||
SubURI string `json:"subURI" form:"subURI"`
|
||||
SubJsonPath string `json:"subJsonPath" form:"subJsonPath"`
|
||||
SubJsonURI string `json:"subJsonURI" form:"subJsonURI"`
|
||||
SubClashEnable bool `json:"subClashEnable" form:"subClashEnable"`
|
||||
SubClashPath string `json:"subClashPath" form:"subClashPath"`
|
||||
SubClashURI string `json:"subClashURI" form:"subClashURI"`
|
||||
SubClashEnableRouting bool `json:"subClashEnableRouting" form:"subClashEnableRouting"`
|
||||
SubClashRules string `json:"subClashRules" form:"subClashRules"`
|
||||
SubClashRemoteDNS bool `json:"subClashRemoteDNS" form:"subClashRemoteDNS"`
|
||||
SubJsonMux string `json:"subJsonMux" form:"subJsonMux"`
|
||||
SubJsonRules string `json:"subJsonRules" form:"subJsonRules"`
|
||||
SubJsonRoutingRules string `json:"subJsonRoutingRules" form:"subJsonRoutingRules"`
|
||||
SubJsonDns string `json:"subJsonDns" form:"subJsonDns"`
|
||||
SubJsonFinalMask string `json:"subJsonFinalMask" form:"subJsonFinalMask"`
|
||||
SubJsonObservatory string `json:"subJsonObservatory" form:"subJsonObservatory"`
|
||||
SubThemeDir string `json:"subThemeDir" form:"subThemeDir"`
|
||||
SubHideSettings bool `json:"subHideSettings" form:"subHideSettings"`
|
||||
|
||||
RestartOnClientDepleted *bool `json:"restartXrayOnClientDepleted,omitempty" form:"restartXrayOnClientDepleted"`
|
||||
NodeTrafficFetchTimeout int `json:"nodeTrafficFetchTimeout" form:"nodeTrafficFetchTimeout" example:"4"`
|
||||
|
||||
SubEncrypt bool `json:"subEncrypt" form:"subEncrypt"`
|
||||
SubURI string `json:"subURI" form:"subURI"`
|
||||
SubJsonPath string `json:"subJsonPath" form:"subJsonPath"`
|
||||
SubJsonURI string `json:"subJsonURI" form:"subJsonURI"`
|
||||
SubClashEnable bool `json:"subClashEnable" form:"subClashEnable"`
|
||||
SubClashPath string `json:"subClashPath" form:"subClashPath"`
|
||||
SubClashURI string `json:"subClashURI" form:"subClashURI"`
|
||||
SubClashEnableRouting bool `json:"subClashEnableRouting" form:"subClashEnableRouting"`
|
||||
SubClashRules string `json:"subClashRules" form:"subClashRules"`
|
||||
SubClashRemoteDNS bool `json:"subClashRemoteDNS" form:"subClashRemoteDNS"`
|
||||
SubJsonMux string `json:"subJsonMux" form:"subJsonMux"`
|
||||
SubJsonRules string `json:"subJsonRules" form:"subJsonRules"`
|
||||
SubJsonRoutingRules string `json:"subJsonRoutingRules" form:"subJsonRoutingRules"`
|
||||
SubJsonDns string `json:"subJsonDns" form:"subJsonDns"`
|
||||
SubJsonFinalMask string `json:"subJsonFinalMask" form:"subJsonFinalMask"`
|
||||
SubJsonObservatory string `json:"subJsonObservatory" form:"subJsonObservatory"`
|
||||
SubThemeDir string `json:"subThemeDir" form:"subThemeDir"`
|
||||
SubHideSettings bool `json:"subHideSettings" form:"subHideSettings"`
|
||||
|
||||
// Happ client customization settings (app-management / routing / UX).
|
||||
SubHappAutoDetect bool `json:"subHappAutoDetect" form:"subHappAutoDetect"`
|
||||
|
||||
@@ -122,6 +122,11 @@ func (j *NodeTrafficSyncJob) Run() {
|
||||
j.pruneClientSpeedNodes(nodes)
|
||||
j.clientSpeedMu.Unlock()
|
||||
|
||||
fetchTimeout, err := j.settingService.GetNodeTrafficFetchTimeout()
|
||||
if err != nil || fetchTimeout < time.Second || fetchTimeout > 30*time.Second {
|
||||
fetchTimeout = nodeTrafficSyncRequestTimeout
|
||||
}
|
||||
|
||||
sem := make(chan struct{}, nodeTrafficSyncConcurrency)
|
||||
var wg sync.WaitGroup
|
||||
var activeMu sync.Mutex
|
||||
@@ -136,7 +141,7 @@ func (j *NodeTrafficSyncJob) Run() {
|
||||
common.GoRecover("node-traffic-sync:"+n.Name, func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
if emails := j.syncOne(mgr, n, doIpSync); len(emails) > 0 {
|
||||
if emails := j.syncOne(mgr, n, doIpSync, fetchTimeout); len(emails) > 0 {
|
||||
activeMu.Lock()
|
||||
activeEmails = append(activeEmails, emails...)
|
||||
activeMu.Unlock()
|
||||
@@ -150,16 +155,7 @@ func (j *NodeTrafficSyncJob) Run() {
|
||||
logger.Warning("node traffic sync: depletion check failed:", err)
|
||||
}
|
||||
if clientsDisabled {
|
||||
if restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable(); settingErr == nil && restartOnDisable {
|
||||
// Not forced: a client only nodes serve leaves the local config unchanged, and a node
|
||||
// deciding when this tick disables clients must not decide when local users drop.
|
||||
if err := j.xrayService.RestartXrayFrom(false, service.XrayOriginClientDepletion); err != nil {
|
||||
logger.Warning("node traffic sync: restart xray after disabling clients failed:", err)
|
||||
j.xrayService.SetToNeedRestartFrom(service.XrayOriginNodeTrafficSync)
|
||||
}
|
||||
} else if settingErr != nil {
|
||||
logger.Warning("node traffic sync: get RestartXrayOnClientDisable failed:", settingErr)
|
||||
}
|
||||
j.xrayService.ApplyPendingDepletionRestart()
|
||||
j.structural.set()
|
||||
}
|
||||
|
||||
@@ -452,7 +448,7 @@ func (j *NodeTrafficSyncJob) maybePushGlobals(mgr *runtime.Manager, nodes []*mod
|
||||
// syncOne pulls one node's traffic snapshot and merges it. It returns the
|
||||
// emails online on that node this tick, feeding the delta broadcast above the
|
||||
// snapshot threshold; nil on any failure path.
|
||||
func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool) []string {
|
||||
func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool, fetchTimeout time.Duration) []string {
|
||||
rt, err := mgr.RemoteFor(n)
|
||||
if err != nil {
|
||||
logger.Warningf("node traffic sync: remote lookup failed for %s: %v", n.Name, err)
|
||||
@@ -487,7 +483,7 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy
|
||||
}
|
||||
resetCancel()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
snap, err := rt.FetchTrafficSnapshot(ctx)
|
||||
|
||||
@@ -109,18 +109,7 @@ func (j *XrayTrafficJob) Run() {
|
||||
}
|
||||
traffics, clientTraffics := sample.traffics, sample.clients
|
||||
if clientsDisabled {
|
||||
restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable()
|
||||
if settingErr != nil {
|
||||
logger.Warning("get RestartXrayOnClientDisable failed:", settingErr)
|
||||
}
|
||||
if restartOnDisable {
|
||||
if !j.xrayService.IsXrayRunning() {
|
||||
needRestart = true
|
||||
} else if err := j.xrayService.RestartXrayFrom(false, service.XrayOriginClientDepletion); err != nil {
|
||||
logger.Warning("reconcile xray after disabling clients failed:", err)
|
||||
needRestart = true
|
||||
}
|
||||
}
|
||||
j.xrayService.ApplyPendingDepletionRestart()
|
||||
websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
|
||||
}
|
||||
if needRestart {
|
||||
|
||||
@@ -140,8 +140,8 @@ func TestXrayTrafficRunFinishesCommittedSampleWhileStopped(t *testing.T) {
|
||||
if client.Up != 10 || client.Enable {
|
||||
t.Errorf("stored client has up=%d enabled=%t, want up=10 enabled=false", client.Up, client.Enable)
|
||||
}
|
||||
if !job.xrayService.IsNeedRestartAndSetFalse() {
|
||||
t.Error("restart was not queued after disabling a client with Xray stopped")
|
||||
if job.xrayService.IsNeedRestartAndSetFalse() {
|
||||
t.Error("disabling an unattached client with Xray stopped queued an unnecessary restart")
|
||||
}
|
||||
// The report leaves the accounting tick on its own goroutine, and the idle second run adds none.
|
||||
select {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
restartOnDepletedKey = "restartXrayOnClientDepleted"
|
||||
nodeFetchTimeoutKey = "nodeTrafficFetchTimeout"
|
||||
)
|
||||
|
||||
// GetRestartXrayOnClientDepleted inherits the old switch until explicitly configured.
|
||||
func (s *SettingService) GetRestartXrayOnClientDepleted() (bool, error) {
|
||||
value, err := s.getString(restartOnDepletedKey)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if value == "" {
|
||||
return s.GetRestartXrayOnClientDisable()
|
||||
}
|
||||
return strconv.ParseBool(value)
|
||||
}
|
||||
|
||||
func (s *SettingService) GetNodeTrafficFetchTimeout() (time.Duration, error) {
|
||||
seconds, err := s.getInt(nodeFetchTimeoutKey)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
@@ -177,7 +177,9 @@ func (s *InboundService) disableInvalidClients(tx *gorm.DB, mutationBatch *traff
|
||||
oldInbound: *oldInbound, newInbound: *inbound,
|
||||
})
|
||||
mutationBatch.addNode(*inbound.NodeID)
|
||||
disabledNodeIDs[*inbound.NodeID] = struct{}{}
|
||||
if depletionNeedsXrayRestart(oldInbound) {
|
||||
disabledNodeIDs[*inbound.NodeID] = struct{}{}
|
||||
}
|
||||
continue
|
||||
}
|
||||
for email := range emails {
|
||||
|
||||
@@ -1620,17 +1620,17 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
return structuralChange, nil
|
||||
}
|
||||
|
||||
func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
|
||||
restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
|
||||
func (s *InboundService) restartRemoteNodesOnDepletion(nodeIDs []int) {
|
||||
restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDepleted()
|
||||
if err != nil {
|
||||
logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
|
||||
logger.Warning("disableInvalidClients: get RestartXrayOnClientDepleted failed:", err)
|
||||
return
|
||||
}
|
||||
if !restartOnDisable {
|
||||
return
|
||||
}
|
||||
// Best-effort and never replayed: a hanging node must not hold the traffic poll.
|
||||
common.GoRecover("restart-nodes-on-client-disable", func() {
|
||||
common.GoRecover("restart-nodes-on-client-depletion", func() {
|
||||
for _, nodeID := range nodeIDs {
|
||||
nodeIDCopy := nodeID
|
||||
rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
|
||||
@@ -1638,7 +1638,10 @@ func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
|
||||
logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
|
||||
continue
|
||||
}
|
||||
if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
|
||||
ctx, cancel := nodePushContext()
|
||||
rtErr = rt.RestartXray(ctx)
|
||||
cancel()
|
||||
if rtErr != nil {
|
||||
logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b
|
||||
// Off the serial writer: a hanging node must not stall traffic accounting.
|
||||
needRestart = s.applyTrafficRemotePlans(remotePlans) || needRestart
|
||||
if len(disabledNodeIDs) > 0 {
|
||||
s.restartRemoteNodesOnDisable(disabledNodeIDs)
|
||||
s.restartRemoteNodesOnDepletion(disabledNodeIDs)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -116,6 +116,9 @@ func (s *InboundService) maintainTrafficLocked() (bool, bool, []int, []trafficIn
|
||||
return false, false, nil, nil, nil, err
|
||||
}
|
||||
needRestart = needRestart || s.applyTrafficMutationBatch(batch)
|
||||
if clientsDisabled {
|
||||
queueLocalDepletionRestart(batch)
|
||||
}
|
||||
return needRestart, clientsDisabled, disabledNodeIDs, batch.remotePlans, batch.renewedEmails, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -102,10 +102,16 @@ func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePla
|
||||
}
|
||||
|
||||
func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool {
|
||||
if b == nil {
|
||||
if b == nil || len(b.localPlans) == 0 {
|
||||
return false
|
||||
}
|
||||
needRestart := false
|
||||
process := currentXrayProcess()
|
||||
var original *xray.Config
|
||||
if process != nil {
|
||||
original = process.GetConfig()
|
||||
}
|
||||
var removed map[string]map[string]struct{}
|
||||
for i := range b.localPlans {
|
||||
plan := &b.localPlans[i]
|
||||
if plan.inbound.Protocol == model.MTProto {
|
||||
@@ -130,6 +136,15 @@ func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool
|
||||
if err != nil && strings.Contains(err.Error(), "not found") {
|
||||
err = nil
|
||||
}
|
||||
if err == nil && original != nil && depletionNeedsXrayRestart(&plan.inbound) {
|
||||
if removed == nil {
|
||||
removed = make(map[string]map[string]struct{})
|
||||
}
|
||||
if removed[plan.inbound.Tag] == nil {
|
||||
removed[plan.inbound.Tag] = make(map[string]struct{})
|
||||
}
|
||||
removed[plan.inbound.Tag][plan.email] = struct{}{}
|
||||
}
|
||||
case trafficDisableInbound:
|
||||
err = rt.DelInbound(context.Background(), &plan.inbound)
|
||||
if xray.IsMissingHandlerErr(err) {
|
||||
@@ -142,5 +157,15 @@ func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool
|
||||
needRestart = true
|
||||
}
|
||||
}
|
||||
if len(removed) > 0 {
|
||||
// A restart or reconcile may have replaced the snapshot while an API
|
||||
// call was running. Only amend the snapshot we applied against.
|
||||
lock.Lock()
|
||||
if process == currentXrayProcess() && process.IsRunning() &&
|
||||
process.GetConfig() == original && process.DropInboundUsers(removed) {
|
||||
persistHotConfig(process)
|
||||
}
|
||||
lock.Unlock()
|
||||
}
|
||||
return needRestart
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -83,6 +84,29 @@ func xrayReleaseServer(t *testing.T, version string, asset []byte) {
|
||||
|
||||
// startFakeCore runs the installed core on the panel's own config, as RestartXray
|
||||
// would, and stops whichever core is current when the test ends.
|
||||
// useFreeXrayAPIPort moves the template's API inbound off its default port for tests that
|
||||
// serve that gRPC API themselves: a real core on this host may already hold the default.
|
||||
func useFreeXrayAPIPort(t *testing.T) {
|
||||
t.Helper()
|
||||
settings := SettingService{}
|
||||
template, err := settings.GetXrayConfigTemplate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cfg xray.Config
|
||||
if err := json.Unmarshal([]byte(template), &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := range cfg.InboundConfigs {
|
||||
if cfg.InboundConfigs[i].Tag == "api" {
|
||||
cfg.InboundConfigs[i].Port = freeLoopbackPort(t)
|
||||
}
|
||||
}
|
||||
if err := settings.saveSetting("xrayTemplateConfig", string(mustJSON(t, cfg))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func startFakeCore(t *testing.T) *xray.Process {
|
||||
t.Helper()
|
||||
cfg, err := (&XrayService{}).GetXrayConfig()
|
||||
|
||||
@@ -228,9 +228,13 @@ var defaultValueMap = map[string]string{
|
||||
externalTrafficInformIntervalKey: "5",
|
||||
|
||||
"restartXrayOnClientDisable": "true",
|
||||
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
||||
"panelOutbound": "",
|
||||
"devChannelEnable": "false",
|
||||
|
||||
restartOnDepletedKey: "",
|
||||
nodeFetchTimeoutKey: "4",
|
||||
|
||||
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
||||
"panelOutbound": "",
|
||||
"devChannelEnable": "false",
|
||||
|
||||
// LDAP defaults
|
||||
"ldapEnable": "false",
|
||||
@@ -317,7 +321,8 @@ func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
|
||||
var found bool
|
||||
var field reflect.StructField
|
||||
for _, f := range fields {
|
||||
if f.Tag.Get("json") == key {
|
||||
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
|
||||
if name == key {
|
||||
field = f
|
||||
found = true
|
||||
break
|
||||
@@ -341,6 +346,14 @@ func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
|
||||
fieldV.SetString(value)
|
||||
case bool:
|
||||
fieldV.SetBool(effectiveSettingValue(key, value) == "true")
|
||||
case *bool:
|
||||
if value != "" {
|
||||
flag, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fieldV.Set(reflect.ValueOf(&flag))
|
||||
}
|
||||
default:
|
||||
return common.NewErrorf("unknown field %v type %v", key, t)
|
||||
}
|
||||
@@ -371,6 +384,9 @@ func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
|
||||
allSetting.SubProfileMode = ""
|
||||
}
|
||||
allSetting.SubProfileMode = effectiveSubProfileMode(allSetting.SubProfileMode, allSetting.SubProfileUrl)
|
||||
if allSetting.RestartOnClientDepleted == nil {
|
||||
allSetting.RestartOnClientDepleted = new(allSetting.RestartXrayOnClientDisable)
|
||||
}
|
||||
return allSetting, nil
|
||||
}
|
||||
|
||||
@@ -1764,6 +1780,9 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
|
||||
if seconds := allSetting.TrafficInformInterval; seconds != 0 && !validExternalTrafficInformInterval(seconds) {
|
||||
return errors.New("external traffic inform interval must be between 5 and 3600 seconds")
|
||||
}
|
||||
if seconds := allSetting.NodeTrafficFetchTimeout; seconds != 0 && (seconds < 1 || seconds > 30) {
|
||||
return errors.New("node traffic fetch timeout must be between 1 and 30 seconds")
|
||||
}
|
||||
if err := validateNetworkTrafficSettings(allSetting); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1840,16 +1859,21 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
|
||||
return err
|
||||
}
|
||||
for _, field := range fields {
|
||||
key := field.Tag.Get("json")
|
||||
key, _, _ := strings.Cut(field.Tag.Get("json"), ",")
|
||||
// Older clients omit this pair; skipping its writes also preserves
|
||||
// explicit selections committed concurrently with an unrelated save.
|
||||
if preserveTrafficSelection && (key == "networkTrafficMode" || key == "networkTrafficInterface") {
|
||||
continue
|
||||
}
|
||||
if key == externalTrafficInformIntervalKey && allSetting.TrafficInformInterval == 0 {
|
||||
if (key == externalTrafficInformIntervalKey && allSetting.TrafficInformInterval == 0) ||
|
||||
(key == restartOnDepletedKey && allSetting.RestartOnClientDepleted == nil) ||
|
||||
(key == nodeFetchTimeoutKey && allSetting.NodeTrafficFetchTimeout == 0) {
|
||||
continue
|
||||
}
|
||||
fieldV := v.FieldByName(field.Name)
|
||||
if key == restartOnDepletedKey {
|
||||
fieldV = fieldV.Elem()
|
||||
}
|
||||
value := fmt.Sprint(fieldV.Interface())
|
||||
if st, ok := byKey[key]; ok {
|
||||
if st.Value == value {
|
||||
@@ -2194,10 +2218,14 @@ xrayTemplateConfig) are excluded structurally rather than by deny-list.
|
||||
func (s *SettingService) GetFactoryDefaults() map[string]string {
|
||||
result := make(map[string]string)
|
||||
for _, field := range reflect_util.GetFields(reflect.TypeFor[entity.AllSetting]()) {
|
||||
key := field.Tag.Get("json")
|
||||
key, _, _ := strings.Cut(field.Tag.Get("json"), ",")
|
||||
if key == "" || factoryDefaultSecretKeys[key] {
|
||||
continue
|
||||
}
|
||||
if key == restartOnDepletedKey {
|
||||
result[key] = defaultValueMap["restartXrayOnClientDisable"]
|
||||
continue
|
||||
}
|
||||
if value, ok := defaultValueMap[key]; ok {
|
||||
result[key] = value
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/reflect_util"
|
||||
@@ -12,7 +13,7 @@ func allSettingJSONTags(t *testing.T) map[string]bool {
|
||||
t.Helper()
|
||||
tags := make(map[string]bool)
|
||||
for _, field := range reflect_util.GetFields(reflect.TypeFor[entity.AllSetting]()) {
|
||||
if tag := field.Tag.Get("json"); tag != "" {
|
||||
if tag, _, _ := strings.Cut(field.Tag.Get("json"), ","); tag != "" {
|
||||
tags[tag] = true
|
||||
}
|
||||
}
|
||||
@@ -28,6 +29,8 @@ func TestGetFactoryDefaultsExposesBrowserSafeKeys(t *testing.T) {
|
||||
}{
|
||||
{key: "webPort", want: "2053"},
|
||||
{key: "subPort", want: "2096"},
|
||||
{key: restartOnDepletedKey, want: "true"},
|
||||
{key: nodeFetchTimeoutKey, want: "4"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.key, func(t *testing.T) {
|
||||
|
||||
@@ -131,7 +131,10 @@ func (h *hangingRestartRuntime) RestartXray(ctx context.Context) error {
|
||||
// not hold the traffic poll that disabled its client.
|
||||
func TestTrafficDisableNodeRestartDoesNotBlockTrafficPoll(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
setRestartOnClientDisable(t, true)
|
||||
setRestartOnClientDisable(t, false)
|
||||
if err := (&SettingService{}).saveSetting("restartXrayOnClientDepleted", "true"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodeID, _ := setupNodeRuntime(t)
|
||||
hanging := &hangingRestartRuntime{entered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
runtime.GetManager().SetRuntimeOverride(nodeID, hanging)
|
||||
|
||||
@@ -1549,10 +1549,12 @@ func (s *XrayService) RestartXray(isForce bool) error {
|
||||
|
||||
// RestartXrayFrom records the initiating operation while applying the usual restart policy.
|
||||
func (s *XrayService) RestartXrayFrom(isForce bool, origin XrayOrigin) error {
|
||||
return s.restartXrayFrom(isForce, origin, "")
|
||||
return s.restartXrayFrom(isForce, origin, "", false)
|
||||
}
|
||||
|
||||
func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin) error {
|
||||
// dropSessions replaces a running core whatever its config says: only a new process
|
||||
// ends the sessions of clients the API has already removed.
|
||||
func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin, dropSessions bool) error {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
logger.Debug("restart Xray, force:", isForce)
|
||||
@@ -1591,7 +1593,7 @@ func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin)
|
||||
if wasRunning {
|
||||
event.NewPID = oldPID
|
||||
configUnchanged := process.GetConfig().Equals(xrayConfig)
|
||||
if !isForce && configUnchanged && pendingXrayRestart.Load() == nil {
|
||||
if !isForce && !dropSessions && configUnchanged && pendingXrayRestart.Load() == nil {
|
||||
logger.Debug("It does not need to restart Xray")
|
||||
return repairUnavailableTuicRelays(xrayConfig, process.GetAPIPort())
|
||||
}
|
||||
@@ -1608,7 +1610,7 @@ func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin)
|
||||
event.Event, event.Reason = "config_rejected", "bind_conflict"
|
||||
return fmt.Errorf("xray %s", refused)
|
||||
}
|
||||
if !isForce && !configUnchanged {
|
||||
if !isForce && !dropSessions && !configUnchanged {
|
||||
var failure hotApplyFailure
|
||||
outcome, err := s.applyHotConfig(process, xrayConfig, &failure)
|
||||
if failure.step != "" {
|
||||
@@ -1632,6 +1634,9 @@ func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin)
|
||||
if !isForce && configUnchanged {
|
||||
event.Reason = "pending_restart"
|
||||
}
|
||||
if dropSessions && !isForce {
|
||||
event.Reason = string(hotClientsRemoved)
|
||||
}
|
||||
invalidateTuicRelayReadiness(process.GetConfig())
|
||||
invalidateTuicRelayReadiness(xrayConfig)
|
||||
switch err := process.Stop(); {
|
||||
@@ -1976,16 +1981,23 @@ func (s *XrayService) IsNeedRestartAndSetFalse() bool {
|
||||
func (s *XrayService) ApplyPendingRestart() {
|
||||
reconcile := isNeedXrayReconcile.Swap(false)
|
||||
pending := pendingXrayRestart.Swap(nil)
|
||||
if pending == nil && !reconcile {
|
||||
depleted := pendingXrayDepletionRestart.Swap(false) && s.IsXrayRunning()
|
||||
if pending == nil && !reconcile && !depleted {
|
||||
return
|
||||
}
|
||||
origin := XrayOriginConfigChange
|
||||
var trigger XrayOrigin
|
||||
if pending != nil {
|
||||
switch {
|
||||
case pending != nil:
|
||||
origin, trigger = XrayOriginPendingRestart, *pending
|
||||
case depleted:
|
||||
origin = XrayOriginClientDepletion
|
||||
}
|
||||
if err := s.restartXrayFrom(false, origin, trigger); err != nil {
|
||||
if err := s.restartXrayFrom(false, origin, trigger, depleted); err != nil {
|
||||
logger.Error("reconcile xray failed:", err)
|
||||
if depleted {
|
||||
pendingXrayDepletionRestart.Store(true)
|
||||
}
|
||||
if pending != nil {
|
||||
pendingXrayRestart.CompareAndSwap(nil, pending)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
)
|
||||
|
||||
var pendingXrayDepletionRestart atomic.Bool
|
||||
|
||||
func depletionNeedsXrayRestart(inbound *model.Inbound) bool {
|
||||
if !inbound.Enable {
|
||||
return false
|
||||
}
|
||||
switch inbound.Protocol {
|
||||
case model.MTProto, model.AmneziaWG, model.TUIC, model.WireGuard:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func queueLocalDepletionRestart(batch *trafficMutationBatch) {
|
||||
for _, plan := range batch.localPlans {
|
||||
if plan.action != trafficRemoveUser || !depletionNeedsXrayRestart(&plan.inbound) {
|
||||
continue
|
||||
}
|
||||
enabled, err := (&SettingService{}).GetRestartXrayOnClientDepleted()
|
||||
if err != nil {
|
||||
logger.Warning("get restartXrayOnClientDepleted failed:", err)
|
||||
} else if enabled {
|
||||
pendingXrayDepletionRestart.Store(true)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyPendingDepletionRestart drops sessions for a committed local depletion batch.
|
||||
func (s *XrayService) ApplyPendingDepletionRestart() {
|
||||
if !pendingXrayDepletionRestart.Swap(false) || !s.IsXrayRunning() {
|
||||
return
|
||||
}
|
||||
if err := s.restartXrayFrom(false, XrayOriginClientDepletion, "", true); err != nil {
|
||||
logger.Error("restart xray after client depletion failed:", err)
|
||||
pendingXrayDepletionRestart.Store(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/xtls/xray-core/app/proxyman/command"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"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"
|
||||
panelruntime "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestDepletionSettingsAreIndependentAndSurviveLegacySaves(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
setRestartOnClientDisable(t, false)
|
||||
settings := new(SettingService)
|
||||
all, err := settings.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if all.RestartOnClientDepleted == nil || *all.RestartOnClientDepleted {
|
||||
t.Fatal("an unset depletion switch did not inherit the legacy value")
|
||||
}
|
||||
all.RestartOnClientDepleted = new(true)
|
||||
all.NodeTrafficFetchTimeout = 15
|
||||
if err := settings.UpdateAllSetting(all, SecretClears{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all.RestartOnClientDepleted, all.NodeTrafficFetchTimeout = nil, 0
|
||||
if err := settings.UpdateAllSetting(all, SecretClears{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
depletion, err := settings.GetRestartXrayOnClientDepleted()
|
||||
if err != nil || !depletion {
|
||||
t.Fatalf("depletion = %t, error %v", depletion, err)
|
||||
}
|
||||
if droppedClientNeedsRestart() {
|
||||
t.Fatal("enabling depletion restarts also enabled ordinary disable restarts")
|
||||
}
|
||||
timeout, err := settings.GetNodeTrafficFetchTimeout()
|
||||
if err != nil || timeout != 15*time.Second {
|
||||
t.Fatalf("fetch timeout = %v, error %v", timeout, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommittedLocalDepletionReplacesOnlyTheRunningCore(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the fake core is a shell script")
|
||||
}
|
||||
t.Run("restart enabled", func(t *testing.T) { checkCommittedLocalDepletion(t, true) })
|
||||
t.Run("restart disabled and ordinary restarts enabled", func(t *testing.T) { checkCommittedLocalDepletion(t, false) })
|
||||
}
|
||||
|
||||
func checkCommittedLocalDepletion(t *testing.T, restart bool) {
|
||||
t.Helper()
|
||||
setupConflictDB(t)
|
||||
setRestartOnClientDisable(t, !restart)
|
||||
if err := (&SettingService{}).saveSetting(restartOnDepletedKey, fmt.Sprint(restart)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wasStopped := isManuallyStopped.Swap(false)
|
||||
wasPending := pendingXrayDepletionRestart.Swap(false)
|
||||
ordinaryPending := pendingXrayRestart.Swap(nil)
|
||||
t.Cleanup(func() {
|
||||
isManuallyStopped.Store(wasStopped)
|
||||
pendingXrayDepletionRestart.Store(wasPending)
|
||||
pendingXrayRestart.Store(ordinaryPending)
|
||||
})
|
||||
t.Setenv("XUI_BIN_FOLDER", t.TempDir())
|
||||
t.Setenv("XUI_LOG_FOLDER", t.TempDir())
|
||||
if err := os.WriteFile(xray.GetBinaryPath(), []byte(fakeXrayCore("26.10.21", true)), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
client := model.Client{Email: "local-depletion@test", Enable: true, ID: "00000000-0000-4000-8000-000000000001"}
|
||||
inbound := &model.Inbound{
|
||||
UserId: 1, Tag: "local-depletion", Port: freeLoopbackPort(t), Enable: true, Protocol: model.VLESS,
|
||||
Settings: clientsSettings(t, []model.Client{client}), StreamSettings: `{"network":"tcp"}`,
|
||||
}
|
||||
db := database.GetDB()
|
||||
if err := db.Create(inbound).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (&ClientService{}).SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Where("email = ?", client.Email).FirstOrCreate(&xray.ClientTraffic{
|
||||
Email: client.Email, InboundId: inbound.Id, Total: 10, Enable: true,
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
useFreeXrayAPIPort(t)
|
||||
before := startFakeCore(t)
|
||||
listener, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", before.GetAPIPort()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applied := make(chan bool, 4)
|
||||
core := grpc.NewServer(grpc.UnaryInterceptor(func(_ context.Context, req any, _ *grpc.UnaryServerInfo, _ grpc.UnaryHandler) (any, error) {
|
||||
op, ok := req.(*command.AlterInboundRequest)
|
||||
if !ok || op.Tag != inbound.Tag {
|
||||
return nil, fmt.Errorf("unexpected gRPC request %T", req)
|
||||
}
|
||||
applied <- true
|
||||
return &command.AlterInboundResponse{}, nil
|
||||
}))
|
||||
command.RegisterHandlerServiceServer(core, command.UnimplementedHandlerServiceServer{})
|
||||
go func() { _ = core.Serve(listener) }()
|
||||
t.Cleanup(core.Stop)
|
||||
oldManager := panelruntime.GetManager()
|
||||
panelruntime.SetManager(panelruntime.NewManager(panelruntime.LocalDeps{APIPort: before.GetAPIPort}))
|
||||
t.Cleanup(func() { panelruntime.SetManager(oldManager) })
|
||||
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", client.Email).
|
||||
Updates(map[string]any{"enable": true, "total": 10, "up": 10}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, disabled, err := (&InboundService{}).AddTraffic(nil, nil); err != nil || !disabled {
|
||||
t.Fatalf("depletion disabled = %t, error %v", disabled, err)
|
||||
}
|
||||
|
||||
xraySvc := new(XrayService)
|
||||
xraySvc.ApplyPendingDepletionRestart()
|
||||
if len(applied) != 1 {
|
||||
t.Fatal("depletion did not remove the client through the running core API")
|
||||
}
|
||||
after := XrayProcess()
|
||||
if restart {
|
||||
if after == before || after == nil || !after.IsRunning() || before.IsRunning() {
|
||||
t.Fatal("depletion did not replace the affected running core")
|
||||
}
|
||||
} else {
|
||||
if err := xraySvc.RestartXray(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after != before || XrayProcess() != before || !before.IsRunning() {
|
||||
t.Fatal("ordinary reconciliation restarted the core after a depletion-only removal")
|
||||
}
|
||||
}
|
||||
xraySvc.ApplyPendingDepletionRestart()
|
||||
if XrayProcess() != after {
|
||||
t.Fatal("the same depletion batch caused multiple restarts")
|
||||
}
|
||||
var traffic xray.ClientTraffic
|
||||
if err := db.Where("email = ?", client.Email).First(&traffic).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if traffic.Enable || traffic.Up != 10 || traffic.Total != 10 {
|
||||
t.Fatalf("depletion changed quota or usage, got enabled=%t up=%d total=%d", traffic.Enable, traffic.Up, traffic.Total)
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,11 @@ func TestXrayLifecycleReportsActualReplacement(t *testing.T) {
|
||||
first := startFakeCore(t)
|
||||
stopped := isManuallyStopped.Swap(false)
|
||||
pending := pendingXrayRestart.Swap(nil)
|
||||
depletion := pendingXrayDepletionRestart.Swap(false)
|
||||
t.Cleanup(func() {
|
||||
isManuallyStopped.Store(stopped)
|
||||
pendingXrayRestart.Store(pending)
|
||||
pendingXrayDepletionRestart.Store(depletion)
|
||||
})
|
||||
|
||||
svc := new(XrayService)
|
||||
@@ -185,6 +187,7 @@ func TestXrayLifecycleIdentifiesRejectedHotApply(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := new(XrayService)
|
||||
useFreeXrayAPIPort(t)
|
||||
template, err := svc.settingService.GetXrayConfigTemplate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -194,12 +197,6 @@ func TestXrayLifecycleIdentifiesRejectedHotApply(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.RouterConfig = []byte("{\"domainStrategy\":\"AsIs\",\"rules\":[]}")
|
||||
// This test serves the core's gRPC API itself; the template's port may belong to a real core here.
|
||||
for i := range cfg.InboundConfigs {
|
||||
if cfg.InboundConfigs[i].Tag == "api" {
|
||||
cfg.InboundConfigs[i].Port = freeLoopbackPort(t)
|
||||
}
|
||||
}
|
||||
if err := svc.settingService.saveSetting("xrayTemplateConfig", string(mustJSON(t, cfg))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "فاصل إرسال بيانات المرور الخارجية (بالثواني)",
|
||||
"restartXrayOnClientDisable": "إعادة تشغيل Xray بعد تعطيل العميل",
|
||||
"restartXrayOnClientDisableDesc": "عندما يتوقف تقديم الخدمة للعميل — بتعطيل تلقائي بسبب انتهاء الصلاحية أو حد حركة المرور، أو بتعطيل أو حذف يدوي — أعد تشغيل Xray لإنهاء اتصالاته النشطة.",
|
||||
"restartXrayOnClientDepleted": "إعادة تشغيل Xray عند نفاد حصة العميل أو انتهائها",
|
||||
"nodeTrafficFetchTimeout": "مهلة جلب حركة مرور العقدة (بالثواني)",
|
||||
"fragment": "تجزئة",
|
||||
"fragmentDesc": "يفعل تجزئة لحزمة TLS hello.",
|
||||
"fragmentSett": "إعدادات التجزئة",
|
||||
|
||||
@@ -1646,7 +1646,9 @@
|
||||
"externalTrafficInformURIDesc": "Traffic updates are sent to this URI.",
|
||||
"externalTrafficInformInterval": "External traffic inform interval (seconds)",
|
||||
"restartXrayOnClientDisable": "Restart Xray After Client Disable",
|
||||
"restartXrayOnClientDisableDesc": "When a client stops being served - auto-disabled by expiration or traffic limit, or disabled or deleted by hand - restart Xray so its live connections end.",
|
||||
"restartXrayOnClientDisableDesc": "When a client is disabled or deleted by hand, restart Xray so its live connections end. Clients disabled automatically by expiration or traffic limit follow the next switch.",
|
||||
"restartXrayOnClientDepleted": "Restart Xray on client quota or expiry",
|
||||
"nodeTrafficFetchTimeout": "Node traffic fetch timeout (seconds)",
|
||||
"fragment": "Fragmentation",
|
||||
"fragmentDesc": "Enable fragmentation for TLS hello packet.",
|
||||
"fragmentSett": "Fragmentation Settings",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Intervalo de aviso de tráfico externo (segundos)",
|
||||
"restartXrayOnClientDisable": "Reiniciar Xray al desactivar un cliente",
|
||||
"restartXrayOnClientDisableDesc": "Cuando un cliente deja de atenderse — desactivado automáticamente por vencimiento o límite de tráfico, o desactivado o eliminado a mano — reiniciar Xray para que terminen sus conexiones activas.",
|
||||
"restartXrayOnClientDepleted": "Reiniciar Xray al agotar la cuota o vencer el cliente",
|
||||
"nodeTrafficFetchTimeout": "Tiempo de espera de tráfico del nodo (segundos)",
|
||||
"fragment": "Fragmentación",
|
||||
"fragmentDesc": "Habilitar la fragmentación para el paquete de saludo de TLS",
|
||||
"fragmentSett": "Configuración de Fragmentación",
|
||||
|
||||
@@ -1525,7 +1525,9 @@
|
||||
"externalTrafficInformURIDesc": "ترافیک های مصرفی به این لینک هم ارسال می شود",
|
||||
"externalTrafficInformInterval": "فاصلهٔ ارسال گزارش ترافیک خارجی (ثانیه)",
|
||||
"restartXrayOnClientDisable": "ریاستارت Xray پس از غیرفعالسازی کلاینت",
|
||||
"restartXrayOnClientDisableDesc": "وقتی دیگر به کاربر سرویس داده نمیشود — غیرفعال شدن خودکار بهخاطر اتمام زمان یا محدودیت ترافیک، یا غیرفعال/حذف دستی — Xray ریاستارت شود تا اتصالهای فعالش بسته شوند.",
|
||||
"restartXrayOnClientDisableDesc": "وقتی کاربری بهصورت دستی غیرفعال یا حذف میشود، Xray ریاستارت شود تا اتصالهای فعالش بسته شوند. غیرفعال شدن خودکار بهخاطر اتمام زمان یا محدودیت ترافیک را سوئیچ بعدی کنترل میکند.",
|
||||
"restartXrayOnClientDepleted": "ریاستارت Xray پس از اتمام سهمیه یا انقضای کاربر",
|
||||
"nodeTrafficFetchTimeout": "مهلت دریافت ترافیک نود (ثانیه)",
|
||||
"fragment": "فرگمنت",
|
||||
"fragmentDesc": "فعال کردن فرگمنت برای بستهی نخست تیالاس",
|
||||
"fragmentSett": "تنظیمات فرگمنت",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Interval pemberitahuan lalu lintas eksternal (detik)",
|
||||
"restartXrayOnClientDisable": "Nyalakan Ulang Xray Setelah Klien Dinonaktifkan",
|
||||
"restartXrayOnClientDisableDesc": "Saat klien berhenti dilayani — dinonaktifkan otomatis karena kedaluwarsa atau batas trafik, atau dinonaktifkan maupun dihapus secara manual — mulai ulang Xray agar koneksi aktifnya berakhir.",
|
||||
"restartXrayOnClientDepleted": "Mulai ulang Xray saat kuota klien habis atau kedaluwarsa",
|
||||
"nodeTrafficFetchTimeout": "Batas waktu pengambilan lalu lintas node (detik)",
|
||||
"fragment": "Fragmentasi",
|
||||
"fragmentDesc": "Aktifkan fragmentasi untuk paket hello TLS",
|
||||
"fragmentSett": "Pengaturan Fragmentasi",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "外部トラフィック通知間隔(秒)",
|
||||
"restartXrayOnClientDisable": "クライアント無効化後に Xray を再起動",
|
||||
"restartXrayOnClientDisableDesc": "クライアントがサービス対象でなくなったとき(有効期限や通信量上限による自動無効化、または手動での無効化・削除)、接続を終わらせるため Xray を再起動します。",
|
||||
"restartXrayOnClientDepleted": "クライアントのクォータ超過または期限切れ時に Xray を再起動",
|
||||
"nodeTrafficFetchTimeout": "ノード通信量の取得タイムアウト(秒)",
|
||||
"fragment": "フラグメント",
|
||||
"fragmentDesc": "TLS helloパケットのフラグメントを有効にする",
|
||||
"fragmentSett": "設定",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Intervalo de notificação externa de tráfego (segundos)",
|
||||
"restartXrayOnClientDisable": "Reiniciar Xray Após Desativar um Cliente",
|
||||
"restartXrayOnClientDisableDesc": "Quando um cliente deixa de ser atendido — desativado automaticamente por expiração ou limite de tráfego, ou desativado ou excluído manualmente — reinicie o Xray para encerrar suas conexões ativas.",
|
||||
"restartXrayOnClientDepleted": "Reiniciar o Xray ao atingir a cota ou o vencimento do cliente",
|
||||
"nodeTrafficFetchTimeout": "Tempo limite da consulta de tráfego do nó (segundos)",
|
||||
"fragment": "Fragmentação",
|
||||
"fragmentDesc": "Ativa a fragmentação para o pacote TLS hello.",
|
||||
"fragmentSett": "Configurações de Fragmentação",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Интервал внешних уведомлений о трафике (секунды)",
|
||||
"restartXrayOnClientDisable": "Перезапускать Xray после отключения клиента",
|
||||
"restartXrayOnClientDisableDesc": "Когда клиент перестаёт обслуживаться — автоматически (по сроку или лимиту трафика) или вручную — перезапускать Xray, чтобы его активные соединения оборвались.",
|
||||
"restartXrayOnClientDepleted": "Перезапускать Xray при исчерпании квоты или истечении срока клиента",
|
||||
"nodeTrafficFetchTimeout": "Тайм-аут получения трафика узла (секунды)",
|
||||
"fragment": "Фрагментация",
|
||||
"fragmentDesc": "Включить фрагментацию TLS-хэндшейка",
|
||||
"fragmentSett": "Настройки фрагментации",
|
||||
|
||||
@@ -1647,6 +1647,8 @@
|
||||
"externalTrafficInformInterval": "Interval externých upozornení o prevádzke (sekundy)",
|
||||
"restartXrayOnClientDisable": "Reštartovať Xray po vypnutí klienta",
|
||||
"restartXrayOnClientDisableDesc": "Keď klient stratí prístup pre skončenú platnosť alebo vyčerpaný limit, prípadne ho správca vypne či odstráni, reštartovať Xray a ukončiť jeho existujúce spojenia.",
|
||||
"restartXrayOnClientDepleted": "Reštartovať Xray pri vyčerpaní kvóty alebo vypršaní klienta",
|
||||
"nodeTrafficFetchTimeout": "Časový limit načítania prevádzky uzla (sekundy)",
|
||||
"fragment": "Fragmentácia",
|
||||
"fragmentDesc": "Zapnúť delenie paketu TLS hello.",
|
||||
"fragmentSett": "Nastavenia fragmentácie",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Harici trafik bildirim aralığı (saniye)",
|
||||
"restartXrayOnClientDisable": "İstemci Devre Dışı Bırakıldığında Xray'i Yeniden Başlat",
|
||||
"restartXrayOnClientDisableDesc": "Bir istemci artık sunulmadığında — süre dolumu veya trafik limiti nedeniyle otomatik, ya da elle devre dışı bırakıldığında veya silindiğinde — açık bağlantıları bitsin diye Xray'i yeniden başlatır.",
|
||||
"restartXrayOnClientDepleted": "İstemci kotası dolduğunda veya süresi bittiğinde Xray’i yeniden başlat",
|
||||
"nodeTrafficFetchTimeout": "Düğüm trafik sorgusu zaman aşımı (saniye)",
|
||||
"fragment": "Parçalama",
|
||||
"fragmentDesc": "TLS merhaba paketinin parçalanmasını etkinleştirir.",
|
||||
"fragmentSett": "Parçalama Ayarları",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Інтервал зовнішніх сповіщень про трафік (секунди)",
|
||||
"restartXrayOnClientDisable": "Перезапускати Xray після вимкнення клієнта",
|
||||
"restartXrayOnClientDisableDesc": "Коли клієнт перестає обслуговуватися — автоматично (через термін дії чи ліміт трафіку) або вручну — перезапускати Xray, щоб його активні з'єднання обірвалися.",
|
||||
"restartXrayOnClientDepleted": "Перезапускати Xray після вичерпання квоти або строку клієнта",
|
||||
"nodeTrafficFetchTimeout": "Час очікування отримання трафіку вузла (секунди)",
|
||||
"fragment": "Фрагментація",
|
||||
"fragmentDesc": "Увімкнути фрагментацію для пакету привітання TLS",
|
||||
"fragmentSett": "Параметри фрагментації",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "Khoảng thời gian thông báo lưu lượng ra ngoài (giây)",
|
||||
"restartXrayOnClientDisable": "Khởi Động Lại Xray Sau Khi Vô Hiệu Hóa Máy Khách",
|
||||
"restartXrayOnClientDisableDesc": "Khi một máy khách không còn được phục vụ — bị vô hiệu hóa tự động do hết hạn hoặc giới hạn lưu lượng, hoặc bị vô hiệu hóa hay xóa thủ công — hãy khởi động lại Xray để các kết nối đang mở của nó kết thúc.",
|
||||
"restartXrayOnClientDepleted": "Khởi động lại Xray khi máy khách hết hạn mức hoặc hết hạn",
|
||||
"nodeTrafficFetchTimeout": "Thời gian chờ lấy lưu lượng nút (giây)",
|
||||
"fragment": "Sự phân mảnh",
|
||||
"fragmentDesc": "Kích hoạt phân mảnh cho gói TLS hello",
|
||||
"fragmentSett": "Cài đặt phân mảnh",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "外部流量通知间隔(秒)",
|
||||
"restartXrayOnClientDisable": "客户端被禁用后重启 Xray",
|
||||
"restartXrayOnClientDisableDesc": "当客户端不再被服务时——因到期或流量超限被自动禁用,或被手动禁用、删除——重启 Xray 以断开其活动连接。",
|
||||
"restartXrayOnClientDepleted": "客户端配额用尽或到期时重启 Xray",
|
||||
"nodeTrafficFetchTimeout": "节点流量获取超时(秒)",
|
||||
"fragment": "分片",
|
||||
"fragmentDesc": "启用 TLS hello 数据包分片",
|
||||
"fragmentSett": "设置",
|
||||
|
||||
@@ -1522,6 +1522,8 @@
|
||||
"externalTrafficInformInterval": "外部流量通知間隔(秒)",
|
||||
"restartXrayOnClientDisable": "用戶被停用後重新啟動 Xray",
|
||||
"restartXrayOnClientDisableDesc": "當用戶不再被服務時——因到期或流量上限被自動停用,或被手動停用、刪除——重新啟動 Xray 以中斷其作用中的連線。",
|
||||
"restartXrayOnClientDepleted": "用戶端配額用盡或到期時重啟 Xray",
|
||||
"nodeTrafficFetchTimeout": "節點流量擷取逾時(秒)",
|
||||
"fragment": "分片",
|
||||
"fragmentDesc": "啟用 TLS hello 資料包分片",
|
||||
"fragmentSett": "設定",
|
||||
|
||||
@@ -350,6 +350,49 @@ func (p *Process) DropInbound(tag string) {
|
||||
})
|
||||
}
|
||||
|
||||
// DropInboundUsers records successful per-user removals from the running core.
|
||||
// The remaining settings and clients retain their existing values and order.
|
||||
func (p *Process) DropInboundUsers(removed map[string]map[string]struct{}) bool {
|
||||
changed := false
|
||||
p.editInbounds(func(inbounds []InboundConfig) []InboundConfig {
|
||||
for i := range inbounds {
|
||||
inbound := &inbounds[i]
|
||||
emails := removed[inbound.Tag]
|
||||
if len(emails) == 0 {
|
||||
continue
|
||||
}
|
||||
var settings map[string]json.RawMessage
|
||||
if json.Unmarshal(inbound.Settings, &settings) != nil {
|
||||
continue
|
||||
}
|
||||
var clients []json.RawMessage
|
||||
if json.Unmarshal(settings["clients"], &clients) != nil {
|
||||
continue
|
||||
}
|
||||
count := len(clients)
|
||||
clients = slices.DeleteFunc(clients, func(client json.RawMessage) bool {
|
||||
var address struct {
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if json.Unmarshal(client, &address) != nil {
|
||||
return false
|
||||
}
|
||||
_, remove := emails[address.Email]
|
||||
return remove
|
||||
})
|
||||
if len(clients) == count {
|
||||
continue
|
||||
}
|
||||
// Removing the last client keeps an empty array.
|
||||
settings["clients"], _ = json.Marshal(clients)
|
||||
inbound.Settings, _ = json.Marshal(settings)
|
||||
changed = true
|
||||
}
|
||||
return inbounds
|
||||
})
|
||||
return changed
|
||||
}
|
||||
|
||||
// editInbounds swaps in a copy: readers keep the snapshot GetConfig handed them.
|
||||
func (p *Process) editInbounds(edit func([]InboundConfig) []InboundConfig) {
|
||||
p.mu.Lock()
|
||||
|
||||
Reference in New Issue
Block a user