feat(monitoring): allow selecting the network interface for traffic statistics (#6972)

The panel's network totals and speed add up every interface that is not on a fixed list of virtual names. On hosts where a second interface carries the same traffic, such as an SR-IOV function beside eth0, the dashboard and the bot reports counted it twice (#6906).

Add a traffic mode to General settings: legacy keeps today's sum, auto follows the default-route interface, manual names one. An interface that is not available shows as unavailable in the dashboard and in the Telegram and Discord reports instead of 0 B, and a saved manual choice is only re-checked when it changes.
This commit is contained in:
Hamed
2026-11-24 19:55:55 +03:30
committed by GitHub
parent 447b2d036a
commit e0c01942ec
63 changed files with 2767 additions and 176 deletions
+81
View File
@@ -49,6 +49,87 @@ can obtain a Let's Encrypt certificate for you — or terminate TLS at a
| `timeLocation` | `Local` | Time zone for stats and expiry. |
| `datepicker` | `gregorian` | Calendar for date inputs (Gregorian or Jalali/Persian). |
## Network traffic interface
In **Settings → General → Panel settings**, use **Network Traffic Interface**
to select the source of system traffic totals and throughput. It does not change
Xray client quotas, client billing counters, or inbound traffic accounting.
| Setting | Default | Meaning |
| --- | --- | --- |
| `networkTrafficMode` | `legacy` | `legacy`, `auto`, or `manual`. |
| `networkTrafficInterface` | _(empty)_ | Exact interface name used in manual mode, such as `eth0`, `ens3`, or `enP6129s1`. |
- **All interfaces (Legacy)** remains the default on new installations and upgrades.
It sums the same interfaces as before, excluding the existing loopback and virtual
interface prefixes. Stacked interfaces, such as Azure's synthetic interface and
its SR-IOV function, can represent the same traffic and be counted twice.
- **Automatic** reads Linux's main routing table through netlink without executing
shell commands or sending network probes. Among usable default routes, IPv4 is
preferred to IPv6. The lowest route metric wins within that family; equal metrics
use the interface name as a deterministic tie-breaker. IPv6-only systems use their
IPv6 default route. ECMP also selects a single usable next hop.
Only the selected interface is counted, including virtual
interfaces when the default route uses one. Policy-routing tables and
destination-specific route selection are outside this primary-route heuristic.
- **Manual** lists interfaces dynamically and counts only the exact selected name.
Explicit selections bypass the legacy virtual-interface exclusions. The backend
validates that a newly selected interface exists when settings are saved.
An unchanged saved selection may remain unavailable, so unrelated settings can
still be edited while the interface is absent.
![Manual network traffic interface selection](/images/network-traffic-interface.png)
![Automatic default-route interface resolution](/images/network-traffic-automatic.png)
These screenshots render the settings component locally with example interface names.
Automatic detection runs on each status collection, normally every two seconds,
so route changes take effect on the next sample. If detection fails, a selected
interface disappears, or counters cannot be read, the network metrics are marked
unavailable. The dashboard and bot reports show this state, and histories omit
unavailable samples. No other interface or aggregation mode is substituted.
When the interface returns, normal collection resumes automatically.
Speed and packet-rate calculations start from a new baseline after a mode change,
interface change, detected device recreation, counter decrease/reset, or a failed
sample. The first comparable sample resumes normal rates. Totals remain the
selected kernel counters, rather than monthly billing totals; existing history
can contain samples collected under previous interface selections.
Each panel, including a sub-node, selects interfaces in its own network namespace.
In a Docker bridge network these are container interfaces, not host-wide traffic.
Host interfaces are visible only when the deployment shares the host network
namespace. Reading interfaces, routes, and counters requires no `CAP_NET_ADMIN`,
firewall rules, nftables setup, Python process, or additional daemon. The existing
Docker capabilities needed by other features are unrelated to this setting.
Legacy and manual modes remain available on supported non-Linux platforms.
Automatic mode currently requires Linux; other platforms show an explicit
detection error and should use manual or legacy mode.
Settings persist in the existing key/value settings table; no schema migration is
needed. Database backups retain the selection. **Keep this machine's settings** on
import preserves the destination panel's selection, including a missing setting
that uses the legacy default. An imported manual interface that does not exist
is reported as unavailable rather than replaced.
Older settings API clients that omit the new fields preserve the current selection.
Send an explicit `networkTrafficMode: "legacy"` to restore legacy aggregation.
Authenticated administrators can list interfaces with
`GET /panel/api/server/networkInterfaces`. It uses the existing response envelope
and returns interface names/up state plus the automatic choice or detection error.
Status responses retain `netTraffic` and `netIO` and add `networkInterface`
(`mode`, `name`, `available`, `error`), together with the existing
`unavailableMetrics` list when collection fails. Older status responses without
this metadata remain compatible.
The default-route selection approach was inspired by
[IPv6Monitor](https://github.com/HamedSanaei/ipv6monitor). Its Python daemon,
database, and nftables accounting are not used. Separate IPv4/IPv6 traffic counters
are outside this feature's scope: the selected interface's counters include both.
## Security & authentication
Credentials, two-factor auth, the brute-force limiter, sessions, and LDAP are
+10 -1
View File
@@ -23,6 +23,11 @@ _openapi:
panel uses it to gate the "IP Limit" field, since enforcement depends on
Fail2ban being installed.
url: '#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed'
- depth: 2
title: List network interface names and resolve the primary default-route
interface in this panel network namespace. Requires an admin session or
admin API token. No addresses or hardware identifiers are returned.
url: '#list-network-interface-names-and-resolve-the-primary-default-route-interface-in-this-panel-network-namespace-requires-an-admin-session-or-admin-api-token-no-addresses-or-hardware-identifiers-are-returned'
- depth: 2
title: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.'
@@ -195,6 +200,10 @@ _openapi:
panel uses it to gate the "IP Limit" field, since enforcement depends
on Fail2ban being installed.
id: reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: List network interface names and resolve the primary default-route
interface in this panel network namespace. Requires an admin session
or admin API token. No addresses or hardware identifiers are returned.
id: list-network-interface-names-and-resolve-the-primary-default-route-interface-in-this-panel-network-namespace-requires-an-admin-session-or-admin-api-token-no-addresses-or-hardware-identifiers-are-returned
- content: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead —
same data with a uniform {t, v} shape.'
id: legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
@@ -325,7 +334,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/openapi.json","method":"get"},{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getUpdateStatus","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/amneziawglogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/scanRealityTarget","method":"post"},{"path":"/panel/api/server/scanRealityTargets","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/openapi.json","method":"get"},{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/networkInterfaces","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getUpdateStatus","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/amneziawglogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/scanRealityTarget","method":"post"},{"path":"/panel/api/server/scanRealityTargets","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
</>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+266 -29
View File
@@ -152,6 +152,19 @@
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -663,6 +676,8 @@
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -962,6 +977,19 @@
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -1481,6 +1509,8 @@
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -3753,6 +3783,72 @@
],
"type": "object"
},
"NetworkInterfaceOption": {
"properties": {
"name": {
"example": "eth0",
"type": "string"
},
"up": {
"example": true,
"type": "boolean"
}
},
"required": [
"name",
"up"
],
"type": "object"
},
"NetworkInterfacesResponse": {
"properties": {
"automatic": {
"example": "eth0",
"type": "string"
},
"automaticError": {
"type": "string"
},
"interfaces": {
"items": {
"$ref": "#/components/schemas/NetworkInterfaceOption"
},
"type": "array"
}
},
"required": [
"automatic",
"automaticError",
"interfaces"
],
"type": "object"
},
"NetworkTrafficSelection": {
"properties": {
"available": {
"example": true,
"type": "boolean"
},
"error": {
"type": "string"
},
"mode": {
"example": "manual",
"type": "string"
},
"name": {
"example": "eth0",
"type": "string"
}
},
"required": [
"available",
"error",
"mode",
"name"
],
"type": "object"
},
"NewUUIDResponse": {
"properties": {
"uuid": {
@@ -4892,6 +4988,99 @@
],
"type": "object"
},
"Status": {
"description": "Status represents comprehensive system and application status information.\nIt includes CPU, memory, disk, network statistics, and Xray process status.",
"properties": {
"amneziawg": {
"description": "AmneziaWG gates the overview's AmneziaWG log view: Configured stays true\nwhile an inbound exists but its embedded interface isn't up yet, which\nis exactly when that view's event lines are worth reading."
},
"appStats": {},
"cpu": {
"type": "number"
},
"cpuCores": {
"type": "integer"
},
"cpuSpeedMhz": {
"type": "number"
},
"disk": {},
"diskIO": {},
"diskTraffic": {},
"loads": {
"items": {
"type": "number"
},
"type": "array"
},
"logicalPro": {
"type": "integer"
},
"mem": {},
"netIO": {},
"netTraffic": {},
"networkInterface": {
"allOf": [
{
"$ref": "#/components/schemas/NetworkTrafficSelection"
}
],
"nullable": true
},
"panelGuid": {
"type": "string"
},
"panelVersion": {
"type": "string"
},
"publicIP": {},
"resourceScope": {
"type": "string"
},
"swap": {},
"tcpCount": {
"type": "integer"
},
"udpCount": {
"type": "integer"
},
"unavailableMetrics": {
"items": {
"type": "string"
},
"type": "array"
},
"uptime": {
"format": "int64",
"type": "integer"
},
"xray": {}
},
"required": [
"amneziawg",
"appStats",
"cpu",
"cpuCores",
"cpuSpeedMhz",
"disk",
"diskIO",
"diskTraffic",
"loads",
"logicalPro",
"mem",
"netIO",
"netTraffic",
"panelGuid",
"panelVersion",
"publicIP",
"swap",
"tcpCount",
"udpCount",
"uptime",
"xray"
],
"type": "object"
},
"SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": {
@@ -6602,39 +6791,42 @@
"msg": {
"type": "string"
},
"obj": {}
"obj": {
"$ref": "#/components/schemas/Status"
}
}
},
"example": {
"success": true,
"obj": {
"cpu": 12.5,
"mem": {
"current": 2147483648,
"total": 8589934592
},
"swap": {
"current": 0,
"total": 4294967296
},
"disk": {
"current": 53687091200,
"total": 268435456000
},
"netIO": {
"up": 1073741824,
"down": 2147483648
},
"xray": {
"state": "running",
"version": "v25.10.31"
},
"tcpCount": 42,
"load": {
"load1": 0.5,
"load5": 0.3,
"load15": 0.2
}
"amneziawg": null,
"appStats": null,
"cpu": 0,
"cpuCores": 0,
"cpuSpeedMhz": 0,
"disk": null,
"diskIO": null,
"diskTraffic": null,
"loads": [
0
],
"logicalPro": 0,
"mem": null,
"netIO": null,
"netTraffic": null,
"networkInterface": null,
"panelGuid": "",
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"swap": null,
"tcpCount": 0,
"udpCount": 0,
"unavailableMetrics": [
""
],
"uptime": 0,
"xray": null
}
}
}
@@ -6682,6 +6874,51 @@
}
}
},
"/panel/api/server/networkInterfaces": {
"get": {
"tags": [
"Server"
],
"summary": "List network interface names and resolve the primary default-route interface in this panel network namespace. Requires an admin session or admin API token. No addresses or hardware identifiers are returned.",
"operationId": "get_panel_api_server_networkInterfaces",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/NetworkInterfacesResponse"
}
}
},
"example": {
"success": true,
"obj": {
"automatic": "eth0",
"automaticError": "",
"interfaces": [
{
"name": "eth0",
"up": true
}
]
}
}
}
}
}
}
}
},
"/panel/api/server/cpuHistory/{bucket}": {
"get": {
"tags": [
@@ -8004,7 +8241,7 @@
"keepHostSettings": {
"type": "boolean",
"default": true,
"description": "Keep this machine's addresses, certificates and node identity. Default true."
"description": "Keep this machine's addresses, certificates, node identity, and network traffic interface selection. Default true."
}
},
"required": [
+266 -29
View File
@@ -152,6 +152,19 @@
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -663,6 +676,8 @@
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -962,6 +977,19 @@
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -1481,6 +1509,8 @@
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -3753,6 +3783,72 @@
],
"type": "object"
},
"NetworkInterfaceOption": {
"properties": {
"name": {
"example": "eth0",
"type": "string"
},
"up": {
"example": true,
"type": "boolean"
}
},
"required": [
"name",
"up"
],
"type": "object"
},
"NetworkInterfacesResponse": {
"properties": {
"automatic": {
"example": "eth0",
"type": "string"
},
"automaticError": {
"type": "string"
},
"interfaces": {
"items": {
"$ref": "#/components/schemas/NetworkInterfaceOption"
},
"type": "array"
}
},
"required": [
"automatic",
"automaticError",
"interfaces"
],
"type": "object"
},
"NetworkTrafficSelection": {
"properties": {
"available": {
"example": true,
"type": "boolean"
},
"error": {
"type": "string"
},
"mode": {
"example": "manual",
"type": "string"
},
"name": {
"example": "eth0",
"type": "string"
}
},
"required": [
"available",
"error",
"mode",
"name"
],
"type": "object"
},
"NewUUIDResponse": {
"properties": {
"uuid": {
@@ -4892,6 +4988,99 @@
],
"type": "object"
},
"Status": {
"description": "Status represents comprehensive system and application status information.\nIt includes CPU, memory, disk, network statistics, and Xray process status.",
"properties": {
"amneziawg": {
"description": "AmneziaWG gates the overview's AmneziaWG log view: Configured stays true\nwhile an inbound exists but its embedded interface isn't up yet, which\nis exactly when that view's event lines are worth reading."
},
"appStats": {},
"cpu": {
"type": "number"
},
"cpuCores": {
"type": "integer"
},
"cpuSpeedMhz": {
"type": "number"
},
"disk": {},
"diskIO": {},
"diskTraffic": {},
"loads": {
"items": {
"type": "number"
},
"type": "array"
},
"logicalPro": {
"type": "integer"
},
"mem": {},
"netIO": {},
"netTraffic": {},
"networkInterface": {
"allOf": [
{
"$ref": "#/components/schemas/NetworkTrafficSelection"
}
],
"nullable": true
},
"panelGuid": {
"type": "string"
},
"panelVersion": {
"type": "string"
},
"publicIP": {},
"resourceScope": {
"type": "string"
},
"swap": {},
"tcpCount": {
"type": "integer"
},
"udpCount": {
"type": "integer"
},
"unavailableMetrics": {
"items": {
"type": "string"
},
"type": "array"
},
"uptime": {
"format": "int64",
"type": "integer"
},
"xray": {}
},
"required": [
"amneziawg",
"appStats",
"cpu",
"cpuCores",
"cpuSpeedMhz",
"disk",
"diskIO",
"diskTraffic",
"loads",
"logicalPro",
"mem",
"netIO",
"netTraffic",
"panelGuid",
"panelVersion",
"publicIP",
"swap",
"tcpCount",
"udpCount",
"uptime",
"xray"
],
"type": "object"
},
"SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": {
@@ -6602,39 +6791,42 @@
"msg": {
"type": "string"
},
"obj": {}
"obj": {
"$ref": "#/components/schemas/Status"
}
}
},
"example": {
"success": true,
"obj": {
"cpu": 12.5,
"mem": {
"current": 2147483648,
"total": 8589934592
},
"swap": {
"current": 0,
"total": 4294967296
},
"disk": {
"current": 53687091200,
"total": 268435456000
},
"netIO": {
"up": 1073741824,
"down": 2147483648
},
"xray": {
"state": "running",
"version": "v25.10.31"
},
"tcpCount": 42,
"load": {
"load1": 0.5,
"load5": 0.3,
"load15": 0.2
}
"amneziawg": null,
"appStats": null,
"cpu": 0,
"cpuCores": 0,
"cpuSpeedMhz": 0,
"disk": null,
"diskIO": null,
"diskTraffic": null,
"loads": [
0
],
"logicalPro": 0,
"mem": null,
"netIO": null,
"netTraffic": null,
"networkInterface": null,
"panelGuid": "",
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"swap": null,
"tcpCount": 0,
"udpCount": 0,
"unavailableMetrics": [
""
],
"uptime": 0,
"xray": null
}
}
}
@@ -6682,6 +6874,51 @@
}
}
},
"/panel/api/server/networkInterfaces": {
"get": {
"tags": [
"Server"
],
"summary": "List network interface names and resolve the primary default-route interface in this panel network namespace. Requires an admin session or admin API token. No addresses or hardware identifiers are returned.",
"operationId": "get_panel_api_server_networkInterfaces",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/NetworkInterfacesResponse"
}
}
},
"example": {
"success": true,
"obj": {
"automatic": "eth0",
"automaticError": "",
"interfaces": [
{
"name": "eth0",
"up": true
}
]
}
}
}
}
}
}
}
},
"/panel/api/server/cpuHistory/{bucket}": {
"get": {
"tags": [
@@ -8004,7 +8241,7 @@
"keepHostSettings": {
"type": "boolean",
"default": true,
"description": "Keep this machine's addresses, certificates and node identity. Default true."
"description": "Keep this machine's addresses, certificates, node identity, and network traffic interface selection. Default true."
}
},
"required": [
+2 -2
View File
@@ -6,7 +6,7 @@ import { parseMsg } from '@/utils/zodValidate';
import { AllSetting } from '@/models/setting';
import {
AllSettingResponseSchema,
AllSettingSchema,
AllSettingFieldsSchema,
type AllSettingInput,
} from '@/schemas/setting';
import { keys } from '@/api/queryKeys';
@@ -63,7 +63,7 @@ export function useAllSettings() {
saved?: AllSetting;
}): Promise<SettingSaveResult> => {
const next = { ...payload };
const body = AllSettingSchema.partial().safeParse(next);
const body = AllSettingFieldsSchema.partial().safeParse(next);
if (!body.success) {
console.warn('[zod] setting/update body failed validation', body.error.issues);
}
@@ -0,0 +1,21 @@
import { useQuery } from '@tanstack/react-query';
import { NetworkInterfacesResponseSchema } from '@/generated/zod';
import { keys } from '@/api/queryKeys';
import { HttpUtil } from '@/utils';
export function useNetworkInterfaces(enabled: boolean) {
return useQuery({
enabled,
queryKey: keys.server.networkInterfaces(),
queryFn: async () => {
const msg = await HttpUtil.get('/panel/api/server/networkInterfaces', undefined, {
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load network interfaces');
return NetworkInterfacesResponseSchema.parse(msg.obj);
},
staleTime: 10_000,
refetchInterval: 15_000,
});
}
+1
View File
@@ -2,6 +2,7 @@ export const keys = {
sponsors: () => ['sponsors'] as const,
server: {
status: () => ['server', 'status'] as const,
networkInterfaces: () => ['server', 'networkInterfaces'] as const,
fail2banStatus: () => ['server', 'fail2banStatus'] as const,
},
nodes: {
+54
View File
@@ -39,6 +39,8 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapUserAttr": "",
"ldapUserFilter": "",
"ldapVlessField": "",
"networkTrafficInterface": "eth0",
"networkTrafficMode": "legacy",
"nodeDownThreshold": 1,
"outboundDownThreshold": 1,
"pageSize": 0,
@@ -233,6 +235,8 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapUserAttr": "",
"ldapUserFilter": "",
"ldapVlessField": "",
"networkTrafficInterface": "eth0",
"networkTrafficMode": "legacy",
"nodeDownThreshold": 1,
"outboundDownThreshold": 1,
"pageSize": 0,
@@ -946,6 +950,26 @@ export const EXAMPLES: Record<string, unknown> = {
"obj": null,
"success": false
},
"NetworkInterfaceOption": {
"name": "eth0",
"up": true
},
"NetworkInterfacesResponse": {
"automatic": "eth0",
"automaticError": "",
"interfaces": [
{
"name": "eth0",
"up": true
}
]
},
"NetworkTrafficSelection": {
"available": true,
"error": "",
"mode": "manual",
"name": "eth0"
},
"NewUUIDResponse": {
"uuid": "550e8400-e29b-41d4-a716-446655440000"
},
@@ -1217,6 +1241,36 @@ export const EXAMPLES: Record<string, unknown> = {
}
]
},
"Status": {
"amneziawg": null,
"appStats": null,
"cpu": 0,
"cpuCores": 0,
"cpuSpeedMhz": 0,
"disk": null,
"diskIO": null,
"diskTraffic": null,
"loads": [
0
],
"logicalPro": 0,
"mem": null,
"netIO": null,
"netTraffic": null,
"networkInterface": null,
"panelGuid": "",
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"swap": null,
"tcpCount": 0,
"udpCount": 0,
"unavailableMetrics": [
""
],
"uptime": 0,
"xray": null
},
"SubBalancer": {
"createdAt": 1710000000000,
"enabled": true,
+189
View File
@@ -126,6 +126,19 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -637,6 +650,8 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -936,6 +951,19 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapVlessField": {
"type": "string"
},
"networkTrafficInterface": {
"example": "eth0",
"type": "string"
},
"networkTrafficMode": {
"enum": [
"legacy",
"auto",
"manual"
],
"example": "legacy",
"type": "string"
},
"nodeDownThreshold": {
"maximum": 100,
"minimum": 1,
@@ -1455,6 +1483,8 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapUserAttr",
"ldapUserFilter",
"ldapVlessField",
"networkTrafficInterface",
"networkTrafficMode",
"nodeDownThreshold",
"outboundDownThreshold",
"pageSize",
@@ -3727,6 +3757,72 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"NetworkInterfaceOption": {
"properties": {
"name": {
"example": "eth0",
"type": "string"
},
"up": {
"example": true,
"type": "boolean"
}
},
"required": [
"name",
"up"
],
"type": "object"
},
"NetworkInterfacesResponse": {
"properties": {
"automatic": {
"example": "eth0",
"type": "string"
},
"automaticError": {
"type": "string"
},
"interfaces": {
"items": {
"$ref": "#/components/schemas/NetworkInterfaceOption"
},
"type": "array"
}
},
"required": [
"automatic",
"automaticError",
"interfaces"
],
"type": "object"
},
"NetworkTrafficSelection": {
"properties": {
"available": {
"example": true,
"type": "boolean"
},
"error": {
"type": "string"
},
"mode": {
"example": "manual",
"type": "string"
},
"name": {
"example": "eth0",
"type": "string"
}
},
"required": [
"available",
"error",
"mode",
"name"
],
"type": "object"
},
"NewUUIDResponse": {
"properties": {
"uuid": {
@@ -4866,6 +4962,99 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"Status": {
"description": "Status represents comprehensive system and application status information.\nIt includes CPU, memory, disk, network statistics, and Xray process status.",
"properties": {
"amneziawg": {
"description": "AmneziaWG gates the overview's AmneziaWG log view: Configured stays true\nwhile an inbound exists but its embedded interface isn't up yet, which\nis exactly when that view's event lines are worth reading."
},
"appStats": {},
"cpu": {
"type": "number"
},
"cpuCores": {
"type": "integer"
},
"cpuSpeedMhz": {
"type": "number"
},
"disk": {},
"diskIO": {},
"diskTraffic": {},
"loads": {
"items": {
"type": "number"
},
"type": "array"
},
"logicalPro": {
"type": "integer"
},
"mem": {},
"netIO": {},
"netTraffic": {},
"networkInterface": {
"allOf": [
{
"$ref": "#/components/schemas/NetworkTrafficSelection"
}
],
"nullable": true
},
"panelGuid": {
"type": "string"
},
"panelVersion": {
"type": "string"
},
"publicIP": {},
"resourceScope": {
"type": "string"
},
"swap": {},
"tcpCount": {
"type": "integer"
},
"udpCount": {
"type": "integer"
},
"unavailableMetrics": {
"items": {
"type": "string"
},
"type": "array"
},
"uptime": {
"format": "int64",
"type": "integer"
},
"xray": {}
},
"required": [
"amneziawg",
"appStats",
"cpu",
"cpuCores",
"cpuSpeedMhz",
"disk",
"diskIO",
"diskTraffic",
"loads",
"logicalPro",
"mem",
"netIO",
"netTraffic",
"panelGuid",
"panelVersion",
"publicIP",
"swap",
"tcpCount",
"udpCount",
"uptime",
"xray"
],
"type": "object"
},
"SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": {
+49 -4
View File
@@ -4,10 +4,6 @@ export type GeoKind = string;
export type OnlineAPISupport = number;
export type ProcessState = string;
export type Protocol = string;
export type addrFamily = number;
export type staticEgressResolver = string;
export type trafficLocalApplyAction = number;
export type transportBits = number;
export interface AllSetting {
datepicker: string;
@@ -48,6 +44,8 @@ export interface AllSetting {
ldapUserAttr: string;
ldapUserFilter: string;
ldapVlessField: string;
networkTrafficInterface: string;
networkTrafficMode: string;
nodeDownThreshold: number;
outboundDownThreshold: number;
pageSize: number;
@@ -243,6 +241,8 @@ export interface AllSettingView {
ldapUserAttr: string;
ldapUserFilter: string;
ldapVlessField: string;
networkTrafficInterface: string;
networkTrafficMode: string;
nodeDownThreshold: number;
outboundDownThreshold: number;
pageSize: number;
@@ -860,6 +860,24 @@ export interface Msg {
success: boolean;
}
export interface NetworkInterfaceOption {
name: string;
up: boolean;
}
export interface NetworkInterfacesResponse {
automatic: string;
automaticError: string;
interfaces: NetworkInterfaceOption[];
}
export interface NetworkTrafficSelection {
available: boolean;
error: string;
mode: string;
name: string;
}
export interface NewUUIDResponse {
uuid: string;
}
@@ -1109,6 +1127,33 @@ export interface SponsorList {
sponsors: Sponsor[];
}
export interface Status {
amneziawg: unknown;
appStats: unknown;
cpu: number;
cpuCores: number;
cpuSpeedMhz: number;
disk: unknown;
diskIO: unknown;
diskTraffic: unknown;
loads: number[];
logicalPro: number;
mem: unknown;
netIO: unknown;
netTraffic: unknown;
networkInterface?: NetworkTrafficSelection | null;
panelGuid: string;
panelVersion: string;
publicIP: unknown;
resourceScope?: string;
swap: unknown;
tcpCount: number;
udpCount: number;
unavailableMetrics?: string[];
uptime: number;
xray: unknown;
}
export interface SubBalancer {
createdAt: number;
enabled: boolean;
+53 -12
View File
@@ -15,18 +15,6 @@ export type ProcessState = z.infer<typeof ProcessStateSchema>;
export const ProtocolSchema = z.string();
export type Protocol = z.infer<typeof ProtocolSchema>;
export const addrFamilySchema = z.number().int();
export type addrFamily = z.infer<typeof addrFamilySchema>;
export const staticEgressResolverSchema = z.string();
export type staticEgressResolver = z.infer<typeof staticEgressResolverSchema>;
export const trafficLocalApplyActionSchema = z.number().int();
export type trafficLocalApplyAction = z.infer<typeof trafficLocalApplyActionSchema>;
export const transportBitsSchema = z.number().int();
export type transportBits = z.infer<typeof transportBitsSchema>;
export const AllSettingSchema = z.object({
datepicker: z.string(),
discordAdminIds: z.string(),
@@ -66,6 +54,8 @@ export const AllSettingSchema = z.object({
ldapUserAttr: z.string(),
ldapUserFilter: z.string(),
ldapVlessField: z.string(),
networkTrafficInterface: z.string(),
networkTrafficMode: z.enum(['legacy', 'auto', 'manual']),
nodeDownThreshold: z.number().int().min(1).max(100),
outboundDownThreshold: z.number().int().min(1).max(100),
pageSize: z.number().int().min(0).max(1000),
@@ -262,6 +252,8 @@ export const AllSettingViewSchema = z.object({
ldapUserAttr: z.string(),
ldapUserFilter: z.string(),
ldapVlessField: z.string(),
networkTrafficInterface: z.string(),
networkTrafficMode: z.enum(['legacy', 'auto', 'manual']),
nodeDownThreshold: z.number().int().min(1).max(100),
outboundDownThreshold: z.number().int().min(1).max(100),
pageSize: z.number().int().min(0).max(1000),
@@ -919,6 +911,27 @@ export const MsgSchema = z.object({
});
export type Msg = z.infer<typeof MsgSchema>;
export const NetworkInterfaceOptionSchema = z.object({
name: z.string(),
up: z.boolean(),
});
export type NetworkInterfaceOption = z.infer<typeof NetworkInterfaceOptionSchema>;
export const NetworkInterfacesResponseSchema = z.object({
automatic: z.string(),
automaticError: z.string(),
interfaces: z.array(z.lazy(() => NetworkInterfaceOptionSchema)),
});
export type NetworkInterfacesResponse = z.infer<typeof NetworkInterfacesResponseSchema>;
export const NetworkTrafficSelectionSchema = z.object({
available: z.boolean(),
error: z.string(),
mode: z.string(),
name: z.string(),
});
export type NetworkTrafficSelection = z.infer<typeof NetworkTrafficSelectionSchema>;
export const NewUUIDResponseSchema = z.object({
uuid: z.string(),
});
@@ -1182,6 +1195,34 @@ export const SponsorListSchema = z.object({
});
export type SponsorList = z.infer<typeof SponsorListSchema>;
export const StatusSchema = z.object({
amneziawg: z.unknown(),
appStats: z.unknown(),
cpu: z.number(),
cpuCores: z.number().int(),
cpuSpeedMhz: z.number(),
disk: z.unknown(),
diskIO: z.unknown(),
diskTraffic: z.unknown(),
loads: z.array(z.number()),
logicalPro: z.number().int(),
mem: z.unknown(),
netIO: z.unknown(),
netTraffic: z.unknown(),
networkInterface: z.lazy(() => NetworkTrafficSelectionSchema).nullable().optional(),
panelGuid: z.string(),
panelVersion: z.string(),
publicIP: z.unknown(),
resourceScope: z.string().optional(),
swap: z.unknown(),
tcpCount: z.number().int(),
udpCount: z.number().int(),
unavailableMetrics: z.array(z.string()).optional(),
uptime: z.number().int(),
xray: z.unknown(),
});
export type Status = z.infer<typeof StatusSchema>;
export const SubBalancerSchema = z.object({
createdAt: z.number().int(),
enabled: z.boolean(),
+3 -1
View File
@@ -1,5 +1,5 @@
import { ObjectUtil } from '@/utils';
import type { SubProfileMode, SubHostSortMode } from '@/schemas/setting';
import type { SubProfileMode, SubHostSortMode, NetworkTrafficMode } from '@/schemas/setting';
export class AllSetting {
webListen = '';
@@ -18,6 +18,8 @@ export class AllSetting {
'www.cloudflare.com:443,www.microsoft.com:443,www.amazon.com:443,aws.amazon.com:443,www.samsung.com:443,www.nvidia.com:443,www.amd.com:443,www.intel.com:443,www.sony.com:443,dl.google.com:443';
ipLimitAllowlist = '';
panelOutbound = '';
networkTrafficMode: NetworkTrafficMode = 'legacy';
networkTrafficInterface = '';
pageSize = 25;
expireDiff = 0;
trafficDiff = 0;
+3
View File
@@ -68,6 +68,7 @@ export interface AmneziaWGInfo {
}
interface StatusInput extends Pick<ParsedStatusInput, 'resourceScope' | 'unavailableMetrics'> {
networkInterface?: ParsedStatusInput['networkInterface'];
cpu?: number;
cpuCores?: number;
logicalPro?: number;
@@ -89,6 +90,7 @@ interface StatusInput extends Pick<ParsedStatusInput, 'resourceScope' | 'unavail
}
export class Status {
networkInterface: ParsedStatusInput['networkInterface'];
resourceScope = '';
unavailableMetrics: string[] = [];
@@ -119,6 +121,7 @@ export class Status {
if (data == null) return;
this.resourceScope = data.resourceScope ?? '';
this.networkInterface = data.networkInterface;
this.unavailableMetrics = data.unavailableMetrics ?? [];
this.cpu = new CurTotal(data.cpu ?? 0, 100);
this.cpuCores = data.cpuCores ?? 0;
+9 -3
View File
@@ -455,8 +455,7 @@ export const sections: readonly Section[] = [
path: '/panel/api/server/status',
summary:
'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load averages, open connections, Xray state. Cached and refreshed every 2 seconds in the background.',
response:
'{\n "success": true,\n "obj": {\n "cpu": 12.5,\n "mem": { "current": 2147483648, "total": 8589934592 },\n "swap": { "current": 0, "total": 4294967296 },\n "disk": { "current": 53687091200, "total": 268435456000 },\n "netIO": { "up": 1073741824, "down": 2147483648 },\n "xray": { "state": "running", "version": "v25.10.31" },\n "tcpCount": 42,\n "load": { "load1": 0.5, "load5": 0.3, "load15": 0.2 }\n }\n}',
responseSchema: 'Status',
},
{
method: 'GET',
@@ -466,6 +465,13 @@ export const sections: readonly Section[] = [
response:
'{\n "success": true,\n "obj": {\n "enabled": true,\n "installed": true,\n "usable": true,\n "windows": false\n }\n}',
},
{
method: 'GET',
path: '/panel/api/server/networkInterfaces',
summary:
'List network interface names and resolve the primary default-route interface in this panel network namespace. Requires an admin session or admin API token. No addresses or hardware identifiers are returned.',
responseSchema: 'NetworkInterfacesResponse',
},
{
method: 'GET',
path: '/panel/api/server/cpuHistory/:bucket',
@@ -822,7 +828,7 @@ export const sections: readonly Section[] = [
name: 'keepHostSettings',
in: 'body (multipart)',
type: 'boolean',
desc: "Keep this machine's addresses, certificates and node identity. Default true.",
desc: "Keep this machine's addresses, certificates, node identity, and network traffic interface selection. Default true.",
optional: true,
defaultValue: true,
},
+29 -7
View File
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, theme } from 'antd';
import { Alert, Card, theme } from 'antd';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { SizeFormatter } from '@/utils';
@@ -27,6 +27,7 @@ export default function ThroughputCard({
const { token } = theme.useToken();
const accent = token.colorPrimary;
const downColor = token.colorTextTertiary;
const available = status.metricAvailable('netTraffic');
const referenceLines = useMemo(
() => [
@@ -38,6 +39,19 @@ export default function ThroughputCard({
return (
<Card hoverable styles={{ body: { padding: 0 } }}>
{!available && (
<Alert
type="warning"
showIcon
title={t('pages.settings.networkTrafficUnavailable')}
description={status.networkInterface?.error}
/>
)}
{status.networkInterface?.name && available && (
<div className="ov-sub" style={{ padding: '8px 16px 0' }}>
{status.networkInterface.name}
</div>
)}
<div className="ov-wide-head">
<div>
<div className="ov-kicker">{t('pages.index.overallSpeed')}</div>
@@ -49,20 +63,24 @@ export default function ThroughputCard({
<div className="ov-legend-label">
<ArrowUpOutlined aria-hidden style={{ color: accent }} />
{t('pages.index.upload')}
<span className="ov-legend-num">{SizeFormatter.speedFormat(status.netIO.up)}</span>
<span className="ov-legend-num">
{available ? SizeFormatter.speedFormat(status.netIO.up) : '—'}
</span>
</div>
<div className="ov-legend-label">
<ArrowDownOutlined aria-hidden style={{ color: downColor }} />
{t('pages.index.download')}
<span className="ov-legend-num">{SizeFormatter.speedFormat(status.netIO.down)}</span>
<span className="ov-legend-num">
{available ? SizeFormatter.speedFormat(status.netIO.down) : '—'}
</span>
</div>
</div>
</div>
<div className="ov-wide-chart">
<Sparkline
data={up}
data2={down}
data={available ? up : []}
data2={available ? down : []}
labels={labels}
height={isMobile ? 140 : 186}
strokeWidth={1.75}
@@ -82,12 +100,16 @@ export default function ThroughputCard({
<div className="ov-wide-foot">
<div>
<div className="ov-kicker">{t('pages.index.sent')}</div>
<div className="ov-foot-value">{SizeFormatter.sizeFormat(status.netTraffic.sent)}</div>
<div className="ov-foot-value">
{available ? SizeFormatter.sizeFormat(status.netTraffic.sent) : '—'}
</div>
</div>
<span className="ov-foot-sep" />
<div>
<div className="ov-kicker">{t('pages.index.received')}</div>
<div className="ov-foot-value">{SizeFormatter.sizeFormat(status.netTraffic.recv)}</div>
<div className="ov-foot-value">
{available ? SizeFormatter.sizeFormat(status.netTraffic.recv) : '—'}
</div>
</div>
<span className="ov-foot-sep" />
<div>
@@ -163,10 +163,9 @@ export function useOverviewHistory(status: Status, hasData: boolean): OverviewHi
for (const key of SERIES_KEYS) {
const scoped = key === 'cpu' || key === 'swap';
const previous = scoped && scopeChanged ? [] : prev.series[key];
next.series[key] =
!scoped || status.metricAvailable(key)
? tailWindow(previous.concat(point[key]))
: previous;
next.series[key] = status.metricAvailable(key)
? tailWindow(previous.concat(point[key]))
: previous;
}
return next;
});
@@ -19,6 +19,7 @@ import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel';
import { sanitizePath } from './uriPath';
import SecretInput from './SecretInput';
import NetworkTrafficSettings from './NetworkTrafficSettings';
interface ApiMsg<T = unknown> {
success?: boolean;
@@ -373,6 +374,8 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
/>
</SettingListItem>
<NetworkTrafficSettings allSetting={allSetting} updateSetting={updateSetting} />
<SettingListItem
paddings="small"
title={t('pages.settings.pageSize')}
@@ -0,0 +1,101 @@
import { Alert, Button, Flex, Select, Spin, Typography } from 'antd';
import { useTranslation } from 'react-i18next';
import { useNetworkInterfaces } from '@/api/queries/useNetworkInterfaces';
import { SettingListItem } from '@/components/ui';
import type { AllSetting } from '@/models/setting';
export default function NetworkTrafficSettings({
allSetting,
updateSetting,
}: {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
}) {
const { t } = useTranslation();
const mode = allSetting.networkTrafficMode;
const query = useNetworkInterfaces(mode !== 'legacy');
const interfaces = query.data?.interfaces ?? [];
const missing =
mode === 'manual' &&
query.data &&
!interfaces.some((iface) => iface.name === allSetting.networkTrafficInterface);
return (
<SettingListItem
paddings="small"
title={t('pages.settings.networkTrafficInterfaceTitle')}
description={t('pages.settings.networkTrafficDescription')}
>
<Flex vertical gap="small" style={{ width: '100%' }}>
<Select
id="network-traffic-mode"
aria-label={t('pages.settings.networkTrafficMode')}
value={mode}
options={[
{ value: 'legacy', label: t('pages.settings.networkTrafficLegacy') },
{ value: 'auto', label: t('pages.settings.networkTrafficAutomatic') },
{ value: 'manual', label: t('pages.settings.networkTrafficManual') },
]}
onChange={(value) =>
updateSetting({ networkTrafficMode: value, networkTrafficInterface: '' })
}
/>
{mode === 'manual' && (
<Select
id="network-traffic-interface"
aria-label={t('pages.settings.networkTrafficInterfaceTitle')}
showSearch
value={allSetting.networkTrafficInterface || undefined}
placeholder={t('pages.settings.networkTrafficInterfaceTitle')}
loading={query.isFetching}
disabled={query.isPending || query.isError}
options={interfaces.map((iface) => ({
value: iface.name,
title: iface.name,
label: iface.up ? iface.name : `${iface.name} (${t('disabled')})`,
}))}
notFoundContent={
query.isPending ? <Spin size="small" /> : t('pages.settings.networkTrafficEmpty')
}
onChange={(value) => updateSetting({ networkTrafficInterface: value })}
/>
)}
{mode !== 'legacy' && query.isPending && <Spin size="small" aria-label={t('loading')} />}
{mode !== 'legacy' && query.isError && (
<Alert
type="error"
showIcon
title={t('pages.settings.networkTrafficLoadError')}
action={
<Button size="small" onClick={() => void query.refetch()}>
{t('refresh')}
</Button>
}
/>
)}
{missing && (
<Alert type="warning" showIcon title={t('pages.settings.networkTrafficUnavailable')} />
)}
{mode === 'manual' && query.data && interfaces.length === 0 && (
<Typography.Text type="secondary">
{t('pages.settings.networkTrafficEmpty')}
</Typography.Text>
)}
{mode === 'auto' &&
query.data &&
(query.data.automatic ? (
<Typography.Text type="secondary">
{t('pages.settings.networkTrafficAutoResolved', { interface: query.data.automatic })}
</Typography.Text>
) : (
<Alert
type="warning"
showIcon
title={t('pages.settings.networkTrafficAutoUnavailable')}
description={query.data.automaticError}
/>
))}
</Flex>
</SettingListItem>
);
}
+17 -2
View File
@@ -4,13 +4,16 @@ const port = z.number().int().min(1).max(65535);
const nonNegativeInt = z.number().int().min(0);
const absolutePath = z.string().regex(/^\//, 'pages.settings.validation.pathLeadingSlash');
export const NetworkTrafficModeSchema = z.enum(['legacy', 'auto', 'manual']);
export type NetworkTrafficMode = z.infer<typeof NetworkTrafficModeSchema>;
export const SubProfileModeSchema = z.enum(['none', 'builtin', 'custom']);
export type SubProfileMode = z.infer<typeof SubProfileModeSchema>;
export const SubHostSortModeSchema = z.enum(['inbound-first', 'hosts-first']);
export type SubHostSortMode = z.infer<typeof SubHostSortModeSchema>;
export const AllSettingSchema = z
export const AllSettingFieldsSchema = z
.object({
webListen: z.string().optional(),
webDomain: z.string().optional(),
@@ -27,6 +30,8 @@ export const AllSettingSchema = z
realityScanCandidates: z.string().optional(),
ipLimitAllowlist: z.string().optional(),
panelOutbound: z.string().optional(),
networkTrafficMode: NetworkTrafficModeSchema.optional(),
networkTrafficInterface: z.string().max(255).optional(),
pageSize: z.number().int().min(0).max(1000).optional(),
expireDiff: nonNegativeInt.optional(),
trafficDiff: nonNegativeInt.max(100).optional(),
@@ -192,13 +197,23 @@ export const AllSettingSchema = z
})
.loose();
export const AllSettingSchema = AllSettingFieldsSchema.superRefine((setting, context) => {
if (setting.networkTrafficMode === 'manual' && !setting.networkTrafficInterface) {
context.addIssue({
code: 'custom',
path: ['networkTrafficInterface'],
message: 'pages.settings.networkTrafficUnavailable',
});
}
});
export type AllSettingInput = z.infer<typeof AllSettingSchema>;
// Existing installations can contain regex values saved before the backend
// enforced its 2,048-character limit. Accept those values when reading so the
// settings page can display and let users correct them, while keeping the
// stricter schema above for outgoing updates.
export const AllSettingResponseSchema = AllSettingSchema.extend({
export const AllSettingResponseSchema = AllSettingFieldsSchema.extend({
subJsonUserAgentRegex: z.string().optional(),
subClashUserAgentRegex: z.string().optional(),
});
+2
View File
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { NetworkTrafficSelectionSchema } from '@/generated/zod';
export const CurTotalInputSchema = z.object({
current: z.number().optional(),
@@ -36,6 +37,7 @@ export const XrayInfoSchema = z
.partial();
export const StatusSchema = z.object({
networkInterface: NetworkTrafficSelectionSchema.optional(),
resourceScope: z.string().optional(),
unavailableMetrics: z.array(z.string()).optional(),
cpu: z.number().optional(),
@@ -0,0 +1,144 @@
import { useState } from 'react';
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { AllSetting } from '@/models/setting';
import GeneralTab from '@/pages/settings/GeneralTab';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
function SettingsHarness({ initial }: { initial?: unknown }) {
const [settings, setSettings] = useState(() => new AllSetting(initial));
return (
<MemoryRouter>
<GeneralTab
allSetting={settings}
updateSetting={(patch) =>
setSettings((current) => new AllSetting({ ...current, ...patch }))
}
/>
<output data-testid="settings">{JSON.stringify(settings)}</output>
</MemoryRouter>
);
}
afterEach(() => vi.restoreAllMocks());
function mockInterfaces(names: string[], automatic = 'eth0', automaticError = '') {
vi.spyOn(HttpUtil, 'get').mockImplementation(
async (url) =>
new Msg(
true,
'',
url === '/panel/api/server/networkInterfaces'
? {
interfaces: names.map((name) => ({ name, up: true })),
automatic,
automaticError,
}
: [],
),
);
}
describe('network traffic settings', () => {
it('shows the automatic interface and reports detection failure without substituting legacy mode', async () => {
mockInterfaces(['eth0'], 'eth0');
const { unmount } = renderWithProviders(
<SettingsHarness initial={{ networkTrafficMode: 'auto' }} />,
);
await screen.findByText('Default-route interface: eth0');
unmount();
mockInterfaces(['eth0'], '', 'no default route');
renderWithProviders(<SettingsHarness initial={{ networkTrafficMode: 'auto' }} />);
await screen.findByText(
'No default-route interface is available. Traffic metrics remain unavailable until detection recovers or the mode changes.',
);
expect(JSON.parse(screen.getByTestId('settings').textContent || '{}').networkTrafficMode).toBe(
'auto',
);
});
it('shows loading and an empty result without fabricating interface options', async () => {
let complete: (value: Msg<unknown>) => void = () => undefined;
vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) =>
url === '/panel/api/server/networkInterfaces'
? new Promise<Msg<unknown>>((resolve) => {
complete = resolve;
})
: new Msg(true, '', []),
);
renderWithProviders(<SettingsHarness initial={{ networkTrafficMode: 'manual' }} />);
expect(
(document.getElementById('network-traffic-interface') as HTMLInputElement).disabled,
).toBe(true);
await act(async () =>
complete(
new Msg(true, '', { interfaces: [], automatic: '', automaticError: 'no default route' }),
),
);
await screen.findByText('No network interfaces are available.');
});
it('can retry an interface-list error and recover the automatic interface', async () => {
let attempts = 0;
vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) => {
if (url !== '/panel/api/server/networkInterfaces') return new Msg(true, '', []);
if (attempts++ === 0) throw new Error('offline');
return new Msg(true, '', {
interfaces: [{ name: 'eth0', up: true }],
automatic: 'eth0',
automaticError: '',
});
});
renderWithProviders(<SettingsHarness initial={{ networkTrafficMode: 'auto' }} />);
await screen.findByText('Could not load network interfaces.');
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
await screen.findByText('Default-route interface: eth0');
expect(screen.queryByText('Could not load network interfaces.')).toBeNull();
});
it('keeps legacy as the default and selects exactly the requested dynamic interface', async () => {
mockInterfaces(['eth0', 'ens3', 'enP6129s1', 'wg0']);
renderWithProviders(<SettingsHarness />);
expect(screen.getByText('All interfaces (Legacy)')).toBeTruthy();
chooseSelectOption('network-traffic-mode', 'Manual');
await waitFor(() =>
expect(
(document.getElementById('network-traffic-interface') as HTMLInputElement).disabled,
).toBe(false),
);
chooseSelectOption('network-traffic-interface', 'enP6129s1');
expect(JSON.parse(screen.getByTestId('settings').textContent || '{}')).toMatchObject({
networkTrafficMode: 'manual',
networkTrafficInterface: 'enP6129s1',
});
chooseSelectOption('network-traffic-interface', 'wg0');
expect(
JSON.parse(screen.getByTestId('settings').textContent || '{}').networkTrafficInterface,
).toBe('wg0');
});
it('preserves a saved missing interface and warns instead of replacing it', async () => {
mockInterfaces(['eth0']);
renderWithProviders(
<SettingsHarness
initial={{ networkTrafficMode: 'manual', networkTrafficInterface: 'removed0' }}
/>,
);
await screen.findByText(
'The selected network interface is unavailable. Choose an available interface or another monitoring mode.',
);
expect(
JSON.parse(screen.getByTestId('settings').textContent || '{}').networkTrafficInterface,
).toBe('removed0');
chooseSelectOption('network-traffic-interface', 'eth0');
await waitFor(() =>
expect(
screen.queryByText(
'The selected network interface is unavailable. Choose an available interface or another monitoring mode.',
),
).toBeNull(),
);
});
});
@@ -0,0 +1,66 @@
import { act, renderHook, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
import { StatusSchema } from '@/schemas/status';
import ThroughputCard from '@/pages/index/ThroughputCard';
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
vi.mock('@/components/viz', () => ({ Sparkline: () => null }));
afterEach(() => vi.restoreAllMocks());
describe('network traffic status', () => {
it('preserves selected interface metadata and displays unavailable metrics as missing', () => {
const status = new Status(
StatusSchema.parse({
networkInterface: {
mode: 'manual',
name: 'removed0',
available: false,
error: 'device removed',
},
unavailableMetrics: ['netTraffic', 'netUp', 'netDown'],
netIO: { up: 0, down: 0 },
netTraffic: { sent: 0, recv: 0 },
}),
);
expect(status.networkInterface).toEqual({
mode: 'manual',
name: 'removed0',
available: false,
error: 'device removed',
});
renderWithProviders(
<ThroughputCard
status={status}
up={[100]}
down={[200]}
labels={['12:00']}
isMobile={false}
/>,
);
expect(
screen.getByText(
'The selected network interface is unavailable. Choose an available interface or another monitoring mode.',
),
).toBeTruthy();
expect(screen.getAllByText('—')).toHaveLength(4);
});
it('does not turn unavailable network samples into real zero throughput history', async () => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
const { result, rerender } = renderHook(({ status }) => useOverviewHistory(status, true), {
initialProps: { status: new Status({ netIO: { up: 100, down: 200 } }) },
});
await act(async () => {});
rerender({
status: new Status({ unavailableMetrics: ['netUp', 'netDown'], netIO: { up: 0, down: 0 } }),
});
expect(result.current.series.netUp).toEqual([100]);
expect(result.current.series.netDown).toEqual([200]);
rerender({ status: new Status({ netIO: { up: 300, down: 400 } }) });
expect(result.current.series.netUp).toEqual([100, 300]);
});
});
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { AllSettingSchema } from '@/schemas/setting';
describe('network traffic settings validation', () => {
it('requires a selected interface for a complete manual-mode save', () => {
const result = AllSettingSchema.safeParse({
networkTrafficMode: 'manual',
networkTrafficInterface: '',
});
expect(result.success).toBe(false);
if (!result.success)
expect(result.error.issues.map((issue) => issue.path)).toEqual([['networkTrafficInterface']]);
expect(
AllSettingSchema.safeParse({
networkTrafficMode: 'manual',
networkTrafficInterface: 'enP6129s1',
}).success,
).toBe(true);
expect(
AllSettingSchema.safeParse({ networkTrafficMode: 'legacy', networkTrafficInterface: '' })
.success,
).toBe(true);
expect(
AllSettingSchema.safeParse({ networkTrafficMode: 'auto', networkTrafficInterface: '' })
.success,
).toBe(true);
});
});
@@ -13,6 +13,34 @@ afterEach(() => {
});
describe('useAllSettings', () => {
it('saves a manual traffic interface and reloads it in a fresh settings session', async () => {
let stored: { networkTrafficMode?: string; networkTrafficInterface?: string } = {};
vi.spyOn(HttpUtil, 'post').mockImplementation(async (url, body) => {
if (url === '/panel/api/setting/all') return new Msg(true, '', stored);
if (url === '/panel/api/setting/update') stored = body as typeof stored;
return new Msg(true, '', {});
});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={makeTestQueryClient()}>{children}</QueryClientProvider>
);
const first = renderHook(() => useAllSettings(), { wrapper });
await waitFor(() => expect(first.result.current.fetched).toBe(true));
expect(first.result.current.allSetting.networkTrafficMode).toBe('legacy');
act(() =>
first.result.current.updateSetting({
networkTrafficMode: 'manual',
networkTrafficInterface: 'enP6129s1',
}),
);
await act(async () => {
await first.result.current.saveAll();
});
first.unmount();
const second = renderHook(() => useAllSettings(), { wrapper });
await waitFor(() => expect(second.result.current.fetched).toBe(true));
expect(second.result.current.allSetting.networkTrafficMode).toBe('manual');
expect(second.result.current.allSetting.networkTrafficInterface).toBe('enP6129s1');
});
it('persists the subscription host ordering mode and reloads it in a fresh session', async () => {
let storedMode = 'inbound-first';
vi.spyOn(HttpUtil, 'post').mockImplementation(async (url, body) => {
+1 -1
View File
@@ -27,6 +27,7 @@ require (
github.com/shirou/gopsutil/v4 v4.26.10
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/valyala/fasthttp v1.80.0
github.com/vishvananda/netlink v1.3.1
github.com/xlzd/gotp v0.1.0
github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0
go.uber.org/atomic v1.12.0
@@ -98,7 +99,6 @@ require (
github.com/ugorji/go/codec v1.3.2 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fastjson v1.6.10 // indirect
github.com/vishvananda/netlink v1.3.1 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b // indirect
@@ -0,0 +1,66 @@
package controller
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
)
func TestNetworkInterfacesRequireAdminAndUseExistingEnvelope(t *testing.T) {
engine, api := newAPIAuthTestEngine(t)
controller := &ServerController{}
group := engine.Group("/panel/api/server", api.checkAPIAuth, api.enforceTokenScope)
group.GET("/networkInterfaces", controller.getNetworkInterfaces)
for _, tc := range []struct {
name, scope string
want int
}{
{"anonymous", "", http.StatusUnauthorized},
{"monitor", model.ApiScopeMonitor, http.StatusForbidden},
{"node sync", model.ApiScopeNodeSync, http.StatusForbidden},
{"admin", model.ApiScopeAdmin, http.StatusOK},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/panel/api/server/networkInterfaces", nil)
req.Header.Set("X-Requested-With", "XMLHttpRequest")
if tc.scope != "" {
token := "network-test-" + tc.name
if err := database.GetDB().Create(&model.ApiToken{Name: tc.name, Token: crypto.HashTokenSHA256(token), Scope: tc.scope, Enabled: true}).Error; err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
engine.ServeHTTP(w, req)
if w.Code != tc.want {
t.Fatalf("status=%d want=%d body=%s", w.Code, tc.want, w.Body.String())
}
if tc.want == http.StatusOK {
var response struct {
Success bool `json:"success"`
Obj struct {
Interfaces []map[string]any `json:"interfaces"`
Automatic string `json:"automatic"`
AutomaticError string `json:"automaticError"`
} `json:"obj"`
}
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if !response.Success || response.Obj.Interfaces == nil {
t.Fatalf("response=%s", w.Body.String())
}
for _, iface := range response.Obj.Interfaces {
if len(iface) != 2 || iface["name"] == "" {
t.Fatalf("unexpected interface metadata: %v", iface)
}
}
}
})
}
}
+6
View File
@@ -66,6 +66,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
g.GET("/getNewVlessEnc", a.getNewVlessEnc)
g.GET("/clientIps", a.getClientIps)
g.GET("/fail2banStatus", a.getFail2banStatus)
g.GET("/networkInterfaces", a.getNetworkInterfaces)
g.POST("/stopXrayService", a.stopXrayService)
g.POST("/restartXrayService", a.restartXrayService)
@@ -114,6 +115,11 @@ func (a *ServerController) getFail2banStatus(c *gin.Context) {
jsonObj(c, a.serverService.GetFail2banStatus(), nil)
}
func (a *ServerController) getNetworkInterfaces(c *gin.Context) {
interfaces, err := a.serverService.GetNetworkInterfaces()
jsonObj(c, interfaces, err)
}
func parseHistoryBucket(c *gin.Context) (int, bool) {
bucket, err := strconv.Atoi(c.Param("bucket"))
if err != nil || bucket <= 0 || !service.IsAllowedHistoryBucket(bucket) {
+10 -8
View File
@@ -29,14 +29,16 @@ type AllSetting struct {
WebBasePath string `json:"webBasePath" form:"webBasePath"`
SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge" validate:"gte=1,lte=525600"`
// 0 stops refreshing the detected public IP after the first success.
PublicIpRefreshMinutes int `json:"publicIpRefreshMinutes" form:"publicIpRefreshMinutes" validate:"gte=0,lte=10080"`
PublicIpv6Detect bool `json:"publicIpv6Detect" form:"publicIpv6Detect"`
PublicIpv4Override string `json:"publicIpv4Override" form:"publicIpv4Override"`
PublicIpv6Override string `json:"publicIpv6Override" form:"publicIpv6Override"`
TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"`
RealityScanCandidates string `json:"realityScanCandidates" form:"realityScanCandidates"`
IpLimitAllowlist string `json:"ipLimitAllowlist" form:"ipLimitAllowlist"`
PanelOutbound string `json:"panelOutbound" form:"panelOutbound"`
PublicIpRefreshMinutes int `json:"publicIpRefreshMinutes" form:"publicIpRefreshMinutes" validate:"gte=0,lte=10080"`
PublicIpv6Detect bool `json:"publicIpv6Detect" form:"publicIpv6Detect"`
PublicIpv4Override string `json:"publicIpv4Override" form:"publicIpv4Override"`
PublicIpv6Override string `json:"publicIpv6Override" form:"publicIpv6Override"`
TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"`
RealityScanCandidates string `json:"realityScanCandidates" form:"realityScanCandidates"`
IpLimitAllowlist string `json:"ipLimitAllowlist" form:"ipLimitAllowlist"`
PanelOutbound string `json:"panelOutbound" form:"panelOutbound"`
NetworkTrafficMode string `json:"networkTrafficMode" form:"networkTrafficMode" validate:"omitempty,oneof=legacy auto manual" example:"legacy"`
NetworkTrafficInterface string `json:"networkTrafficInterface" form:"networkTrafficInterface" example:"eth0"`
PageSize int `json:"pageSize" form:"pageSize" validate:"gte=0,lte=1000"`
ExpireDiff int `json:"expireDiff" form:"expireDiff" validate:"gte=0"`
+8 -2
View File
@@ -504,6 +504,12 @@ func (g *GatewayClient) sendStatus(ctx context.Context) {
}
tr := translator(g.settingService)
sentTraffic := common.FormatTraffic(int64(status.NetTraffic.Sent))
receivedTraffic := common.FormatTraffic(int64(status.NetTraffic.Recv))
if !status.MetricAvailable("netTraffic") {
sentTraffic = tr("pages.settings.networkTrafficUnavailable")
receivedTraffic = sentTraffic
}
embed := Embed{
Title: tr("discord.commands.statusTitle"),
Description: tr("discord.commands.statusDescription", "Host=="+hostname),
@@ -517,8 +523,8 @@ func (g *GatewayClient) sendStatus(ctx context.Context) {
{Name: tr("pages.index.memory"), Value: fmt.Sprintf("%s / %s", common.FormatTraffic(int64(status.Mem.Current)), common.FormatTraffic(int64(status.Mem.Total))), Inline: true},
{Name: tr("pages.index.historyTitleOnline"), Value: strconv.Itoa(len(onlines)), Inline: true},
{Name: tr("pages.index.historyTabConnections"), Value: fmt.Sprintf("TCP: %d | UDP: %d", status.TcpCount, status.UdpCount), Inline: true},
{Name: tr("pages.index.sent"), Value: common.FormatTraffic(int64(status.NetTraffic.Sent)), Inline: true},
{Name: tr("pages.index.received"), Value: common.FormatTraffic(int64(status.NetTraffic.Recv)), Inline: true},
{Name: tr("pages.index.sent"), Value: sentTraffic, Inline: true},
{Name: tr("pages.index.received"), Value: receivedTraffic, Inline: true},
},
Footer: &EmbedFooter{Text: tr("discord.footer")},
}
@@ -24,6 +24,60 @@ type mockXrayRestart struct {
err error
}
func TestGatewayStatusDistinguishesUnavailableTrafficFromMeasuredZero(t *testing.T) {
settings := setupTestDB(t)
_ = settings.SetDiscordLang("en-US")
_ = settings.SetDiscordBotToken("network-status-test")
_ = settings.SetDiscordChannelId("local-test-channel")
sent := make(chan MessagePayload, 1)
rest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var payload MessagePayload
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
sent <- payload
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":"local-message"}`))
}))
t.Cleanup(rest.Close)
discord := NewDiscordService(settings)
discord.SetBaseURL(rest.URL)
discord.SetHTTPClient(rest.Client())
provider := &mockServerProvider{}
gateway := NewGatewayClient(discord, settings, provider, nil, nil)
for _, tc := range []struct {
name string
unavailable []string
want string
}{
{"unavailable", []string{"netTraffic"}, "The selected network interface is unavailable. Choose an available interface or another monitoring mode."},
{"measured zero", nil, "0.00B"},
} {
t.Run(tc.name, func(t *testing.T) {
provider.status = &service.Status{UnavailableMetrics: tc.unavailable}
gateway.sendStatus(context.Background())
select {
case payload := <-sent:
if len(payload.Embeds) != 1 {
t.Fatalf("status embeds=%d", len(payload.Embeds))
}
fields := make(map[string]string)
for _, field := range payload.Embeds[0].Fields {
fields[field.Name] = field.Value
}
for _, name := range []string{"Sent", "Received"} {
if fields[name] != tc.want {
t.Fatalf("%s=%q, want %q", name, fields[name], tc.want)
}
}
default:
t.Fatal("status message was not sent")
}
})
}
}
func (m *mockXrayRestart) RestartXray(force bool) error {
m.restarted = true
return m.err
+3
View File
@@ -110,6 +110,9 @@ func (s *DiscordService) BuildReport(ctx context.Context, server ServerProvider,
"Down=="+common.FormatTraffic(int64(status.NetTraffic.Recv)),
"Total=="+common.FormatTraffic(int64(status.NetTraffic.Sent+status.NetTraffic.Recv)),
)
if !status.MetricAvailable("netTraffic") {
trafficStr = tr("pages.settings.networkTrafficUnavailable")
}
load1, load2, load3 := 0.0, 0.0, 0.0
if len(status.Loads) > 0 {
load1 = status.Loads[0]
@@ -20,6 +20,26 @@ type mockServerProvider struct {
filename string
}
func TestReportNetworkUnavailableDoesNotReportZeroTraffic(t *testing.T) {
settings := setupTestDB(t)
_ = settings.SetDiscordLang("en-US")
_ = settings.SetDiscordBotBackup(false)
status := &service.Status{UnavailableMetrics: []string{"netTraffic"}, Loads: []float64{0, 0, 0}}
report, _, err := NewDiscordService(settings).BuildReport(context.Background(), &mockServerProvider{status: status}, nil)
if err != nil {
t.Fatal(err)
}
for _, field := range report.Embeds[0].Fields {
if field.Name == "Network Traffic" {
if field.Value != "The selected network interface is unavailable. Choose an available interface or another monitoring mode." {
t.Fatalf("traffic=%q", field.Value)
}
return
}
}
t.Fatal("traffic field missing")
}
func (m *mockServerProvider) GetStatus(lastStatus *service.Status) *service.Status {
return m.status
}
+136
View File
@@ -0,0 +1,136 @@
package service
import (
"errors"
"fmt"
"math"
stdnet "net"
"slices"
"strings"
"time"
"github.com/shirou/gopsutil/v4/net"
)
var errNetworkUnavailable = errors.New("network traffic interface is unavailable")
type (
networkTrafficConfig struct{ mode, iface string }
networkDefaultRoute struct {
iface string
family int
metric uint32
}
)
type networkTrafficSample struct {
source string
sent, recv, pktSent, pktRecv uint64
members map[string]net.IOCountersStat
}
func selectNetworkTraffic(config networkTrafficConfig, counters []net.IOCountersStat, interfaces []stdnet.Interface, automatic string) (networkTrafficSample, error) {
selected := config.iface
switch config.mode {
case "legacy":
case "auto":
selected = automatic
if selected == "" {
return networkTrafficSample{}, errNetworkUnavailable
}
case "manual":
if selected == "" {
return networkTrafficSample{}, errNetworkUnavailable
}
default:
return networkTrafficSample{}, fmt.Errorf("%w: invalid monitoring mode", errNetworkUnavailable)
}
byName := make(map[string]stdnet.Interface, len(interfaces))
for _, iface := range interfaces {
byName[iface.Name] = iface
}
if config.mode != "legacy" {
if _, ok := byName[selected]; !ok {
return networkTrafficSample{}, fmt.Errorf("%w: %s", errNetworkUnavailable, selected)
}
}
sample := networkTrafficSample{members: make(map[string]net.IOCountersStat)}
var identities []string
for _, counter := range counters {
if config.mode == "legacy" {
if isVirtualInterface(strings.ToLower(counter.Name)) {
continue
}
} else if counter.Name != selected {
continue
}
iface := byName[counter.Name]
identity := fmt.Sprintf("%q:%d:%s", counter.Name, iface.Index, iface.HardwareAddr)
if _, exists := sample.members[identity]; exists {
continue
}
sample.members[identity] = counter
identities = append(identities, identity)
if math.MaxUint64-sample.sent < counter.BytesSent || math.MaxUint64-sample.recv < counter.BytesRecv || math.MaxUint64-sample.pktSent < counter.PacketsSent || math.MaxUint64-sample.pktRecv < counter.PacketsRecv {
return networkTrafficSample{}, fmt.Errorf("%w: counter overflow", errNetworkUnavailable)
}
sample.sent += counter.BytesSent
sample.recv += counter.BytesRecv
sample.pktSent += counter.PacketsSent
sample.pktRecv += counter.PacketsRecv
}
if config.mode != "legacy" && len(sample.members) == 0 {
return networkTrafficSample{}, fmt.Errorf("%w: no counters for %s", errNetworkUnavailable, selected)
}
slices.Sort(identities)
sample.source = config.mode + ":" + strings.Join(identities, ";")
return sample, nil
}
func chooseNetworkDefaultRoute(routes []networkDefaultRoute, interfaces []stdnet.Interface) (string, error) {
up := make(map[string]bool, len(interfaces))
for _, iface := range interfaces {
up[iface.Name] = iface.Flags&stdnet.FlagUp != 0 && iface.Flags&stdnet.FlagLoopback == 0
}
candidates := slices.Clone(routes)
candidates = slices.DeleteFunc(candidates, func(r networkDefaultRoute) bool { return !up[r.iface] || (r.family != 4 && r.family != 6) })
slices.SortFunc(candidates, func(a, b networkDefaultRoute) int {
if a.family != b.family {
return a.family - b.family
}
if a.metric != b.metric {
if a.metric < b.metric {
return -1
}
return 1
}
return strings.Compare(a.iface, b.iface)
})
if len(candidates) == 0 {
return "", fmt.Errorf("%w: no usable default route", errNetworkUnavailable)
}
return candidates[0].iface, nil
}
func networkTrafficRates(previous, current *networkTrafficSample, elapsed time.Duration) [4]uint64 {
if previous == nil || current == nil || previous.source != current.source || elapsed <= 0 {
return [4]uint64{}
}
for identity, counter := range current.members {
before, exists := previous.members[identity]
if !exists || counter.BytesSent < before.BytesSent || counter.BytesRecv < before.BytesRecv || counter.PacketsSent < before.PacketsSent || counter.PacketsRecv < before.PacketsRecv {
return [4]uint64{}
}
}
seconds := elapsed.Seconds()
deltas := [4]uint64{current.sent - previous.sent, current.recv - previous.recv, current.pktSent - previous.pktSent, current.pktRecv - previous.pktRecv}
var rates [4]uint64
for i, delta := range deltas {
rate := float64(delta) / seconds
if rate >= float64(math.MaxUint64) {
return [4]uint64{}
}
rates[i] = uint64(rate)
}
return rates
}
@@ -0,0 +1,163 @@
package service
import (
"fmt"
stdnet "net"
"slices"
"strings"
"unicode"
"unicode/utf8"
"github.com/shirou/gopsutil/v4/net"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
)
type NetworkInterfaceOption struct {
Name string `json:"name" example:"eth0"`
Up bool `json:"up" example:"true"`
}
type NetworkInterfacesResponse struct {
Interfaces []NetworkInterfaceOption `json:"interfaces"`
Automatic string `json:"automatic" example:"eth0"`
AutomaticError string `json:"automaticError"`
}
type NetworkTrafficSelection struct {
Mode string `json:"mode" example:"manual"`
Name string `json:"name" example:"eth0"`
Available bool `json:"available" example:"true"`
Error string `json:"error"`
}
type networkTrafficReader struct {
interfaces func() ([]stdnet.Interface, error)
counters func() ([]net.IOCountersStat, error)
routes func([]stdnet.Interface) ([]networkDefaultRoute, error)
}
func (s *ServerService) trafficReader() networkTrafficReader {
if s.networkTrafficReader != nil {
return *s.networkTrafficReader
}
return networkTrafficReader{stdnet.Interfaces, func() ([]net.IOCountersStat, error) { return net.IOCounters(true) }, readNetworkDefaultRoutes}
}
func (s *SettingService) getNetworkTrafficConfig() (networkTrafficConfig, error) {
config := networkTrafficConfig{mode: defaultValueMap["networkTrafficMode"]}
var rows []model.Setting
if err := database.GetDB().Where("key IN ?", []string{"networkTrafficMode", "networkTrafficInterface"}).Find(&rows).Error; err != nil {
return config, err
}
for _, row := range rows {
switch row.Key {
case "networkTrafficMode":
if row.Value != "" {
config.mode = row.Value
}
case "networkTrafficInterface":
config.iface = row.Value
}
}
return config, nil
}
func validateNetworkTrafficSettings(settings *entity.AllSetting) error {
if settings.NetworkTrafficMode == "" {
if settings.NetworkTrafficInterface != "" {
return fmt.Errorf("network traffic mode is required when selecting an interface")
}
return nil
}
if !slices.Contains([]string{"legacy", "auto", "manual"}, settings.NetworkTrafficMode) {
return fmt.Errorf("network traffic mode must be legacy, auto, or manual")
}
name := settings.NetworkTrafficInterface
if name != "" && (utf8.RuneCountInString(name) > 255 || !utf8.ValidString(name) || strings.ContainsFunc(name, unicode.IsControl)) {
return fmt.Errorf("network traffic interface name is invalid")
}
if settings.NetworkTrafficMode == "manual" && name == "" {
return fmt.Errorf("network traffic interface is required in manual mode")
}
return nil
}
func validateNetworkTrafficInterfaceChange(settings *entity.AllSetting, previous networkTrafficConfig) error {
if settings.NetworkTrafficMode != "manual" || (previous.mode == "manual" && previous.iface == settings.NetworkTrafficInterface) {
return nil
}
if _, err := stdnet.InterfaceByName(settings.NetworkTrafficInterface); err != nil {
return fmt.Errorf("network traffic interface %q is unavailable: %w", settings.NetworkTrafficInterface, err)
}
return nil
}
func (s *ServerService) GetNetworkInterfaces() (*NetworkInterfacesResponse, error) {
reader := s.trafficReader()
interfaces, err := reader.interfaces()
if err != nil {
return nil, err
}
response := &NetworkInterfacesResponse{Interfaces: make([]NetworkInterfaceOption, 0, len(interfaces))}
for _, iface := range interfaces {
response.Interfaces = append(response.Interfaces, NetworkInterfaceOption{iface.Name, iface.Flags&stdnet.FlagUp != 0})
}
slices.SortFunc(response.Interfaces, func(a, b NetworkInterfaceOption) int { return strings.Compare(a.Name, b.Name) })
routes, err := reader.routes(interfaces)
if err == nil {
response.Automatic, err = chooseNetworkDefaultRoute(routes, interfaces)
}
if err != nil {
response.AutomaticError = err.Error()
}
return response, nil
}
func (s *ServerService) collectNetworkTraffic(status, previous *Status) {
config, err := s.settingService.getNetworkTrafficConfig()
selection := &NetworkTrafficSelection{Mode: config.mode}
status.NetworkInterface = selection
if config.mode == "manual" {
selection.Name = config.iface
}
reader := s.trafficReader()
var sample networkTrafficSample
if err == nil {
var interfaces []stdnet.Interface
interfaces, err = reader.interfaces()
if err == nil && config.mode == "auto" {
var routes []networkDefaultRoute
routes, err = reader.routes(interfaces)
if err == nil {
selection.Name, err = chooseNetworkDefaultRoute(routes, interfaces)
}
}
if err == nil {
var counters []net.IOCountersStat
counters, err = reader.counters()
if err == nil {
sample, err = selectNetworkTraffic(config, counters, interfaces, selection.Name)
}
}
}
if err != nil {
selection.Error = err.Error()
if previous == nil || previous.NetworkInterface == nil || previous.NetworkInterface.Error != selection.Error {
logger.Warning("network traffic statistics unavailable: ", err)
}
status.UnavailableMetrics = append(status.UnavailableMetrics, "netTraffic", "netUp", "netDown", "pktUp", "pktDown")
return
}
selection.Available = true
status.networkTrafficSample = &sample
status.NetTraffic.Sent, status.NetTraffic.Recv = sample.sent, sample.recv
status.NetTraffic.PktSent, status.NetTraffic.PktRecv = sample.pktSent, sample.pktRecv
if previous != nil {
rates := networkTrafficRates(previous.networkTrafficSample, &sample, status.T.Sub(previous.T))
status.NetIO.Up, status.NetIO.Down, status.NetIO.PktUp, status.NetIO.PktDown = rates[0], rates[1], rates[2], rates[3]
}
}
@@ -0,0 +1,57 @@
package service
import (
stdnet "net"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
func readNetworkDefaultRoutes(interfaces []stdnet.Interface) ([]networkDefaultRoute, error) {
routes, err := netlink.RouteListFiltered(netlink.FAMILY_ALL, &netlink.Route{Table: unix.RT_TABLE_MAIN}, netlink.RT_FILTER_TABLE)
if err != nil {
return nil, err
}
return networkRoutesFromNetlink(routes, interfaces), nil
}
func networkRoutesFromNetlink(routes []netlink.Route, interfaces []stdnet.Interface) []networkDefaultRoute {
names := make(map[int]string, len(interfaces))
for _, iface := range interfaces {
names[iface.Index] = iface.Name
}
var defaults []networkDefaultRoute
for _, route := range routes {
if route.Family != unix.AF_INET && route.Family != unix.AF_INET6 {
continue
}
if route.Table != unix.RT_TABLE_MAIN || route.Type != unix.RTN_UNICAST || route.Flags&unix.RTNH_F_LINKDOWN != 0 {
continue
}
if route.Dst != nil {
ones, bits := route.Dst.Mask.Size()
if ones != 0 || bits == 0 || !route.Dst.IP.IsUnspecified() {
continue
}
}
family := 4
if route.Family == unix.AF_INET6 {
family = 6
}
add := func(index, flags int) {
if flags&(unix.RTNH_F_DEAD|unix.RTNH_F_LINKDOWN) == 0 && names[index] != "" {
defaults = append(defaults, networkDefaultRoute{names[index], family, uint32(route.Priority)})
}
}
if len(route.MultiPath) == 0 {
add(route.LinkIndex, route.Flags)
} else {
for _, hop := range route.MultiPath {
if hop != nil {
add(hop.LinkIndex, hop.Flags)
}
}
}
}
return defaults
}
@@ -0,0 +1,42 @@
package service
import (
"net"
"reflect"
"testing"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
func TestNetworkDefaultRoutesExcludeNonDefaultsAndDeadNextHops(t *testing.T) {
_, subnet, _ := net.ParseCIDR("192.0.2.0/24")
_, ipv6Default, _ := net.ParseCIDR("::/0")
label := 100
routes := []netlink.Route{
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_MPLS, MPLSDst: &label, LinkIndex: 2},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, LinkIndex: 1, Priority: 20},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET6, Dst: ipv6Default, LinkIndex: 3, Priority: 10},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, Dst: subnet, LinkIndex: 2},
{Table: 100, Type: unix.RTN_UNICAST, Family: unix.AF_INET, LinkIndex: 2},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_BLACKHOLE, Family: unix.AF_INET, LinkIndex: 2},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, LinkIndex: 2, Flags: unix.RTNH_F_LINKDOWN},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, Priority: 30, MultiPath: []*netlink.NexthopInfo{{LinkIndex: 2, Flags: unix.RTNH_F_DEAD}, {LinkIndex: 3}}},
}
want := []networkDefaultRoute{{"eth0", 4, 20}, {"ens3", 6, 10}, {"ens3", 4, 30}}
if got := networkRoutesFromNetlink(routes, networkTestInterfaces()); !reflect.DeepEqual(got, want) {
t.Fatalf("defaults=%v, want %v", got, want)
}
}
func TestNetworkDefaultRoutePreservesUnsignedPriority(t *testing.T) {
// The netlink library's int holds a signed priority on 32-bit hosts.
routes := []netlink.Route{
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, LinkIndex: 1, Priority: -1},
{Table: unix.RT_TABLE_MAIN, Type: unix.RTN_UNICAST, Family: unix.AF_INET, LinkIndex: 3, Priority: 10},
}
got, err := chooseNetworkDefaultRoute(networkRoutesFromNetlink(routes, networkTestInterfaces()), networkTestInterfaces())
if err != nil || got != "ens3" {
t.Fatalf("default interface=%q, %v; want ens3", got, err)
}
}
@@ -0,0 +1,12 @@
//go:build !linux
package service
import (
"fmt"
"net"
)
func readNetworkDefaultRoutes(_ []net.Interface) ([]networkDefaultRoute, error) {
return nil, fmt.Errorf("automatic network traffic interface selection is supported on Linux; choose legacy or manual mode")
}
@@ -0,0 +1,265 @@
package service
import (
"errors"
"math"
stdnet "net"
"reflect"
"testing"
"time"
"github.com/shirou/gopsutil/v4/net"
)
func networkTestInterfaces() []stdnet.Interface {
return []stdnet.Interface{
{Index: 1, Name: "eth0", Flags: stdnet.FlagUp},
{Index: 2, Name: "enP6129s1", Flags: stdnet.FlagUp},
{Index: 3, Name: "ens3", Flags: stdnet.FlagUp},
{Index: 4, Name: "wg0", Flags: stdnet.FlagUp},
}
}
func TestNetworkLegacyRatesRebaseOnMemberResetAndMembershipChanges(t *testing.T) {
read := func(counters []net.IOCountersStat) *networkTrafficSample {
t.Helper()
sample, err := selectNetworkTraffic(networkTrafficConfig{mode: "legacy"}, counters, networkTestInterfaces(), "")
if err != nil {
t.Fatal(err)
}
return &sample
}
before := read([]net.IOCountersStat{{Name: "eth0", BytesSent: 100}, {Name: "ens3", BytesSent: 100}})
reset := read([]net.IOCountersStat{{Name: "ens3", BytesSent: 1000}, {Name: "eth0", BytesSent: 50}})
if got := networkTrafficRates(before, reset, time.Second); got != [4]uint64{} {
t.Fatalf("member reset hidden by aggregate increase: %v", got)
}
resumed := read([]net.IOCountersStat{{Name: "eth0", BytesSent: 150}, {Name: "ens3", BytesSent: 1100}})
if got := networkTrafficRates(reset, resumed, 2*time.Second); got != [4]uint64{100, 0, 0, 0} {
t.Fatalf("resumed rates=%v", got)
}
removed := read([]net.IOCountersStat{{Name: "eth0", BytesSent: 200}})
if got := networkTrafficRates(resumed, removed, time.Second); got != [4]uint64{} {
t.Fatalf("membership change rates=%v", got)
}
if _, err := selectNetworkTraffic(networkTrafficConfig{mode: "legacy"}, []net.IOCountersStat{{Name: "eth0", BytesSent: math.MaxUint64}, {Name: "ens3", BytesSent: 1}}, networkTestInterfaces(), ""); !errors.Is(err, errNetworkUnavailable) {
t.Fatalf("aggregate overflow=%v", err)
}
zero := read([]net.IOCountersStat{{Name: "eth0"}})
maximum := read([]net.IOCountersStat{{Name: "eth0", BytesSent: math.MaxUint64}})
if got := networkTrafficRates(zero, maximum, time.Nanosecond); got != [4]uint64{} {
t.Fatalf("unrepresentable rate=%v", got)
}
}
func TestNetworkTrafficCollectionRebasesAfterFailureAndRecovery(t *testing.T) {
setupSettingTestDB(t)
settings := &SettingService{}
iface := "eth0"
bytes := uint64(30 << 30)
failed := false
reader := &networkTrafficReader{
interfaces: func() ([]stdnet.Interface, error) { return networkTestInterfaces(), nil },
counters: func() ([]net.IOCountersStat, error) {
if failed {
return nil, errors.New("counter read failed")
}
return []net.IOCountersStat{{Name: iface, BytesSent: bytes, BytesRecv: bytes, PacketsSent: bytes / 10, PacketsRecv: bytes / 10}, {Name: "enP6129s1", BytesSent: bytes, BytesRecv: bytes}}, nil
},
routes: func([]stdnet.Interface) ([]networkDefaultRoute, error) {
if iface == "" {
return nil, errNetworkUnavailable
}
return []networkDefaultRoute{{iface, 4, 10}}, nil
},
}
svc := &ServerService{networkTrafficReader: reader, cachedCpuSpeedMhz: 1}
legacy := svc.GetStatus(nil)
if legacy.NetTraffic.Sent != 2*bytes || legacy.NetworkInterface.Mode != "legacy" {
t.Fatalf("legacy default: sent=%d selection=%+v", legacy.NetTraffic.Sent, legacy.NetworkInterface)
}
if err := settings.saveSetting("networkTrafficMode", "auto"); err != nil {
t.Fatal(err)
}
first := svc.GetStatus(legacy)
if first.NetTraffic.Sent != bytes || first.NetworkInterface == nil || first.NetworkInterface.Name != "eth0" || first.NetIO.Up != 0 {
t.Fatalf("central initial status: %+v", first)
}
previous := first
at := first.T
for _, tc := range []struct {
name, iface string
bytes uint64
failed, available bool
wantRate uint64
}{
{"increasing", "eth0", bytes + 400, false, true, 200},
{"route changes", "ens3", 100, false, true, 0},
{"new route resumes", "ens3", 500, false, true, 200},
{"no route", "", 0, false, false, 0},
{"route returns", "ens3", 900, false, true, 0},
{"counter read fails", "ens3", 900, true, false, 0},
{"counter read recovers", "ens3", 1300, false, true, 0},
{"resumes after recovery", "ens3", 1700, false, true, 200},
} {
t.Run(tc.name, func(t *testing.T) {
iface, bytes, failed = tc.iface, tc.bytes, tc.failed
at = at.Add(2 * time.Second)
current := &Status{T: at}
svc.collectNetworkTraffic(current, previous)
if current.NetworkInterface.Available != tc.available || current.NetIO.Up != tc.wantRate || current.MetricAvailable("netTraffic") != tc.available {
t.Fatalf("selection=%+v rates=%+v unavailable=%v", current.NetworkInterface, current.NetIO, current.UnavailableMetrics)
}
previous = current
})
}
if info, err := svc.GetNetworkInterfaces(); err != nil || info.Automatic != "ens3" || len(info.Interfaces) != 4 {
t.Fatalf("interface response=%+v, err=%v", info, err)
}
}
func TestNetworkUnavailableHistoryIsNotRecordedAsZero(t *testing.T) {
old := systemMetrics
systemMetrics = newMetricHistory()
t.Cleanup(func() { systemMetrics = old })
s := &ServerService{}
status := &Status{UnavailableMetrics: []string{"netUp", "netDown", "pktUp", "pktDown"}}
s.AppendStatusSample(time.Now(), status)
for _, metric := range []string{"netUp", "netDown", "pktUp", "pktDown"} {
if got := s.AggregateSystemMetric(metric, 2, 60); len(got) != 0 {
t.Fatalf("unavailable %s history=%v", metric, got)
}
}
status.UnavailableMetrics = nil
s.AppendStatusSample(time.Now(), status)
if got := s.AggregateSystemMetric("netUp", 2, 60); len(got) != 1 || got[0]["v"] != float64(0) {
t.Fatalf("valid zero history=%v", got)
}
}
func TestNetworkTrafficSelectionAvoidsStackedDoubleCounting(t *testing.T) {
const gb = uint64(1 << 30)
counters := []net.IOCountersStat{
{Name: "eth0", BytesSent: 30 * gb, BytesRecv: 12 * gb, PacketsSent: 100, PacketsRecv: 200},
{Name: "enP6129s1", BytesSent: 30 * gb, BytesRecv: 12 * gb, PacketsSent: 100, PacketsRecv: 200},
{Name: "ens3", BytesSent: gb, BytesRecv: 2 * gb},
{Name: "wg0", BytesSent: 3 * gb, BytesRecv: 4 * gb},
{Name: "lo", BytesSent: 9 * gb},
}
for _, tc := range []struct {
name, mode, selected string
wantSent, wantRecv uint64
wantPackets uint64
}{
{"legacy", "legacy", "", 61 * gb, 26 * gb, 200},
{"manual synthetic", "manual", "eth0", 30 * gb, 12 * gb, 100},
{"manual SR-IOV", "manual", "enP6129s1", 30 * gb, 12 * gb, 100},
{"manual unrelated", "manual", "ens3", gb, 2 * gb, 0},
{"manual tunnel", "manual", "wg0", 3 * gb, 4 * gb, 0},
{"automatic", "auto", "", 30 * gb, 12 * gb, 100},
} {
t.Run(tc.name, func(t *testing.T) {
sample, err := selectNetworkTraffic(networkTrafficConfig{tc.mode, tc.selected}, counters, networkTestInterfaces(), "eth0")
if err != nil {
t.Fatal(err)
}
if sample.sent != tc.wantSent || sample.recv != tc.wantRecv || sample.pktSent != tc.wantPackets {
t.Fatalf("sent=%d recv=%d packets=%d; want %d/%d/%d", sample.sent, sample.recv, sample.pktSent, tc.wantSent, tc.wantRecv, tc.wantPackets)
}
})
}
}
func TestNetworkTrafficMissingSelection(t *testing.T) {
for _, config := range []networkTrafficConfig{{"manual", "missing"}, {"auto", ""}, {"invalid", ""}} {
if _, err := selectNetworkTraffic(config, nil, nil, ""); !errors.Is(err, errNetworkUnavailable) {
t.Fatalf("config %+v: got %v, want unavailable", config, err)
}
}
got, err := selectNetworkTraffic(networkTrafficConfig{mode: "legacy"}, nil, nil, "")
if err != nil || got.sent != 0 || got.recv != 0 {
t.Fatalf("empty legacy: %+v, %v", got, err)
}
}
func TestNetworkDefaultRouteSelection(t *testing.T) {
for _, tc := range []struct {
name string
routes []networkDefaultRoute
want string
}{
{"IPv4 metric", []networkDefaultRoute{{"ens3", 4, 50}, {"eth0", 4, 10}}, "eth0"},
{"IPv6 only", []networkDefaultRoute{{"ens3", 6, 50}, {"eth0", 6, 100}}, "ens3"},
{"IPv4 preferred", []networkDefaultRoute{{"ens3", 6, 1}, {"eth0", 4, 500}}, "eth0"},
{"deterministic ties", []networkDefaultRoute{{"ens3", 4, 10}, {"eth0", 4, 10}}, "ens3"},
{"missing and down interfaces", []networkDefaultRoute{{"missing", 4, 0}, {"down", 4, 1}, {"eth0", 4, 20}}, "eth0"},
} {
t.Run(tc.name, func(t *testing.T) {
interfaces := append(networkTestInterfaces(), stdnet.Interface{Index: 5, Name: "down"})
got, err := chooseNetworkDefaultRoute(tc.routes, interfaces)
if err != nil || got != tc.want {
t.Fatalf("route interface = %q, %v; want %q", got, err, tc.want)
}
for i, j := 0, len(tc.routes)-1; i < j; i, j = i+1, j-1 {
tc.routes[i], tc.routes[j] = tc.routes[j], tc.routes[i]
}
got, err = chooseNetworkDefaultRoute(tc.routes, interfaces)
if err != nil || got != tc.want {
t.Fatalf("reversed route interface = %q, %v; want %q", got, err, tc.want)
}
})
}
if _, err := chooseNetworkDefaultRoute(nil, nil); !errors.Is(err, errNetworkUnavailable) {
t.Fatalf("empty routes: %v", err)
}
}
func TestNetworkRatesRebaseIncompatibleSamples(t *testing.T) {
interfaces := networkTestInterfaces()
makeSample := func(name string, sent, packets uint64) *networkTrafficSample {
t.Helper()
s, err := selectNetworkTraffic(networkTrafficConfig{"manual", name}, []net.IOCountersStat{{Name: name, BytesSent: sent, BytesRecv: sent, PacketsSent: packets, PacketsRecv: packets}}, interfaces, "")
if err != nil {
t.Fatal(err)
}
return &s
}
previous := makeSample("eth0", 1000, 100)
for _, tc := range []struct {
name string
previous, current *networkTrafficSample
elapsed time.Duration
want [4]uint64
}{
{"normal", previous, makeSample("eth0", 1400, 140), 2 * time.Second, [4]uint64{200, 200, 20, 20}},
{"startup", nil, previous, time.Second, [4]uint64{}},
{"switch to smaller", previous, makeSample("ens3", 50, 5), time.Second, [4]uint64{}},
{"switch to larger", previous, makeSample("ens3", 9000000, 500000), time.Second, [4]uint64{}},
{"counter reset", previous, makeSample("eth0", 50, 5), time.Second, [4]uint64{}},
{"packet reset", previous, makeSample("eth0", 1400, 1), time.Second, [4]uint64{}},
{"missing", previous, nil, time.Second, [4]uint64{}},
{"reappeared", nil, makeSample("eth0", 9000000, 500000), time.Second, [4]uint64{}},
{"zero time", previous, makeSample("eth0", 1400, 140), 0, [4]uint64{}},
{"backwards time", previous, makeSample("eth0", 1400, 140), -time.Second, [4]uint64{}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := networkTrafficRates(tc.previous, tc.current, tc.elapsed); got != tc.want {
t.Fatalf("rates = %v, want %v", got, tc.want)
}
})
}
interfaces[0].Index = 99
recreated := makeSample("eth0", 9000000, 500000)
if got := networkTrafficRates(previous, recreated, time.Second); got != [4]uint64{} {
t.Fatalf("recreated device rates: %v", got)
}
for _, mode := range []string{"legacy", "auto"} {
sample, err := selectNetworkTraffic(networkTrafficConfig{mode: mode}, []net.IOCountersStat{{Name: "eth0", BytesSent: 9000000}}, interfaces, "eth0")
if err != nil {
t.Fatal(err)
}
if got := networkTrafficRates(previous, &sample, time.Second); !reflect.DeepEqual(got, [4]uint64{}) {
t.Fatalf("mode switch %s: %v", mode, got)
}
}
}
+6 -2
View File
@@ -1019,8 +1019,12 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
}
nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
if !slices.Contains(p.UnavailableMetrics, "netUp") {
nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
}
if !slices.Contains(p.UnavailableMetrics, "netDown") {
nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
}
}
return nil
}
@@ -135,6 +135,33 @@ func TestProbeKeepsMetricAvailability(t *testing.T) {
}
}
func TestNodeHeartbeatSkipsUnavailableNetworkHistory(t *testing.T) {
body := `{"success":true,"obj":{"unavailableMetrics":["netUp","netDown"],"netIO":{"up":0,"down":0}}}`
svc, n, setBody := availabilityNodeFixture(t, body)
for _, available := range []bool{false, true} {
if available {
setBody(`{"success":true,"obj":{"netIO":{"up":0,"down":0}}}`)
}
patch, err := svc.Probe(context.Background(), n)
if err != nil {
t.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(n.Id, patch); err != nil {
t.Fatal(err)
}
for _, metric := range []string{"netUp", "netDown"} {
points := nodeMetrics.aggregate(nodeMetricKey(n.Id, metric), 2, 60)
if !available && len(points) != 0 {
t.Fatalf("unavailable %s history=%v", metric, points)
}
if available && (len(points) != 1 || points[0]["v"] != float64(0)) {
t.Fatalf("valid zero %s history=%v", metric, points)
}
}
}
}
func TestUpdateHeartbeatKeepsUnavailableCPUOutOfHistory(t *testing.T) {
svc, n, setBody := availabilityNodeFixture(t, unavailableStatusBody)
patch, err := svc.Probe(context.Background(), n)
+12 -44
View File
@@ -52,7 +52,6 @@ import (
"github.com/shirou/gopsutil/v4/host"
"github.com/shirou/gopsutil/v4/load"
"github.com/shirou/gopsutil/v4/mem"
"github.com/shirou/gopsutil/v4/net"
)
// ProcessState represents the current state of a system process.
@@ -68,8 +67,10 @@ const (
// Status represents comprehensive system and application status information.
// It includes CPU, memory, disk, network statistics, and Xray process status.
type Status struct {
ResourceScope string `json:"resourceScope,omitempty"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
NetworkInterface *NetworkTrafficSelection `json:"networkInterface,omitempty"`
networkTrafficSample *networkTrafficSample `json:"-"`
ResourceScope string `json:"resourceScope,omitempty"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
T time.Time `json:"-"`
Cpu float64 `json:"cpu"`
@@ -148,7 +149,8 @@ type Release struct {
// ServerService provides business logic for server monitoring and management.
// It handles system status collection, IP detection, and application statistics.
type ServerService struct {
lxcMetrics sys.LXCReader
networkTrafficReader *networkTrafficReader
lxcMetrics sys.LXCReader
xrayService XrayService
inboundService InboundService
@@ -766,42 +768,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
}
// Network stats
ioStats, err := net.IOCounters(true)
if err != nil {
logger.Warning("get io counters failed:", err)
} else {
var totalSent, totalRecv, totalPktSent, totalPktRecv uint64
for _, iface := range ioStats {
name := strings.ToLower(iface.Name)
if isVirtualInterface(name) {
continue
}
totalSent += iface.BytesSent
totalRecv += iface.BytesRecv
totalPktSent += iface.PacketsSent
totalPktRecv += iface.PacketsRecv
}
status.NetTraffic.Sent = totalSent
status.NetTraffic.Recv = totalRecv
status.NetTraffic.PktSent = totalPktSent
status.NetTraffic.PktRecv = totalPktRecv
if lastStatus != nil {
duration := now.Sub(lastStatus.T)
seconds := float64(duration) / float64(time.Second)
up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds)
down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds)
status.NetIO.Up = up
status.NetIO.Down = down
if seconds > 0 && status.NetTraffic.PktSent >= lastStatus.NetTraffic.PktSent {
status.NetIO.PktUp = uint64(float64(status.NetTraffic.PktSent-lastStatus.NetTraffic.PktSent) / seconds)
}
if seconds > 0 && status.NetTraffic.PktRecv >= lastStatus.NetTraffic.PktRecv {
status.NetIO.PktDown = uint64(float64(status.NetTraffic.PktRecv-lastStatus.NetTraffic.PktRecv) / seconds)
}
}
}
s.collectNetworkTraffic(status, lastStatus)
// TCP/UDP connections
status.TcpCount, err = sys.GetTCPCount()
@@ -889,15 +856,15 @@ func (s *ServerService) AppendStatusSample(t time.Time, status *Status) {
} else {
appendScopedMetric(status, "swap", t, 0)
}
systemMetrics.append("netUp", t, float64(status.NetIO.Up))
systemMetrics.append("netDown", t, float64(status.NetIO.Down))
appendScopedMetric(status, "netUp", t, float64(status.NetIO.Up))
appendScopedMetric(status, "netDown", t, float64(status.NetIO.Down))
systemMetrics.append("diskRead", t, float64(status.DiskIO.Read))
systemMetrics.append("diskWrite", t, float64(status.DiskIO.Write))
if status.Disk.Total > 0 {
systemMetrics.append("diskUsage", t, float64(status.Disk.Current)*100.0/float64(status.Disk.Total))
}
systemMetrics.append("pktUp", t, float64(status.NetIO.PktUp))
systemMetrics.append("pktDown", t, float64(status.NetIO.PktDown))
appendScopedMetric(status, "pktUp", t, float64(status.NetIO.PktUp))
appendScopedMetric(status, "pktDown", t, float64(status.NetIO.PktDown))
systemMetrics.append("tcpCount", t, float64(status.TcpCount))
systemMetrics.append("udpCount", t, float64(status.UdpCount))
online := 0
@@ -1855,6 +1822,7 @@ var hostBoundSettingKeys = []string{
"webListen", "webDomain", "webPort", "webCertFile", "webKeyFile", "webBasePath",
"subListen", "subDomain", "subPort", "subCertFile", "subKeyFile", "subURI", "subJsonURI",
"secret", "panelGuid",
"networkTrafficMode", "networkTrafficInterface",
"nodeMtlsCaCertPem", "nodeMtlsCaKeyPem", "nodeMtlsClientCertPem",
"nodeMtlsClientKeyPem", "nodeMtlsClientCertSha256", "nodeMtlsClientCAPem",
}
+1 -1
View File
@@ -51,7 +51,7 @@ func appendScopedMetric(status *Status, metric string, t time.Time, value float6
if !status.MetricAvailable(metric) {
return
}
if status.ResourceScope != "" {
if status.ResourceScope != "" && scopedMetric(metric) {
metric = containerHistoryPrefix + metric
}
systemMetrics.append(metric, t, value)
+30 -9
View File
@@ -53,15 +53,17 @@ const (
)
var defaultValueMap = map[string]string{
"xrayTemplateConfig": xrayTemplateConfig,
"webListen": "",
"webDomain": "",
"webPort": "2053",
"webCertFile": "",
"webKeyFile": "",
"secret": random.Seq(32),
"panelGuid": uuid.NewString(),
"apiToken": "",
"networkTrafficMode": "legacy",
"networkTrafficInterface": "",
"xrayTemplateConfig": xrayTemplateConfig,
"webListen": "",
"webDomain": "",
"webPort": "2053",
"webCertFile": "",
"webKeyFile": "",
"secret": random.Seq(32),
"panelGuid": uuid.NewString(),
"apiToken": "",
// Node mTLS material (opt-in). All default empty: the CA + master client
// cert are minted lazily on first use, and the node-side trust CA is pasted
// in by the operator. Kept out of entity.AllSetting so private keys never
@@ -1696,6 +1698,10 @@ type SecretClears struct {
}
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
preserveTrafficSelection := allSetting.NetworkTrafficMode == ""
if err := validateNetworkTrafficSettings(allSetting); err != nil {
return err
}
switch allSetting.SubHostSortMode {
case "":
allSetting.SubHostSortMode = "inbound-first"
@@ -1745,11 +1751,26 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
return err
}
byKey := make(map[string]*model.Setting, len(existing))
currentTraffic := networkTrafficConfig{}
for _, st := range existing {
byKey[st.Key] = st
switch st.Key {
case "networkTrafficMode":
currentTraffic.mode = st.Value
case "networkTrafficInterface":
currentTraffic.iface = st.Value
}
}
if err := validateNetworkTrafficInterfaceChange(allSetting, currentTraffic); err != nil {
return err
}
for _, field := range fields {
key := 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
}
fieldV := v.FieldByName(field.Name)
value := fmt.Sprint(fieldV.Interface())
if st, ok := byKey[key]; ok {
@@ -0,0 +1,195 @@
package service
import (
stdnet "net"
"path/filepath"
"strings"
"sync"
"testing"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestNetworkTrafficSettingsPersistAndRejectInvalidChanges(t *testing.T) {
path := filepath.Join(t.TempDir(), "x-ui.db")
dbtest.InitDB(t, path)
s := &SettingService{}
settings, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if settings.NetworkTrafficMode != "legacy" || settings.NetworkTrafficInterface != "" {
t.Fatalf("missing settings defaults: mode=%q interface=%q", settings.NetworkTrafficMode, settings.NetworkTrafficInterface)
}
interfaces, err := stdnet.Interfaces()
if err != nil {
t.Fatal(err)
}
if len(interfaces) == 0 {
t.Skip("no network interfaces available")
}
settings.NetworkTrafficMode, settings.NetworkTrafficInterface = "manual", interfaces[0].Name
if err := s.UpdateAllSetting(settings, SecretClears{}); err != nil {
t.Fatal(err)
}
if err := database.CloseDB(); err != nil {
t.Fatal(err)
}
if err := database.InitDB(path); err != nil {
t.Fatal(err)
}
got, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if got.NetworkTrafficMode != "manual" || got.NetworkTrafficInterface != interfaces[0].Name {
t.Fatalf("restarted settings: mode=%q interface=%q", got.NetworkTrafficMode, got.NetworkTrafficInterface)
}
legacyRequest := *got
legacyRequest.NetworkTrafficMode, legacyRequest.NetworkTrafficInterface = "", ""
legacyRequest.SubTitle = "Unrelated legacy API update"
if err := s.UpdateAllSetting(&legacyRequest, SecretClears{}); err != nil {
t.Fatal(err)
}
legacyReload, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if legacyReload.NetworkTrafficMode != "manual" || legacyReload.NetworkTrafficInterface != interfaces[0].Name || legacyReload.SubTitle != "Unrelated legacy API update" {
t.Fatalf("older API update changed traffic selection: mode=%q interface=%q title=%q", legacyReload.NetworkTrafficMode, legacyReload.NetworkTrafficInterface, legacyReload.SubTitle)
}
for _, tc := range []struct{ mode, iface, message string }{
{"", interfaces[0].Name, "network traffic mode"},
{"other", interfaces[0].Name, "network traffic mode"},
{"manual", "", "network traffic interface"},
{"manual", "does-not-exist-6906", "network traffic interface"},
{"manual", "eth0\n", "network traffic interface"},
{"manual", "../eth0", "network traffic interface"},
} {
got.NetworkTrafficMode, got.NetworkTrafficInterface = tc.mode, tc.iface
if err := s.UpdateAllSetting(got, SecretClears{}); err == nil || !strings.Contains(err.Error(), tc.message) {
t.Fatalf("invalid settings %+v: %v", tc, err)
}
}
reloaded, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if reloaded.NetworkTrafficMode != "manual" || reloaded.NetworkTrafficInterface != interfaces[0].Name || reloaded.SubTitle != "Unrelated legacy API update" {
t.Fatalf("invalid update changed persisted selection: mode=%q interface=%q title=%q", reloaded.NetworkTrafficMode, reloaded.NetworkTrafficInterface, reloaded.SubTitle)
}
for _, mode := range []string{"auto", "legacy", ""} {
reloaded.NetworkTrafficMode = mode
if mode == "" {
reloaded.NetworkTrafficInterface = ""
}
if err := s.UpdateAllSetting(reloaded, SecretClears{}); err != nil {
t.Fatal(err)
}
saved, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
want := mode
if want == "" {
want = "legacy"
}
if saved.NetworkTrafficMode != want {
t.Fatalf("saved %q mode=%q", mode, saved.NetworkTrafficMode)
}
}
}
func TestOmittedNetworkSettingsPreserveConcurrentSelection(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
settings, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
interfaces, err := stdnet.Interfaces()
if err != nil {
t.Fatal(err)
}
if len(interfaces) == 0 {
t.Skip("no network interfaces available")
}
settings.NetworkTrafficMode, settings.NetworkTrafficInterface = "manual", interfaces[0].Name
if err := s.UpdateAllSetting(settings, SecretClears{}); err != nil {
t.Fatal(err)
}
settings.NetworkTrafficMode, settings.NetworkTrafficInterface = "", ""
settings.SubTitle = "Other settings updated"
db := database.GetDB()
var change sync.Once
const callback = "test:concurrent_traffic_selection"
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
if tx.Statement.Table != "settings" {
return
}
change.Do(func() {
if err := db.Transaction(func(write *gorm.DB) error {
if err := write.Model(&model.Setting{}).Where("key = ?", "networkTrafficMode").Update("value", "auto").Error; err != nil {
return err
}
return write.Model(&model.Setting{}).Where("key = ?", "networkTrafficInterface").Update("value", "").Error
}); err != nil {
t.Errorf("concurrent update: %v", err)
}
})
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
if err := s.UpdateAllSetting(settings, SecretClears{}); err != nil {
t.Fatal(err)
}
reloaded, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if reloaded.NetworkTrafficMode != "auto" || reloaded.NetworkTrafficInterface != "" || reloaded.SubTitle != "Other settings updated" {
t.Fatalf("concurrent selection lost: mode=%q interface=%q title=%q", reloaded.NetworkTrafficMode, reloaded.NetworkTrafficInterface, reloaded.SubTitle)
}
}
func TestUnchangedMissingTrafficInterfaceDoesNotBlockOtherSettings(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
for key, value := range map[string]string{"networkTrafficMode": "manual", "networkTrafficInterface": "removed-6906"} {
if err := s.saveSetting(key, value); err != nil {
t.Fatal(err)
}
}
settings, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
settings.SubTitle = "Unrelated settings remain editable"
if err := s.UpdateAllSetting(settings, SecretClears{}); err != nil {
t.Fatalf("unchanged missing interface blocked unrelated update: %v", err)
}
reloaded, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if reloaded.NetworkTrafficMode != "manual" || reloaded.NetworkTrafficInterface != "removed-6906" || reloaded.SubTitle != settings.SubTitle {
t.Fatalf("saved settings: mode=%q interface=%q title=%q", reloaded.NetworkTrafficMode, reloaded.NetworkTrafficInterface, reloaded.SubTitle)
}
reloaded.NetworkTrafficInterface = "another-missing-6906"
reloaded.SubTitle = "Invalid selection must not be saved"
if err := s.UpdateAllSetting(reloaded, SecretClears{}); err == nil || !strings.Contains(err.Error(), "unavailable") {
t.Fatalf("changed missing interface accepted: %v", err)
}
persisted, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if persisted.NetworkTrafficInterface != "removed-6906" || persisted.SubTitle != settings.SubTitle {
t.Fatalf("invalid selection changed settings: interface=%q title=%q", persisted.NetworkTrafficInterface, persisted.SubTitle)
}
}
+5 -1
View File
@@ -199,7 +199,11 @@ func (t *Tgbot) prepareServerUsageInfo() string {
info += t.I18nBot("tgbot.messages.onlinesCount", "Count=="+fmt.Sprint(len(onlines)))
info += t.I18nBot("tgbot.messages.tcpCount", "Count=="+strconv.Itoa(t.lastStatus.TcpCount))
info += t.I18nBot("tgbot.messages.udpCount", "Count=="+strconv.Itoa(t.lastStatus.UdpCount))
info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), "Upload=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), "Download=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
if t.lastStatus.MetricAvailable("netTraffic") {
info += t.I18nBot("tgbot.messages.traffic", "Total=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent+t.lastStatus.NetTraffic.Recv)), "Upload=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Sent)), "Download=="+common.FormatTraffic(int64(t.lastStatus.NetTraffic.Recv)))
} else {
info += t.I18nBot("pages.settings.networkTrafficUnavailable") + "\r\n"
}
info += t.I18nBot("tgbot.messages.xrayStatus", "State=="+fmt.Sprint(t.lastStatus.Xray.State))
// Cache the complete server stats
@@ -13,10 +13,13 @@ import (
"github.com/mymmrac/telego"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
"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"
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
@@ -193,3 +196,46 @@ func TestClientInfoEscapesNodeValues(t *testing.T) {
}
}
}
func TestServerUsageInfoShowsUnavailableMetrics(t *testing.T) {
bundle := i18n.NewBundle(language.English)
_ = bundle.AddMessages(language.English, &i18n.Message{ID: "tgbot.messages.serverUpTime", Other: "Uptime: {{.UpTime}} {{.Unit}}\n"}, &i18n.Message{ID: "tgbot.days", Other: "days"})
_ = bundle.AddMessages(language.English, &i18n.Message{ID: "tgbot.messages.traffic", Other: "Traffic: {{.Total}}\n"}, &i18n.Message{ID: "pages.settings.networkTrafficUnavailable", Other: "NETWORK UNAVAILABLE"})
oldLocale := locale.SwapBotLocalizer(i18n.NewLocalizer(bundle, "en"))
t.Cleanup(func() { locale.SwapBotLocalizer(oldLocale) })
statusCache.mutex.Lock()
oldStatus, oldTime := statusCache.data, statusCache.timestamp
statusCache.mutex.Unlock()
serverStatsCache.mutex.Lock()
oldStats, oldStatsTime := serverStatsCache.data, serverStatsCache.timestamp
serverStatsCache.mutex.Unlock()
t.Cleanup(func() {
statusCache.mutex.Lock()
statusCache.data, statusCache.timestamp = oldStatus, oldTime
statusCache.mutex.Unlock()
serverStatsCache.mutex.Lock()
serverStatsCache.data, serverStatsCache.timestamp = oldStats, oldStatsTime
serverStatsCache.mutex.Unlock()
})
for _, tc := range []struct{ name, metric, want string }{
{"unavailable uptime", "uptime", "Uptime: —"},
{"valid uptime zero", "", "Uptime: 0 days"},
{"unavailable traffic", "netTraffic", "NETWORK UNAVAILABLE"},
{"valid traffic zero", "", "Traffic: 0.00B"},
} {
t.Run(tc.name, func(t *testing.T) {
bot := &Tgbot{}
status := &service.Status{Loads: []float64{0, 0, 0}}
if tc.metric != "" {
status.UnavailableMetrics = []string{tc.metric}
}
bot.setCachedStatus(status)
bot.setCachedServerStats("")
info := bot.prepareServerUsageInfo()
want := tc.want
if !strings.Contains(info, want) {
t.Fatalf("report did not contain %q: %s", want, info)
}
})
}
}
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "الاحتفاظ بإعدادات هذا الجهاز",
"importKeepHostSettingsDesc": "يحتفظ بعناوين الاستماع والمنافذ والمسار الأساسي والشهادات وهوية العقدة الخاصة بهذه اللوحة بدلًا من أخذها من الملف المرفوع.",
"importKeepHostSettingsDesc": "يحتفظ بعناوين الاستماع والمنافذ والمسار الأساسي والشهادات وهوية العقدة الخاصة بهذه اللوحة بدلًا من أخذها من الملف المرفوع. يُحفظ أيضًا اختيار واجهة مراقبة حركة الشبكة.",
"logLines": "عدد الأسطر",
"timeRange": "النطاق الزمني"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "مسار الاشتراك الافتراضي \"/sub/\" معروف — قم بتغييره.",
"warnDefaultJsonPath": "مسار اشتراك JSON الافتراضي \"/json/\" معروف — قم بتغييره.",
"TGBotSettings": "بوت تيليجرام",
"networkTrafficInterfaceTitle": "واجهة حركة مرور الشبكة",
"networkTrafficMode": "وضع مراقبة حركة الشبكة",
"networkTrafficDescription": "اختر الواجهة المستخدمة لإجمالي حركة النظام وسرعته. قد يحسب التجميع القديم حركة الواجهات المتراكبة مرتين. في Docker تتوفر فقط واجهات مساحة أسماء شبكة الحاوية.",
"networkTrafficLegacy": "كل الواجهات (قديم)",
"networkTrafficAutomatic": "تلقائي",
"networkTrafficManual": "يدوي",
"networkTrafficUnavailable": "واجهة الشبكة المحددة غير متاحة. اختر واجهة متاحة أو وضع مراقبة آخر.",
"networkTrafficAutoResolved": "واجهة المسار الافتراضي: {interface}",
"networkTrafficLoadError": "تعذر تحميل واجهات الشبكة.",
"networkTrafficEmpty": "لا تتوفر واجهات شبكة.",
"networkTrafficAutoUnavailable": "لا تتوفر واجهة للمسار الافتراضي. تبقى إحصاءات الحركة غير متاحة حتى استعادة الاكتشاف أو تغيير الوضع.",
"panelListeningIP": "IP الاستماع",
"panelListeningIPDesc": "عنوان IP للبانل. (سيبه فاضي عشان يستمع على كل الـ IPs)",
"panelListeningDomain": "دومين الاستماع",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Keep this machine's settings",
"importKeepHostSettingsDesc": "Keeps this panel's listen addresses, ports, base path, certificates and node identity instead of taking them from the uploaded file.",
"importKeepHostSettingsDesc": "Keeps this panel's listen addresses, ports, base path, certificates and node identity instead of taking them from the uploaded file. Network traffic interface selection is also preserved.",
"logLines": "Number of lines",
"timeRange": "Time range"
},
@@ -1383,6 +1383,17 @@
"warnDefaultSubPath": "Default subscription path \"/sub/\" is well-known — change it.",
"warnDefaultJsonPath": "Default JSON subscription path \"/json/\" is well-known — change it.",
"TGBotSettings": "Telegram Bot",
"networkTrafficInterfaceTitle": "Network Traffic Interface",
"networkTrafficMode": "Network traffic mode",
"networkTrafficDescription": "Select the interface used for system traffic totals and speed. Legacy aggregation can double-count stacked interfaces. In Docker, only interfaces in the container network namespace are available.",
"networkTrafficLegacy": "All interfaces (Legacy)",
"networkTrafficAutomatic": "Automatic",
"networkTrafficManual": "Manual",
"networkTrafficUnavailable": "The selected network interface is unavailable. Choose an available interface or another monitoring mode.",
"networkTrafficAutoResolved": "Default-route interface: {interface}",
"networkTrafficLoadError": "Could not load network interfaces.",
"networkTrafficEmpty": "No network interfaces are available.",
"networkTrafficAutoUnavailable": "No default-route interface is available. Traffic metrics remain unavailable until detection recovers or the mode changes.",
"panelListeningIP": "Listen IP",
"panelListeningIPDesc": "The IP address for the web panel. (leave blank to listen on all IPs)",
"panelListeningDomain": "Listen Domain",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Mantener la configuración de esta máquina",
"importKeepHostSettingsDesc": "Conserva las direcciones de escucha, los puertos, la ruta base, los certificados y la identidad de nodo de este panel en lugar de tomarlos del archivo subido.",
"importKeepHostSettingsDesc": "Conserva las direcciones de escucha, los puertos, la ruta base, los certificados y la identidad de nodo de este panel en lugar de tomarlos del archivo subido. También se conserva la selección de interfaz de tráfico de red.",
"logLines": "Número de líneas",
"timeRange": "Rango de tiempo"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "La ruta de suscripción por defecto \"/sub/\" es conocida — cámbiela.",
"warnDefaultJsonPath": "La ruta de suscripción JSON por defecto \"/json/\" es conocida — cámbiela.",
"TGBotSettings": "Bot de Telegram",
"networkTrafficInterfaceTitle": "Interfaz de tráfico de red",
"networkTrafficMode": "Modo de tráfico de red",
"networkTrafficDescription": "Seleccione la interfaz para los totales y la velocidad del tráfico del sistema. La agregación antigua puede contar dos veces el tráfico de interfaces superpuestas. En Docker solo están disponibles las interfaces del espacio de nombres de red del contenedor.",
"networkTrafficLegacy": "Todas las interfaces (heredado)",
"networkTrafficAutomatic": "Automático",
"networkTrafficManual": "Manual",
"networkTrafficUnavailable": "La interfaz de red seleccionada no está disponible. Elija una interfaz disponible u otro modo de monitorización.",
"networkTrafficAutoResolved": "Interfaz de la ruta predeterminada: {interface}",
"networkTrafficLoadError": "No se pudieron cargar las interfaces de red.",
"networkTrafficEmpty": "No hay interfaces de red disponibles.",
"networkTrafficAutoUnavailable": "No hay una interfaz de ruta predeterminada disponible. Las métricas de tráfico no estarán disponibles hasta que se recupere la detección o se cambie el modo.",
"panelListeningIP": "IP de Escucha del Panel",
"panelListeningIPDesc": "Dejar en blanco por defecto para monitorear todas las IPs.",
"panelListeningDomain": "Dominio de Escucha del Panel",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "حفظ تنظیمات این دستگاه",
"importKeepHostSettingsDesc": "آدرس‌ها و پورت‌های شنود، مسیر پایه، گواهی‌ها و هویت نودِ همین پنل را نگه می‌دارد و آن‌ها را از فایل بارگذاری‌شده نمی‌گیرد.",
"importKeepHostSettingsDesc": "آدرس‌ها و پورت‌های شنود، مسیر پایه، گواهی‌ها و هویت نودِ همین پنل را نگه می‌دارد و آن‌ها را از فایل بارگذاری‌شده نمی‌گیرد. انتخاب اینترفیس پایش ترافیک شبکه نیز حفظ می‌شود.",
"logLines": "تعداد خطوط",
"timeRange": "بازه زمانی"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "مسیر ساب پیش‌فرض «/sub/» شناخته‌شده است — تغییرش دهید.",
"warnDefaultJsonPath": "مسیر JSON ساب پیش‌فرض «/json/» شناخته‌شده است — تغییرش دهید.",
"TGBotSettings": "ربات تلگرام",
"networkTrafficInterfaceTitle": "اینترفیس ترافیک شبکه",
"networkTrafficMode": "حالت پایش ترافیک شبکه",
"networkTrafficDescription": "اینترفیس محاسبهٔ مجموع ترافیک و سرعت سیستم را انتخاب کنید. حالت تجمیعی قدیمی ممکن است ترافیک اینترفیس‌های لایه‌ای را دوباره بشمارد. در Docker فقط اینترفیس‌های فضای نام شبکهٔ کانتینر در دسترس‌اند.",
"networkTrafficLegacy": "همهٔ اینترفیس‌ها (قدیمی)",
"networkTrafficAutomatic": "خودکار",
"networkTrafficManual": "دستی",
"networkTrafficUnavailable": "اینترفیس شبکهٔ انتخاب‌شده در دسترس نیست. یک اینترفیس موجود یا حالت پایش دیگری انتخاب کنید.",
"networkTrafficAutoResolved": "اینترفیس مسیر پیش‌فرض: {interface}",
"networkTrafficLoadError": "دریافت فهرست اینترفیس‌های شبکه ناموفق بود.",
"networkTrafficEmpty": "هیچ اینترفیس شبکه‌ای در دسترس نیست.",
"networkTrafficAutoUnavailable": "اینترفیس مسیر پیش‌فرض در دسترس نیست. آمار ترافیک تا بازیابی تشخیص خودکار یا تغییر حالت در دسترس نخواهد بود.",
"panelListeningIP": "آدرس آی‌پی",
"panelListeningIPDesc": "آدرس آی‌پی برای وب پنل. برای گوش‌دادن به‌تمام آی‌پی‌ها خالی‌بگذارید",
"panelListeningDomain": "نام دامنه",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Pertahankan pengaturan mesin ini",
"importKeepHostSettingsDesc": "Mempertahankan alamat dengar, port, path dasar, sertifikat, dan identitas node panel ini alih-alih mengambilnya dari berkas yang diunggah.",
"importKeepHostSettingsDesc": "Mempertahankan alamat dengar, port, path dasar, sertifikat, dan identitas node panel ini alih-alih mengambilnya dari berkas yang diunggah. Pilihan antarmuka lalu lintas jaringan juga dipertahankan.",
"logLines": "Jumlah baris",
"timeRange": "Rentang waktu"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "Path langganan default \"/sub/\" sudah umum diketahui — ubahlah.",
"warnDefaultJsonPath": "Path langganan JSON default \"/json/\" sudah umum diketahui — ubahlah.",
"TGBotSettings": "Bot Telegram",
"networkTrafficInterfaceTitle": "Antarmuka lalu lintas jaringan",
"networkTrafficMode": "Mode lalu lintas jaringan",
"networkTrafficDescription": "Pilih antarmuka untuk total dan kecepatan lalu lintas sistem. Agregasi lama dapat menghitung lalu lintas antarmuka bertumpuk dua kali. Di Docker, hanya antarmuka dalam namespace jaringan kontainer yang tersedia.",
"networkTrafficLegacy": "Semua antarmuka (Lama)",
"networkTrafficAutomatic": "Otomatis",
"networkTrafficManual": "Manual",
"networkTrafficUnavailable": "Antarmuka jaringan yang dipilih tidak tersedia. Pilih antarmuka yang tersedia atau mode pemantauan lain.",
"networkTrafficAutoResolved": "Antarmuka rute default: {interface}",
"networkTrafficLoadError": "Tidak dapat memuat antarmuka jaringan.",
"networkTrafficEmpty": "Tidak ada antarmuka jaringan yang tersedia.",
"networkTrafficAutoUnavailable": "Antarmuka rute default tidak tersedia. Metrik lalu lintas tidak tersedia hingga deteksi pulih atau mode diubah.",
"panelListeningIP": "IP Pendengar",
"panelListeningIPDesc": "Alamat IP untuk panel web. (biarkan kosong untuk mendengarkan semua IP)",
"panelListeningDomain": "Domain Pendengar",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "このマシンの設定を保持する",
"importKeepHostSettingsDesc": "アップロードしたファイルの値ではなく、このパネルのリッスンアドレス、ポート、ベースパス、証明書、ノード ID を保持します。",
"importKeepHostSettingsDesc": "アップロードしたファイルの値ではなく、このパネルのリッスンアドレス、ポート、ベースパス、証明書、ノード ID を保持します。 ネットワークトラフィックのインターフェース選択も保持されます。",
"logLines": "行数",
"timeRange": "期間"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "デフォルトのサブスクリプションパス \"/sub/\" はよく知られています — 変更してください。",
"warnDefaultJsonPath": "デフォルトの JSON サブスクリプションパス \"/json/\" はよく知られています — 変更してください。",
"TGBotSettings": "Telegram Bot",
"networkTrafficInterfaceTitle": "ネットワークトラフィックのインターフェース",
"networkTrafficMode": "ネットワークトラフィックの監視モード",
"networkTrafficDescription": "システムの通信量と速度を集計するインターフェースを選択します。従来の集計では階層化されたインターフェースの通信を二重に数える場合があります。Docker ではコンテナーのネットワーク名前空間内のインターフェースのみ利用できます。",
"networkTrafficLegacy": "すべてのインターフェース(従来)",
"networkTrafficAutomatic": "自動",
"networkTrafficManual": "手動",
"networkTrafficUnavailable": "選択したネットワークインターフェースは利用できません。利用可能なインターフェースまたは別の監視モードを選択してください。",
"networkTrafficAutoResolved": "デフォルトルートのインターフェース: {interface}",
"networkTrafficLoadError": "ネットワークインターフェースを読み込めませんでした。",
"networkTrafficEmpty": "利用可能なネットワークインターフェースがありません。",
"networkTrafficAutoUnavailable": "デフォルトルートのインターフェースがありません。検出が復旧するかモードを変更するまで、トラフィック指標は利用できません。",
"panelListeningIP": "パネル監視IP",
"panelListeningIPDesc": "デフォルトではすべてのIPを監視する",
"panelListeningDomain": "パネル監視ドメイン",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Manter as configurações desta máquina",
"importKeepHostSettingsDesc": "Mantém os endereços de escuta, as portas, o caminho base, os certificados e a identidade de nó deste painel em vez de obtê-los do arquivo enviado.",
"importKeepHostSettingsDesc": "Mantém os endereços de escuta, as portas, o caminho base, os certificados e a identidade de nó deste painel em vez de obtê-los do arquivo enviado. A seleção da interface de tráfego de rede também é preservada.",
"logLines": "Número de linhas",
"timeRange": "Intervalo de tempo"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "O caminho de assinatura padrão \"/sub/\" é bem conhecido — altere-o.",
"warnDefaultJsonPath": "O caminho de assinatura JSON padrão \"/json/\" é bem conhecido — altere-o.",
"TGBotSettings": "Bot do Telegram",
"networkTrafficInterfaceTitle": "Interface de tráfego de rede",
"networkTrafficMode": "Modo de tráfego de rede",
"networkTrafficDescription": "Selecione a interface usada nos totais e na velocidade do tráfego do sistema. A agregação antiga pode contar duas vezes o tráfego de interfaces sobrepostas. No Docker, apenas interfaces do namespace de rede do contêiner estão disponíveis.",
"networkTrafficLegacy": "Todas as interfaces (Legado)",
"networkTrafficAutomatic": "Automático",
"networkTrafficManual": "Manual",
"networkTrafficUnavailable": "A interface de rede selecionada está indisponível. Escolha uma interface disponível ou outro modo de monitoramento.",
"networkTrafficAutoResolved": "Interface da rota padrão: {interface}",
"networkTrafficLoadError": "Não foi possível carregar as interfaces de rede.",
"networkTrafficEmpty": "Nenhuma interface de rede disponível.",
"networkTrafficAutoUnavailable": "Nenhuma interface de rota padrão disponível. As métricas de tráfego ficam indisponíveis até a recuperação da detecção ou a mudança do modo.",
"panelListeningIP": "IP de Escuta",
"panelListeningIPDesc": "O endereço IP para o painel web. (deixe em branco para escutar em todos os IPs)",
"panelListeningDomain": "Domínio de Escuta",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "ЗАБЛОКИРОВАНО",
"accessProxy": "ЧЕРЕЗ ПРОКСИ",
"importKeepHostSettings": "Сохранить настройки этой машины",
"importKeepHostSettingsDesc": "Оставляет адреса и порты этой панели, базовый путь, сертификаты и удостоверение для узлов вместо тех, что в загруженном файле.",
"importKeepHostSettingsDesc": "Оставляет адреса и порты этой панели, базовый путь, сертификаты и удостоверение для узлов вместо тех, что в загруженном файле. Выбор интерфейса сетевого трафика также сохраняется.",
"logLines": "Количество строк",
"timeRange": "Временной диапазон"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "Путь подписки по умолчанию \"/sub/\" широко известен — измените его.",
"warnDefaultJsonPath": "JSON-путь подписки по умолчанию \"/json/\" широко известен — измените его.",
"TGBotSettings": "Telegram-бот",
"networkTrafficInterfaceTitle": "Интерфейс для статистики трафика",
"networkTrafficMode": "Режим учёта сетевого трафика",
"networkTrafficDescription": "Выберите интерфейс для суммарного трафика и скорости системы. Старый режим может учитывать один трафик несколько раз на связанных интерфейсах. В Docker доступны только интерфейсы сетевого пространства имён контейнера.",
"networkTrafficLegacy": "Все интерфейсы (старый режим)",
"networkTrafficAutomatic": "Автоматически",
"networkTrafficManual": "Вручную",
"networkTrafficUnavailable": "Выбранный сетевой интерфейс недоступен. Выберите доступный интерфейс или другой режим мониторинга.",
"networkTrafficAutoResolved": "Интерфейс маршрута по умолчанию: {interface}",
"networkTrafficLoadError": "Не удалось загрузить сетевые интерфейсы.",
"networkTrafficEmpty": "Нет доступных сетевых интерфейсов.",
"networkTrafficAutoUnavailable": "Интерфейс маршрута по умолчанию недоступен. Статистика трафика будет недоступна до восстановления обнаружения или изменения режима.",
"panelListeningIP": "IP-адрес для управления панелью",
"panelListeningIPDesc": "Оставьте пустым для подключения с любого IP",
"panelListeningDomain": "Домен панели",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOKOVANÉ",
"accessProxy": "PROXY",
"importKeepHostSettings": "Ponechať nastavenia tohto servera",
"importKeepHostSettingsDesc": "Ponechajú sa adresy počúvania, porty, základná cesta, certifikáty a identita tohto servera namiesto nastavení z nahraného súboru.",
"importKeepHostSettingsDesc": "Ponechajú sa adresy počúvania, porty, základná cesta, certifikáty a identita tohto servera namiesto nastavení z nahraného súboru. Zachová sa aj výber rozhrania sieťovej prevádzky.",
"logLines": "Počet riadkov",
"timeRange": "Časový rozsah"
},
@@ -1383,6 +1383,17 @@
"warnDefaultSubPath": "Predvolená cesta odberu „/sub/“ je všeobecne známa. Zmeňte ju.",
"warnDefaultJsonPath": "Predvolená cesta odberu JSON „/json/“ je všeobecne známa. Zmeňte ju.",
"TGBotSettings": "Telegram bot",
"networkTrafficInterfaceTitle": "Rozhranie sieťovej prevádzky",
"networkTrafficMode": "Režim sieťovej prevádzky",
"networkTrafficDescription": "Vyberte rozhranie pre celkovú prevádzku a rýchlosť systému. Pôvodné sčítanie môže započítať prevádzku vrstvených rozhraní dvakrát. V Dockeri sú dostupné iba rozhrania v sieťovom mennom priestore kontajnera.",
"networkTrafficLegacy": "Všetky rozhrania (pôvodné)",
"networkTrafficAutomatic": "Automaticky",
"networkTrafficManual": "Manuálne",
"networkTrafficUnavailable": "Vybrané sieťové rozhranie nie je dostupné. Vyberte dostupné rozhranie alebo iný režim monitorovania.",
"networkTrafficAutoResolved": "Rozhranie predvolenej trasy: {interface}",
"networkTrafficLoadError": "Sieťové rozhrania sa nepodarilo načítať.",
"networkTrafficEmpty": "Nie sú dostupné žiadne sieťové rozhrania.",
"networkTrafficAutoUnavailable": "Rozhranie predvolenej trasy nie je dostupné. Údaje o prevádzke zostanú nedostupné, kým sa detekcia neobnoví alebo nezmeníte režim.",
"panelListeningIP": "IP adresa na počúvanie",
"panelListeningIPDesc": "IP adresa webového panelu. Prázdne pole znamená počúvanie na všetkých IP adresách.",
"panelListeningDomain": "Doména panelu",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Bu makinenin ayarlarını koru",
"importKeepHostSettingsDesc": "Yüklenen dosyadan almak yerine bu panelin dinleme adreslerini, portlarını, temel yolunu, sertifikalarını ve düğüm kimliğini korur.",
"importKeepHostSettingsDesc": "Yüklenen dosyadan almak yerine bu panelin dinleme adreslerini, portlarını, temel yolunu, sertifikalarını ve düğüm kimliğini korur. Ağ trafiği arayüzü seçimi de korunur.",
"logLines": "Satır sayısı",
"timeRange": "Zaman aralığı"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "Varsayılan abonelik yolu \"/sub/\" yaygın olarak bilinmektedir — değiştirin.",
"warnDefaultJsonPath": "Varsayılan JSON abonelik yolu \"/json/\" yaygın olarak bilinmektedir — değiştirin.",
"TGBotSettings": "Telegram Botu",
"networkTrafficInterfaceTitle": "Ağ trafiği arayüzü",
"networkTrafficMode": "Ağ trafiği izleme modu",
"networkTrafficDescription": "Sistem trafik toplamları ve hızı için kullanılacak arayüzü seçin. Eski toplama modu, katmanlı arayüzlerde aynı trafiği iki kez sayabilir. Docker içinde yalnızca kapsayıcının ağ ad alanındaki arayüzler kullanılabilir.",
"networkTrafficLegacy": "Tüm arayüzler (Eski)",
"networkTrafficAutomatic": "Otomatik",
"networkTrafficManual": "Manuel",
"networkTrafficUnavailable": "Seçilen ağ arayüzü kullanılamıyor. Kullanılabilir bir arayüz veya başka bir izleme modu seçin.",
"networkTrafficAutoResolved": "Varsayılan rota arayüzü: {interface}",
"networkTrafficLoadError": "Ağ arayüzleri yüklenemedi.",
"networkTrafficEmpty": "Kullanılabilir ağ arayüzü yok.",
"networkTrafficAutoUnavailable": "Varsayılan rota arayüzü yok. Algılama düzelene veya mod değiştirilene kadar trafik ölçümleri kullanılamaz.",
"panelListeningIP": "Dinleme IP",
"panelListeningIPDesc": "Web paneli için IP adresi. (tüm IP'leri dinlemek için boş bırakın)",
"panelListeningDomain": "Dinleme Alan Adı",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "ЗАБЛОКОВАНО",
"accessProxy": "ЧЕРЕЗ ПРОКСІ",
"importKeepHostSettings": "Зберегти налаштування цієї машини",
"importKeepHostSettingsDesc": "Залишає адреси та порти цієї панелі, базовий шлях, сертифікати та посвідчення для вузлів замість тих, що у завантаженому файлі.",
"importKeepHostSettingsDesc": "Залишає адреси та порти цієї панелі, базовий шлях, сертифікати та посвідчення для вузлів замість тих, що у завантаженому файлі. Вибір інтерфейсу мережевого трафіку також зберігається.",
"logLines": "Кількість рядків",
"timeRange": "Часовий діапазон"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "Шлях підписки за замовчуванням \"/sub/\" широко відомий — змініть його.",
"warnDefaultJsonPath": "JSON-шлях підписки за замовчуванням \"/json/\" широко відомий — змініть його.",
"TGBotSettings": "Telegram-бот",
"networkTrafficInterfaceTitle": "Інтерфейс мережевого трафіку",
"networkTrafficMode": "Режим мережевого трафіку",
"networkTrafficDescription": "Виберіть інтерфейс для загального трафіку та швидкості системи. Старий режим може двічі рахувати трафік багаторівневих інтерфейсів. У Docker доступні лише інтерфейси мережевого простору імен контейнера.",
"networkTrafficLegacy": "Усі інтерфейси (старий режим)",
"networkTrafficAutomatic": "Автоматично",
"networkTrafficManual": "Вручну",
"networkTrafficUnavailable": "Вибраний мережевий інтерфейс недоступний. Виберіть доступний інтерфейс або інший режим моніторингу.",
"networkTrafficAutoResolved": "Інтерфейс маршруту за замовчуванням: {interface}",
"networkTrafficLoadError": "Не вдалося завантажити мережеві інтерфейси.",
"networkTrafficEmpty": "Немає доступних мережевих інтерфейсів.",
"networkTrafficAutoUnavailable": "Інтерфейс маршруту за замовчуванням недоступний. Показники трафіку будуть недоступні до відновлення виявлення або зміни режиму.",
"panelListeningIP": "Слухати IP",
"panelListeningIPDesc": "IP-адреса для веб-панелі. (залиште порожнім, щоб слухати всі IP-адреси)",
"panelListeningDomain": "Домен прослуховування",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "Giữ cài đặt của máy này",
"importKeepHostSettingsDesc": "Giữ nguyên địa chỉ lắng nghe, cổng, đường dẫn cơ sở, chứng chỉ và danh tính node của bảng điều khiển này thay vì lấy chúng từ tệp đã tải lên.",
"importKeepHostSettingsDesc": "Giữ nguyên địa chỉ lắng nghe, cổng, đường dẫn cơ sở, chứng chỉ và danh tính node của bảng điều khiển này thay vì lấy chúng từ tệp đã tải lên. Lựa chọn giao diện lưu lượng mạng cũng được giữ lại.",
"logLines": "Số dòng",
"timeRange": "Khoảng thời gian"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "Đường dẫn đăng ký mặc định \"/sub/\" đã quá phổ biến — đổi nó.",
"warnDefaultJsonPath": "Đường dẫn đăng ký JSON mặc định \"/json/\" đã quá phổ biến — đổi nó.",
"TGBotSettings": "Bot Telegram",
"networkTrafficInterfaceTitle": "Giao diện lưu lượng mạng",
"networkTrafficMode": "Chế độ lưu lượng mạng",
"networkTrafficDescription": "Chọn giao diện dùng cho tổng lưu lượng và tốc độ của hệ thống. Chế độ cộng gộp cũ có thể đếm hai lần lưu lượng của các giao diện xếp chồng. Trong Docker, chỉ các giao diện thuộc không gian tên mạng của container mới khả dụng.",
"networkTrafficLegacy": "Tất cả giao diện (Cũ)",
"networkTrafficAutomatic": "Tự động",
"networkTrafficManual": "Thủ công",
"networkTrafficUnavailable": "Giao diện mạng đã chọn không khả dụng. Hãy chọn giao diện khả dụng hoặc chế độ giám sát khác.",
"networkTrafficAutoResolved": "Giao diện tuyến mặc định: {interface}",
"networkTrafficLoadError": "Không thể tải danh sách giao diện mạng.",
"networkTrafficEmpty": "Không có giao diện mạng khả dụng.",
"networkTrafficAutoUnavailable": "Không có giao diện tuyến mặc định khả dụng. Các chỉ số lưu lượng sẽ không khả dụng cho đến khi việc phát hiện phục hồi hoặc chế độ được thay đổi.",
"panelListeningIP": "IP Nghe của bảng điều khiển",
"panelListeningIPDesc": "Mặc định để trống để nghe tất cả các IP.",
"panelListeningDomain": "Tên miền của nghe bảng điều khiển",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "保留本机设置",
"importKeepHostSettingsDesc": "保留本面板的监听地址、端口、基础路径、证书和节点身份,而不是使用上传文件中的值。",
"importKeepHostSettingsDesc": "保留本面板的监听地址、端口、基础路径、证书和节点身份,而不是使用上传文件中的值。 也会保留网络流量接口选择。",
"logLines": "行数",
"timeRange": "时间范围"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "默认订阅路径 \"/sub/\" 众所周知 — 请更改。",
"warnDefaultJsonPath": "默认 JSON 订阅路径 \"/json/\" 众所周知 — 请更改。",
"TGBotSettings": "Telegram 机器人",
"networkTrafficInterfaceTitle": "网络流量接口",
"networkTrafficMode": "网络流量监控模式",
"networkTrafficDescription": "选择用于统计系统流量总量和速度的接口。旧版汇总模式可能对叠加接口的流量重复计数。在 Docker 中,仅能访问容器网络命名空间内的接口。",
"networkTrafficLegacy": "所有接口(旧版)",
"networkTrafficAutomatic": "自动",
"networkTrafficManual": "手动",
"networkTrafficUnavailable": "所选网络接口不可用。请选择可用接口或其他监控模式。",
"networkTrafficAutoResolved": "默认路由接口:{interface}",
"networkTrafficLoadError": "无法加载网络接口。",
"networkTrafficEmpty": "没有可用的网络接口。",
"networkTrafficAutoUnavailable": "默认路由接口不可用。在检测恢复或更改模式之前,流量指标将不可用。",
"panelListeningIP": "面板监听 IP",
"panelListeningIPDesc": "默认留空监听所有 IP",
"panelListeningDomain": "面板监听域名",
+12 -1
View File
@@ -302,7 +302,7 @@
"accessBlocked": "BLOCKED",
"accessProxy": "PROXY",
"importKeepHostSettings": "保留本機設定",
"importKeepHostSettingsDesc": "保留本面板的監聽位址、連接埠、基礎路徑、憑證與節點身分,而不是使用上傳檔案中的值。",
"importKeepHostSettingsDesc": "保留本面板的監聽位址、連接埠、基礎路徑、憑證與節點身分,而不是使用上傳檔案中的值。 也會保留網路流量介面選擇。",
"logLines": "行數",
"timeRange": "時間範圍"
},
@@ -1262,6 +1262,17 @@
"warnDefaultSubPath": "預設訂閱路徑 \"/sub/\" 廣為人知 — 請更改。",
"warnDefaultJsonPath": "預設 JSON 訂閱路徑 \"/json/\" 廣為人知 — 請更改。",
"TGBotSettings": "Telegram 機器人",
"networkTrafficInterfaceTitle": "網路流量介面",
"networkTrafficMode": "網路流量監控模式",
"networkTrafficDescription": "選擇用於統計系統流量總量和速度的介面。舊版彙總模式可能對堆疊介面的流量重複計數。在 Docker 中,僅能存取容器網路命名空間內的介面。",
"networkTrafficLegacy": "所有介面(舊版)",
"networkTrafficAutomatic": "自動",
"networkTrafficManual": "手動",
"networkTrafficUnavailable": "所選網路介面無法使用。請選擇可用介面或其他監控模式。",
"networkTrafficAutoResolved": "預設路由介面:{interface}",
"networkTrafficLoadError": "無法載入網路介面。",
"networkTrafficEmpty": "沒有可用的網路介面。",
"networkTrafficAutoUnavailable": "預設路由介面無法使用。在偵測恢復或變更模式之前,流量指標將無法使用。",
"panelListeningIP": "面板監聽 IP",
"panelListeningIPDesc": "預設留空監聽所有 IP",
"panelListeningDomain": "面板監聽域名",
+5
View File
@@ -95,6 +95,10 @@ func run(root, outDir string) error {
Path: resolveRel(root, "internal/web/service"),
StructAllow: setOf(
"InboundOption",
"NetworkInterfaceOption",
"NetworkInterfacesResponse",
"NetworkTrafficSelection",
"Status",
"HappLinkResult",
"ClientSlim",
"ClientRenewalPreviewRequest",
@@ -119,6 +123,7 @@ func run(root, outDir string) error {
"PeerActivity",
"HwidSlotStatus",
),
AliasAllow: setOf("ProcessState"),
},
{
Path: resolveRel(root, "internal/web/service/panel"),