feat(nodes): add fleet monitoring and host telemetry

Carry sampled host metrics through existing heartbeats and count client identities in SQL. Show the current panel and fleet in a responsive monitoring table based on the approved design.
This commit is contained in:
Hamed Sanaei
2026-12-01 14:05:35 +03:30
parent 267379456a
commit 45236cd492
57 changed files with 3477 additions and 1318 deletions
+8 -1
View File
@@ -11,6 +11,10 @@ _openapi:
title: List every configured node with its connection details, health, and last
heartbeat patch.
url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch'
- depth: 2
title: Read the local panel, unique fleet client counts and sampled remote host
telemetry.
url: '#read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry'
- depth: 2
title: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
@@ -99,6 +103,9 @@ _openapi:
- content: List every configured node with its connection details, health, and
last heartbeat patch.
id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
- content: Read the local panel, unique fleet client counts and sampled remote
host telemetry.
id: read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry
- content: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
@@ -175,7 +182,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/restartXray/{id}","method":"post"},{"path":"/panel/api/nodes/restartPanel/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/overview","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/restartXray/{id}","method":"post"},{"path":"/panel/api/nodes/restartPanel/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
</>
);
}
+288
View File
@@ -4503,6 +4503,14 @@
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"enum": [
"verify",
@@ -4664,6 +4672,43 @@
],
"type": "object"
},
"NodeFleetCounts": {
"properties": {
"activeCount": {
"example": 90,
"type": "integer"
},
"clientCount": {
"example": 100,
"type": "integer"
},
"depletedCount": {
"example": 2,
"type": "integer"
},
"disabledCount": {
"example": 8,
"type": "integer"
},
"inboundCount": {
"example": 8,
"type": "integer"
},
"onlineCount": {
"example": 20,
"type": "integer"
}
},
"required": [
"activeCount",
"clientCount",
"depletedCount",
"disabledCount",
"inboundCount",
"onlineCount"
],
"type": "object"
},
"NodeInboundTraffic": {
"properties": {
"down": {
@@ -4686,6 +4731,40 @@
],
"type": "object"
},
"NodeMasterView": {
"properties": {
"counts": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"panelVersion": {
"example": "v3.12.0",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"xrayError": {
"type": "string"
},
"xrayState": {
"example": "running",
"type": "string"
},
"xrayVersion": {
"example": "26.1.1",
"type": "string"
}
},
"required": [
"counts"
],
"type": "object"
},
"NodeMutationRequest": {
"description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.",
"properties": {
@@ -4776,6 +4855,33 @@
],
"type": "object"
},
"NodeOverview": {
"properties": {
"fleet": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"master": {
"$ref": "#/components/schemas/NodeMasterView"
},
"nodes": {
"items": {
"allOf": [
{
"$ref": "#/components/schemas/NodeView"
}
],
"nullable": true
},
"type": "array"
}
},
"required": [
"fleet",
"master",
"nodes"
],
"type": "object"
},
"NodeSnapshotAttachment": {
"properties": {
"email": {
@@ -4819,6 +4925,106 @@
],
"type": "object"
},
"NodeTelemetry": {
"description": "NodeTelemetry describes one host sample. Nil metrics were not measured.",
"properties": {
"cpuPct": {
"example": 12.5,
"nullable": true,
"type": "number"
},
"load1": {
"example": 0.25,
"nullable": true,
"type": "number"
},
"load15": {
"example": 0.12,
"nullable": true,
"type": "number"
},
"load5": {
"example": 0.18,
"nullable": true,
"type": "number"
},
"logicalCores": {
"example": 8,
"nullable": true,
"type": "integer"
},
"memAvailableBytes": {
"example": 1073741824,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memTotalBytes": {
"example": 4294967296,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memUsedBytes": {
"example": 2147483648,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netDown": {
"example": 2048,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netUp": {
"example": 1024,
"format": "int64",
"nullable": true,
"type": "integer"
},
"physicalCores": {
"example": 4,
"nullable": true,
"type": "integer"
},
"resourceScope": {
"example": "container",
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"sampledAt": {
"example": 1700000000000,
"format": "int64",
"type": "integer"
},
"tcpCount": {
"example": 75,
"nullable": true,
"type": "integer"
},
"udpCount": {
"example": 12,
"nullable": true,
"type": "integer"
},
"uptimeSecs": {
"example": 3600,
"format": "int64",
"nullable": true,
"type": "integer"
}
},
"required": [
"sampledAt"
],
"type": "object"
},
"NodeTrafficSnapshotV1": {
"description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.",
"properties": {
@@ -5050,6 +5256,14 @@
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"example": "verify",
"type": "string"
@@ -5916,6 +6130,12 @@
"resourceScope": {
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"swap": {},
"tcpCount": {
"type": "integer"
@@ -7932,6 +8152,7 @@
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"sampleAgeMillis": 125,
"swap": null,
"tcpCount": 0,
"udpCount": 0,
@@ -13917,6 +14138,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -13936,6 +14158,69 @@
}
}
},
"/panel/api/nodes/overview": {
"get": {
"tags": [
"Nodes"
],
"summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.",
"operationId": "get_panel_api_nodes_overview",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/NodeOverview"
}
}
},
"example": {
"success": true,
"obj": {
"fleet": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"master": {
"counts": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"panelVersion": "v3.12.0",
"telemetry": null,
"xrayError": "",
"xrayState": "running",
"xrayVersion": "26.1.1"
},
"nodes": [
null
]
}
}
}
}
}
}
}
},
"/panel/api/nodes/mtls/ca": {
"post": {
"tags": [
@@ -14123,6 +14408,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -14278,6 +14564,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -20079,6 +20366,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
+288
View File
@@ -4503,6 +4503,14 @@
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"enum": [
"verify",
@@ -4664,6 +4672,43 @@
],
"type": "object"
},
"NodeFleetCounts": {
"properties": {
"activeCount": {
"example": 90,
"type": "integer"
},
"clientCount": {
"example": 100,
"type": "integer"
},
"depletedCount": {
"example": 2,
"type": "integer"
},
"disabledCount": {
"example": 8,
"type": "integer"
},
"inboundCount": {
"example": 8,
"type": "integer"
},
"onlineCount": {
"example": 20,
"type": "integer"
}
},
"required": [
"activeCount",
"clientCount",
"depletedCount",
"disabledCount",
"inboundCount",
"onlineCount"
],
"type": "object"
},
"NodeInboundTraffic": {
"properties": {
"down": {
@@ -4686,6 +4731,40 @@
],
"type": "object"
},
"NodeMasterView": {
"properties": {
"counts": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"panelVersion": {
"example": "v3.12.0",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"xrayError": {
"type": "string"
},
"xrayState": {
"example": "running",
"type": "string"
},
"xrayVersion": {
"example": "26.1.1",
"type": "string"
}
},
"required": [
"counts"
],
"type": "object"
},
"NodeMutationRequest": {
"description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.",
"properties": {
@@ -4776,6 +4855,33 @@
],
"type": "object"
},
"NodeOverview": {
"properties": {
"fleet": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"master": {
"$ref": "#/components/schemas/NodeMasterView"
},
"nodes": {
"items": {
"allOf": [
{
"$ref": "#/components/schemas/NodeView"
}
],
"nullable": true
},
"type": "array"
}
},
"required": [
"fleet",
"master",
"nodes"
],
"type": "object"
},
"NodeSnapshotAttachment": {
"properties": {
"email": {
@@ -4819,6 +4925,106 @@
],
"type": "object"
},
"NodeTelemetry": {
"description": "NodeTelemetry describes one host sample. Nil metrics were not measured.",
"properties": {
"cpuPct": {
"example": 12.5,
"nullable": true,
"type": "number"
},
"load1": {
"example": 0.25,
"nullable": true,
"type": "number"
},
"load15": {
"example": 0.12,
"nullable": true,
"type": "number"
},
"load5": {
"example": 0.18,
"nullable": true,
"type": "number"
},
"logicalCores": {
"example": 8,
"nullable": true,
"type": "integer"
},
"memAvailableBytes": {
"example": 1073741824,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memTotalBytes": {
"example": 4294967296,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memUsedBytes": {
"example": 2147483648,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netDown": {
"example": 2048,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netUp": {
"example": 1024,
"format": "int64",
"nullable": true,
"type": "integer"
},
"physicalCores": {
"example": 4,
"nullable": true,
"type": "integer"
},
"resourceScope": {
"example": "container",
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"sampledAt": {
"example": 1700000000000,
"format": "int64",
"type": "integer"
},
"tcpCount": {
"example": 75,
"nullable": true,
"type": "integer"
},
"udpCount": {
"example": 12,
"nullable": true,
"type": "integer"
},
"uptimeSecs": {
"example": 3600,
"format": "int64",
"nullable": true,
"type": "integer"
}
},
"required": [
"sampledAt"
],
"type": "object"
},
"NodeTrafficSnapshotV1": {
"description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.",
"properties": {
@@ -5050,6 +5256,14 @@
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"example": "verify",
"type": "string"
@@ -5916,6 +6130,12 @@
"resourceScope": {
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"swap": {},
"tcpCount": {
"type": "integer"
@@ -7932,6 +8152,7 @@
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"sampleAgeMillis": 125,
"swap": null,
"tcpCount": 0,
"udpCount": 0,
@@ -13917,6 +14138,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -13936,6 +14158,69 @@
}
}
},
"/panel/api/nodes/overview": {
"get": {
"tags": [
"Nodes"
],
"summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.",
"operationId": "get_panel_api_nodes_overview",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/NodeOverview"
}
}
},
"example": {
"success": true,
"obj": {
"fleet": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"master": {
"counts": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"panelVersion": "v3.12.0",
"telemetry": null,
"xrayError": "",
"xrayState": "running",
"xrayVersion": "26.1.1"
},
"nodes": [
null
]
}
}
}
}
}
}
}
},
"/panel/api/nodes/mtls/ca": {
"post": {
"tags": [
@@ -14123,6 +14408,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -14278,6 +14564,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -20079,6 +20366,7 @@
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
+23 -1
View File
@@ -3,12 +3,34 @@ import { useMemo } from 'react';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { NodeListSchema } from '@/schemas/node';
import { NodeListSchema, NodeOverviewSchema } from '@/schemas/node';
import type { NodeRecord } from '@/schemas/node';
import { keys } from '@/api/queryKeys';
export type { NodeRecord };
async function fetchNodeOverview() {
const msg = await HttpUtil.get('/panel/api/nodes/overview', undefined, { silent: true });
if (!msg.success || msg.obj == null) throw new Error(msg.msg || 'Failed to fetch node overview');
return NodeOverviewSchema.parse(msg.obj);
}
const emptyNodes: NodeRecord[] = [];
export function useNodeOverviewQuery() {
const query = useQuery({ queryKey: keys.nodes.overview(), queryFn: fetchNodeOverview });
return {
nodes: query.data?.nodes ?? emptyNodes,
master: query.data?.master,
fleet: query.data?.fleet,
nodesUpdatedAt: query.dataUpdatedAt,
loading: query.isFetching,
fetched: query.data !== undefined || query.isError,
fetchError: query.error?.message ?? '',
refetch: query.refetch,
};
}
export interface NodeTotals {
total: number;
online: number;
+1
View File
@@ -8,6 +8,7 @@ export const keys = {
nodes: {
root: () => ['nodes'] as const,
list: () => ['nodes', 'list'] as const,
overview: () => ['nodes', 'overview'] as const,
},
hosts: {
root: () => ['hosts'] as const,
+8
View File
@@ -4,6 +4,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { getSharedWebSocketClient } from '@/api/websocket';
import { keys } from '@/api/queryKeys';
import { isRecentLocalInvalidate } from '@/api/invalidationTracker';
import { NodeOverviewSchema } from '@/schemas/node';
type Handler = (payload: unknown) => void;
@@ -40,6 +41,11 @@ export function useWebSocketBridge() {
queryClient.setQueryData(keys.nodes.list(), payload);
};
const onNodesOverview: Handler = (payload) => {
const overview = NodeOverviewSchema.safeParse(payload);
if (overview.success) queryClient.setQueryData(keys.nodes.overview(), overview.data);
};
const onInbounds: Handler = (payload) => {
if (!Array.isArray(payload)) return;
queryClient.setQueryData(keys.inbounds.slim(), payload);
@@ -48,6 +54,7 @@ export function useWebSocketBridge() {
client.on('invalidate', onInvalidate);
client.on('outbounds', onOutbounds);
client.on('nodes', onNodes);
client.on('nodesOverview', onNodesOverview);
client.on('inbounds', onInbounds);
client.connect();
@@ -55,6 +62,7 @@ export function useWebSocketBridge() {
client.off('invalidate', onInvalidate);
client.off('outbounds', onOutbounds);
client.off('nodes', onNodes);
client.off('nodesOverview', onNodesOverview);
client.off('inbounds', onInbounds);
if (invalidateTimer != null) {
clearTimeout(invalidateTimer);
+73
View File
@@ -1173,6 +1173,7 @@ export const EXAMPLES: Record<string, unknown> = {
"remark": "",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -1200,11 +1201,34 @@ export const EXAMPLES: Record<string, unknown> = {
"total": 10737418240,
"up": 1048576
},
"NodeFleetCounts": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"NodeInboundTraffic": {
"down": 0,
"id": 1,
"up": 0
},
"NodeMasterView": {
"counts": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"panelVersion": "v3.12.0",
"telemetry": null,
"xrayError": "",
"xrayState": "running",
"xrayVersion": "26.1.1"
},
"NodeMutationRequest": {
"address": "",
"allowPrivateAddress": false,
@@ -1225,6 +1249,34 @@ export const EXAMPLES: Record<string, unknown> = {
"scheme": "http",
"tlsVerifyMode": "verify"
},
"NodeOverview": {
"fleet": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"master": {
"counts": {
"activeCount": 90,
"clientCount": 100,
"depletedCount": 2,
"disabledCount": 8,
"inboundCount": 8,
"onlineCount": 20
},
"panelVersion": "v3.12.0",
"telemetry": null,
"xrayError": "",
"xrayState": "running",
"xrayVersion": "26.1.1"
},
"nodes": [
null
]
},
"NodeSnapshotAttachment": {
"email": "user1",
"inboundId": 1
@@ -1240,6 +1292,25 @@ export const EXAMPLES: Record<string, unknown> = {
null
]
},
"NodeTelemetry": {
"cpuPct": 12.5,
"load1": 0.25,
"load15": 0.12,
"load5": 0.18,
"logicalCores": 8,
"memAvailableBytes": 1073741824,
"memTotalBytes": 4294967296,
"memUsedBytes": 2147483648,
"netDown": 2048,
"netUp": 1024,
"physicalCores": 4,
"resourceScope": "container",
"sampleAgeMillis": 125,
"sampledAt": 1700000000000,
"tcpCount": 75,
"udpCount": 12,
"uptimeSecs": 3600
},
"NodeTrafficSnapshotV1": {
"activeInboundTree": {},
"clients": [
@@ -1315,6 +1386,7 @@ export const EXAMPLES: Record<string, unknown> = {
"remark": "Primary edge",
"scheme": "https",
"status": "online",
"telemetry": null,
"tlsVerifyMode": "verify",
"transitive": false,
"unavailableMetrics": [
@@ -1542,6 +1614,7 @@ export const EXAMPLES: Record<string, unknown> = {
"panelVersion": "",
"publicIP": null,
"resourceScope": "",
"sampleAgeMillis": 125,
"swap": null,
"tcpCount": 0,
"udpCount": 0,
+220
View File
@@ -4477,6 +4477,14 @@ export const SCHEMAS: Record<string, unknown> = {
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"enum": [
"verify",
@@ -4638,6 +4646,43 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"NodeFleetCounts": {
"properties": {
"activeCount": {
"example": 90,
"type": "integer"
},
"clientCount": {
"example": 100,
"type": "integer"
},
"depletedCount": {
"example": 2,
"type": "integer"
},
"disabledCount": {
"example": 8,
"type": "integer"
},
"inboundCount": {
"example": 8,
"type": "integer"
},
"onlineCount": {
"example": 20,
"type": "integer"
}
},
"required": [
"activeCount",
"clientCount",
"depletedCount",
"disabledCount",
"inboundCount",
"onlineCount"
],
"type": "object"
},
"NodeInboundTraffic": {
"properties": {
"down": {
@@ -4660,6 +4705,40 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"NodeMasterView": {
"properties": {
"counts": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"panelVersion": {
"example": "v3.12.0",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"xrayError": {
"type": "string"
},
"xrayState": {
"example": "running",
"type": "string"
},
"xrayVersion": {
"example": "26.1.1",
"type": "string"
}
},
"required": [
"counts"
],
"type": "object"
},
"NodeMutationRequest": {
"description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.",
"properties": {
@@ -4750,6 +4829,33 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"NodeOverview": {
"properties": {
"fleet": {
"$ref": "#/components/schemas/NodeFleetCounts"
},
"master": {
"$ref": "#/components/schemas/NodeMasterView"
},
"nodes": {
"items": {
"allOf": [
{
"$ref": "#/components/schemas/NodeView"
}
],
"nullable": true
},
"type": "array"
}
},
"required": [
"fleet",
"master",
"nodes"
],
"type": "object"
},
"NodeSnapshotAttachment": {
"properties": {
"email": {
@@ -4793,6 +4899,106 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"NodeTelemetry": {
"description": "NodeTelemetry describes one host sample. Nil metrics were not measured.",
"properties": {
"cpuPct": {
"example": 12.5,
"nullable": true,
"type": "number"
},
"load1": {
"example": 0.25,
"nullable": true,
"type": "number"
},
"load15": {
"example": 0.12,
"nullable": true,
"type": "number"
},
"load5": {
"example": 0.18,
"nullable": true,
"type": "number"
},
"logicalCores": {
"example": 8,
"nullable": true,
"type": "integer"
},
"memAvailableBytes": {
"example": 1073741824,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memTotalBytes": {
"example": 4294967296,
"format": "int64",
"nullable": true,
"type": "integer"
},
"memUsedBytes": {
"example": 2147483648,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netDown": {
"example": 2048,
"format": "int64",
"nullable": true,
"type": "integer"
},
"netUp": {
"example": 1024,
"format": "int64",
"nullable": true,
"type": "integer"
},
"physicalCores": {
"example": 4,
"nullable": true,
"type": "integer"
},
"resourceScope": {
"example": "container",
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"sampledAt": {
"example": 1700000000000,
"format": "int64",
"type": "integer"
},
"tcpCount": {
"example": 75,
"nullable": true,
"type": "integer"
},
"udpCount": {
"example": 12,
"nullable": true,
"type": "integer"
},
"uptimeSecs": {
"example": 3600,
"format": "int64",
"nullable": true,
"type": "integer"
}
},
"required": [
"sampledAt"
],
"type": "object"
},
"NodeTrafficSnapshotV1": {
"description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.",
"properties": {
@@ -5024,6 +5230,14 @@ export const SCHEMAS: Record<string, unknown> = {
"example": "online",
"type": "string"
},
"telemetry": {
"allOf": [
{
"$ref": "#/components/schemas/NodeTelemetry"
}
],
"nullable": true
},
"tlsVerifyMode": {
"example": "verify",
"type": "string"
@@ -5890,6 +6104,12 @@ export const SCHEMAS: Record<string, unknown> = {
"resourceScope": {
"type": "string"
},
"sampleAgeMillis": {
"example": 125,
"format": "int64",
"nullable": true,
"type": "integer"
},
"swap": {},
"tcpCount": {
"type": "integer"
+47
View File
@@ -1027,6 +1027,7 @@ export interface Node {
remark: string;
scheme: string;
status: string;
telemetry?: NodeTelemetry | null;
tlsVerifyMode: string;
transitive?: boolean;
unavailableMetrics?: string[];
@@ -1054,12 +1055,30 @@ export interface NodeClientTraffic {
up: number;
}
export interface NodeFleetCounts {
activeCount: number;
clientCount: number;
depletedCount: number;
disabledCount: number;
inboundCount: number;
onlineCount: number;
}
export interface NodeInboundTraffic {
down: number;
id: number;
up: number;
}
export interface NodeMasterView {
counts: NodeFleetCounts;
panelVersion?: string;
telemetry?: NodeTelemetry | null;
xrayError?: string;
xrayState?: string;
xrayVersion?: string;
}
export interface NodeMutationRequest {
address: string;
allowPrivateAddress: boolean;
@@ -1079,6 +1098,12 @@ export interface NodeMutationRequest {
tlsVerifyMode: string;
}
export interface NodeOverview {
fleet: NodeFleetCounts;
master: NodeMasterView;
nodes: NodeView | null[];
}
export interface NodeSnapshotAttachment {
email: string;
inboundId: number;
@@ -1089,6 +1114,26 @@ export interface NodeSnapshotStructure {
inbounds: Inbound | null[];
}
export interface NodeTelemetry {
cpuPct?: number | null;
load1?: number | null;
load15?: number | null;
load5?: number | null;
logicalCores?: number | null;
memAvailableBytes?: number | null;
memTotalBytes?: number | null;
memUsedBytes?: number | null;
netDown?: number | null;
netUp?: number | null;
physicalCores?: number | null;
resourceScope?: string;
sampleAgeMillis?: number | null;
sampledAt: number;
tcpCount?: number | null;
udpCount?: number | null;
uptimeSecs?: number | null;
}
export interface NodeTrafficSnapshotV1 {
activeInboundTree: Record<string, string[]>;
clients: NodeClientTraffic[];
@@ -1138,6 +1183,7 @@ export interface NodeView {
remark: string;
scheme: string;
status: string;
telemetry?: NodeTelemetry | null;
tlsVerifyMode: string;
transitive?: boolean;
unavailableMetrics?: string[];
@@ -1337,6 +1383,7 @@ export interface Status {
panelVersion: string;
publicIP: unknown;
resourceScope?: string;
sampleAgeMillis?: number | null;
swap: unknown;
tcpCount: number;
udpCount: number;
+51
View File
@@ -1092,6 +1092,7 @@ export const NodeSchema = z.object({
remark: z.string(),
scheme: z.enum(['http', 'https']),
status: z.string(),
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
tlsVerifyMode: z.enum(['verify', 'skip', 'pin', 'mtls']),
transitive: z.boolean().optional(),
unavailableMetrics: z.array(z.string()).optional(),
@@ -1121,6 +1122,16 @@ export const NodeClientTrafficSchema = z.object({
});
export type NodeClientTraffic = z.infer<typeof NodeClientTrafficSchema>;
export const NodeFleetCountsSchema = z.object({
activeCount: z.number().int(),
clientCount: z.number().int(),
depletedCount: z.number().int(),
disabledCount: z.number().int(),
inboundCount: z.number().int(),
onlineCount: z.number().int(),
});
export type NodeFleetCounts = z.infer<typeof NodeFleetCountsSchema>;
export const NodeInboundTrafficSchema = z.object({
down: z.number().int(),
id: z.number().int(),
@@ -1128,6 +1139,16 @@ export const NodeInboundTrafficSchema = z.object({
});
export type NodeInboundTraffic = z.infer<typeof NodeInboundTrafficSchema>;
export const NodeMasterViewSchema = z.object({
counts: z.lazy(() => NodeFleetCountsSchema),
panelVersion: z.string().optional(),
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
xrayError: z.string().optional(),
xrayState: z.string().optional(),
xrayVersion: z.string().optional(),
});
export type NodeMasterView = z.infer<typeof NodeMasterViewSchema>;
export const NodeMutationRequestSchema = z.object({
address: z.string(),
allowPrivateAddress: z.boolean(),
@@ -1148,6 +1169,13 @@ export const NodeMutationRequestSchema = z.object({
});
export type NodeMutationRequest = z.infer<typeof NodeMutationRequestSchema>;
export const NodeOverviewSchema = z.object({
fleet: z.lazy(() => NodeFleetCountsSchema),
master: z.lazy(() => NodeMasterViewSchema),
nodes: z.array(z.lazy(() => NodeViewSchema).nullable()),
});
export type NodeOverview = z.infer<typeof NodeOverviewSchema>;
export const NodeSnapshotAttachmentSchema = z.object({
email: z.string(),
inboundId: z.number().int(),
@@ -1160,6 +1188,27 @@ export const NodeSnapshotStructureSchema = z.object({
});
export type NodeSnapshotStructure = z.infer<typeof NodeSnapshotStructureSchema>;
export const NodeTelemetrySchema = z.object({
cpuPct: z.number().nullable().optional(),
load1: z.number().nullable().optional(),
load15: z.number().nullable().optional(),
load5: z.number().nullable().optional(),
logicalCores: z.number().int().nullable().optional(),
memAvailableBytes: z.number().int().nullable().optional(),
memTotalBytes: z.number().int().nullable().optional(),
memUsedBytes: z.number().int().nullable().optional(),
netDown: z.number().int().nullable().optional(),
netUp: z.number().int().nullable().optional(),
physicalCores: z.number().int().nullable().optional(),
resourceScope: z.string().optional(),
sampleAgeMillis: z.number().int().nullable().optional(),
sampledAt: z.number().int(),
tcpCount: z.number().int().nullable().optional(),
udpCount: z.number().int().nullable().optional(),
uptimeSecs: z.number().int().nullable().optional(),
});
export type NodeTelemetry = z.infer<typeof NodeTelemetrySchema>;
export const NodeTrafficSnapshotV1Schema = z.object({
activeInboundTree: z.record(z.string(), z.array(z.string())),
clients: z.array(z.lazy(() => NodeClientTrafficSchema)),
@@ -1210,6 +1259,7 @@ export const NodeViewSchema = z.object({
remark: z.string(),
scheme: z.string(),
status: z.string(),
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
tlsVerifyMode: z.string(),
transitive: z.boolean().optional(),
unavailableMetrics: z.array(z.string()).optional(),
@@ -1424,6 +1474,7 @@ export const StatusSchema = z.object({
panelVersion: z.string(),
publicIP: z.unknown(),
resourceScope: z.string().optional(),
sampleAgeMillis: z.number().int().nullable().optional(),
swap: z.unknown(),
tcpCount: z.number().int(),
udpCount: z.number().int(),
+7
View File
@@ -2052,6 +2052,13 @@ export const sections: readonly Section[] = [
responseSchema: 'NodeView',
responseSchemaArray: true,
},
{
method: 'GET',
path: '/panel/api/nodes/overview',
summary:
'Read the local panel, unique fleet client counts and sampled remote host telemetry.',
responseSchema: 'NodeOverview',
},
{
method: 'POST',
path: '/panel/api/nodes/mtls/ca',
+173 -132
View File
@@ -1,160 +1,201 @@
.toolbar {
margin-bottom: 12px;
display: flex;
justify-content: space-between;
align-items: center;
@font-face {
font-family: 'Source Sans Pro';
src: url('./fonts/SourceSansPro-Regular.woff2') format('woff2');
font-weight: 400;
font-display: swap;
}
.name-cell {
display: flex;
flex-direction: column;
}
.name-cell .name {
font-weight: 500;
}
.name-cell .remark {
font-size: 12px;
opacity: 0.65;
}
.address-header {
display: inline-flex;
align-items: center;
gap: 6px;
}
.ip-toggle-icon {
cursor: pointer;
font-size: 14px;
opacity: 0.7;
}
.ip-toggle-icon:hover {
opacity: 1;
}
.address-hidden {
filter: blur(5px);
transition: filter 0.2s ease;
}
.address-visible {
filter: none;
}
.node-cards {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 4px;
}
.node-card {
border: 1px solid var(--ant-color-border-secondary);
border-radius: 10px;
padding: 12px;
background: var(--ant-color-fill-quaternary);
display: flex;
flex-direction: column;
gap: 8px;
}
.card-head {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
user-select: none;
}
.card-expand {
font-size: 12px;
opacity: 0.6;
transition: transform 150ms ease;
flex-shrink: 0;
}
.card-expand.is-expanded {
transform: rotate(90deg);
}
.node-name {
font-weight: 600;
flex: 1;
.nodes-overview {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.row-action-trigger {
font-size: 20px;
cursor: pointer;
}
.card-stats {
display: flex;
flex-direction: column;
gap: 6px;
}
.stat-row {
.nodes-heading,
.nodes-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
gap: 8px 12px;
margin-block-end: 12px;
}
.stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
opacity: 0.6;
min-width: 96px;
flex-shrink: 0;
.nodes-heading {
justify-content: space-between;
}
.card-stats .ant-tag {
margin: 0;
.nodes-heading .ant-typography {
margin-block: 0;
}
.card-history {
margin-top: 4px;
padding-top: 8px;
border-top: 1px solid var(--ant-color-border-secondary);
.nodes-toolbar .ant-input-affix-wrapper {
width: min(100%, 22rem);
}
.card-empty {
text-align: center;
color: var(--ant-color-text-secondary);
padding: 24px 12px;
.nodes-toolbar .ant-select {
min-width: 9rem;
}
.node-muted {
color: var(--node-muted);
font-size: 12px;
}
.node-fleet-table .ant-table {
border: 1px solid var(--ant-color-border-secondary);
border-radius: var(--ant-border-radius);
}
.node-fleet-table .ant-table-cell {
padding-inline: 6px !important;
overflow-wrap: anywhere;
vertical-align: middle;
}
.node-fleet-table .ant-table-thead > tr > th {
background: var(--ant-color-fill-secondary);
}
.node-row-fleet > td,
.node-card.node-row-fleet {
background: var(--node-fleet-bg);
}
.node-row-master > td,
.node-card.node-row-master {
background: var(--node-master-bg);
}
.node-cell-stack,
.node-client-counts,
.node-cards {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
gap: 3px;
min-width: 0;
}
.name-cell .name {
font-weight: 600;
}
.node-child-name {
padding-inline-start: 6px;
}
.node-network-speed {
display: inline-grid;
row-gap: 2px;
text-align: start;
line-height: 1.25;
gap: 3px;
font-variant-numeric: tabular-nums;
}
.node-network-direction {
display: grid;
grid-template-columns: 1em auto;
column-gap: 4px;
align-items: center;
white-space: nowrap;
grid-template-columns: 1em minmax(0, 1fr);
gap: 4px;
}
.node-hardware {
font-family: 'Source Sans Pro', system-ui, sans-serif;
line-height: 1.25;
font-variant-numeric: tabular-nums;
}
.node-cpu {
font-size: 17px;
font-weight: 400;
}
.node-ram {
font-size: 16px;
font-weight: 400;
}
.node-open-link,
.node-status-button {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.node-open-link:any-link,
.node-update-available {
color: var(--node-text);
text-decoration: underline;
}
.node-status-button {
max-width: 100%;
border: 0;
padding: 2px;
background: transparent;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
}
.node-status-button .online-dot,
.node-status-button .xray-error-dot {
display: inline-block;
height: 6px;
width: 6px;
border-radius: 50%;
background: var(--node-online-dot);
}
.node-status-button .xray-error-dot {
background: #722ed1;
}
.node-status-tooltip {
overflow-wrap: anywhere;
}
.node-update-available {
padding-inline: 0;
height: auto;
text-align: start;
white-space: normal;
}
.node-client-counts .ant-tag {
color: var(--ant-color-text);
margin-inline-end: 0;
padding-inline: 3px;
}
.node-cards {
gap: 10px;
}
.node-card {
display: grid;
gap: 10px;
min-width: 0;
overflow-wrap: anywhere;
background: var(--node-surface);
border: 1px solid var(--node-border);
border-radius: var(--node-radius);
padding: 10px;
}
.node-card-heading,
.node-card-metrics {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(9rem, 100%), 1fr));
align-items: start;
gap: 8px;
}
.node-card-history summary {
cursor: pointer;
}
.node-visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@@ -0,0 +1,175 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import { ConfigProvider } from 'antd';
import { useState } from 'react';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import type { NodeRecord } from '@/schemas/node';
import NodeList from './NodeList';
const counts = {
clientCount: 7100,
inboundCount: 40,
activeCount: 6050,
disabledCount: 50,
depletedCount: 1000,
onlineCount: 210,
};
const noop = () => {};
function Fixture({ compact, rtl }: { compact?: boolean; rtl?: boolean }) {
const [selectedIds, setSelectedIds] = useState<number[]>([]);
const { isMobile } = useMediaQuery(1080);
const [now] = useState(Date.now);
const nodes: NodeRecord[] = [
{
id: 1,
name: 'Finland edge',
status: 'online',
enable: true,
xrayVersion: '26.1.1',
panelVersion: '3.12.0',
latencyMs: 42,
lastHeartbeat: Math.floor(now / 1000) - 2,
scheme: 'https',
address: '2001:db8::3',
port: 2053,
basePath: '/edge/',
telemetry: {
sampledAt: now,
cpuPct: 0,
logicalCores: 8,
memUsedBytes: 4 * 2 ** 30,
memTotalBytes: 16 * 2 ** 30,
netUp: 1024,
netDown: 2048,
tcpCount: 0,
udpCount: 21,
load1: 0.25,
load5: 0.15,
load15: 0.1,
uptimeSecs: 5000,
},
clientCount: 3077,
onlineCount: 31,
onlineTotalCount: 53,
},
{
id: 2,
name: 'Frankfurt',
status: 'online',
enable: true,
panelVersion: '3.13.0',
scheme: 'https',
address: 'frankfurt-with-a-very-long-hostname.example.test',
port: 443,
telemetry: { sampledAt: now, cpuPct: 40, logicalCores: 4, tcpCount: 4, load1: 0.75 },
},
{
id: 3,
name: 'This-is-an-intentionally-long-node-name-without-spaces',
status: 'offline',
enable: true,
lastError: 'Remote panel did not respond',
},
{
id: 4,
name: 'Standby',
status: 'online',
enable: false,
telemetry: { sampledAt: now, cpuPct: 100, tcpCount: 9 },
},
];
return (
<ConfigProvider direction={rtl ? 'rtl' : 'ltr'}>
<div dir={rtl ? 'rtl' : 'ltr'} className="nodes-story">
<NodeList
nodes={nodes}
isMobile={compact ?? isMobile}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
master={{
counts: {
inboundCount: 8,
clientCount: 2200,
activeCount: 1860,
disabledCount: 50,
depletedCount: 290,
onlineCount: 80,
},
panelVersion: '3.13.0',
xrayVersion: '26.1.1',
xrayState: 'running',
telemetry: {
sampledAt: now,
cpuPct: 20,
logicalCores: 4,
memUsedBytes: 2 * 2 ** 30,
memTotalBytes: 8 * 2 ** 30,
netUp: 1024,
netDown: 2048,
tcpCount: 10,
udpCount: 5,
load1: 0.5,
load5: 0.3,
load15: 0.15,
uptimeSecs: 91000,
},
}}
fleet={counts}
latestVersion="3.13.0"
onAdd={noop}
onMtls={noop}
onEdit={noop}
onDelete={noop}
onProbe={noop}
onToggleEnable={noop}
onUpdateNode={noop}
onUpdateSelected={noop}
onRestart={noop}
/>
</div>
</ConfigProvider>
);
}
const meta = { title: 'Nodes/Fleet Monitoring', component: Fixture } satisfies Meta<typeof Fixture>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Desktop: Story = {
play: async ({ canvasElement, userEvent }) => {
const canvas = within(canvasElement);
const row = canvas.getByRole('row', { name: /All nodes/ });
await expect(within(row).getByText('3/5 reporting')).toBeVisible();
await expect(within(row).getByText('20.0%')).toBeVisible();
await expect(within(row).queryByRole('checkbox')).toBeNull();
await expect(
within(canvas.getByRole('row', { name: /This panel/ })).queryByRole('switch'),
).toBeNull();
const edge = canvas.getByRole('row', { name: /Finland edge/ });
const link = within(edge).getByRole('link', { name: 'Open' });
await expect(link).toHaveAttribute('href', 'https://[2001:db8::3]:2053/edge/');
await expect(link).toHaveAttribute('rel', 'noopener noreferrer');
const status = within(edge).getByRole('button', { name: 'Online' });
await userEvent.click(status);
await expect(
await within(canvasElement.ownerDocument.body).findByText(/Latency · 42 ms/),
).toBeVisible();
const input = canvas.getByRole('searchbox', { name: 'Search' });
await userEvent.click(input);
for (const viewport of [1280, 1440, 1664, 1920]) {
const container = canvas.getByRole('region', { name: 'Nodes' });
container.style.width = `${viewport - 260}px`;
const table = container.querySelector('.ant-table-content') as HTMLElement;
await expect(table.scrollWidth).toBeLessThanOrEqual(table.clientWidth + 1);
container.style.width = '';
}
await userEvent.type(input, 'Frankfurt');
await expect(canvas.queryByText('Finland edge')).toBeNull();
await expect(canvas.getByText('3/5 reporting')).toBeVisible();
await userEvent.clear(input);
},
};
export const Mobile: Story = { args: { compact: true } };
export const RTL: Story = { args: { rtl: true }, globals: { theme: 'light' } };
File diff suppressed because it is too large Load Diff
+16 -12
View File
@@ -15,8 +15,6 @@ export default function NodeNetworkSpeed({
node: NodeRecord;
receivedAt?: number;
}) {
const { t } = useTranslation();
const { token } = theme.useToken();
const expiration =
receivedAt && node.heartbeatAgeMillis != null
? receivedAt + HEARTBEAT_FRESHNESS_MS - node.heartbeatAgeMillis
@@ -40,15 +38,26 @@ export default function NodeNetworkSpeed({
};
const fresh = useSyncExternalStore(subscribe, isFresh);
const available = node.enable && node.status === 'online' && !node.transitive && fresh;
return (
<NetworkSpeedValues
up={available && !node.unavailableMetrics?.includes('netUp') ? node.netUp : undefined}
down={available && !node.unavailableMetrics?.includes('netDown') ? node.netDown : undefined}
/>
);
}
export function NetworkSpeedValues({ up, down }: { up?: number | null; down?: number | null }) {
const { t } = useTranslation();
const { token } = theme.useToken();
const directions = [
{
key: 'netDown' as const,
rate: down,
label: t('pages.index.download'),
Icon: ArrowDownOutlined,
color: token.colorTextTertiary,
},
{
key: 'netUp' as const,
rate: up,
label: t('pages.index.upload'),
Icon: ArrowUpOutlined,
color: token.colorPrimary,
@@ -56,18 +65,13 @@ export default function NodeNetworkSpeed({
];
return (
<span className="node-network-speed">
{directions.map(({ key, label, Icon, color }) => {
const rate = node[key];
{directions.map(({ rate, label, Icon, color }) => {
const value =
available &&
!node.unavailableMetrics?.includes(key) &&
typeof rate === 'number' &&
Number.isFinite(rate) &&
rate >= 0
typeof rate === 'number' && Number.isFinite(rate) && rate >= 0
? SizeFormatter.speedFormat(rate)
: '—';
return (
<Tooltip key={key} title={label}>
<Tooltip key={label} title={label}>
<span
role="img"
aria-label={label + ' ' + value}
+25 -82
View File
@@ -4,30 +4,19 @@ import { useQuery } from '@tanstack/react-query';
import {
Alert,
Button,
Card,
Checkbox,
Col,
ConfigProvider,
Input,
Layout,
Modal,
Result,
Row,
Spin,
Statistic,
Typography,
message,
} from 'antd';
import {
CheckCircleOutlined,
CloseCircleOutlined,
CloudServerOutlined,
ThunderboltOutlined,
} from '@ant-design/icons';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useNodeOverviewQuery } from '@/api/queries/useNodesQuery';
import type { NodeRecord } from '@/api/queries/useNodesQuery';
import { useNodeMutations } from '@/api/queries/useNodeMutations';
import AppSidebar from '@/layouts/AppSidebar';
@@ -70,14 +59,15 @@ function UpdateChannelChoice({ onChange }: { onChange: (dev: boolean) => void })
export default function NodesPage() {
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { isMobile } = useMediaQuery();
const { isMobile } = useMediaQuery(1080);
const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage();
useEffect(() => {
setMessageInstance(messageApi);
}, [messageApi]);
const { nodes, nodesUpdatedAt, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
const { nodes, master, fleet, nodesUpdatedAt, loading, fetched, fetchError, refetch } =
useNodeOverviewQuery();
const {
create,
update,
@@ -360,74 +350,27 @@ export default function NodesPage() {
}
/>
) : (
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
<Col span={24}>
<Card size="small" hoverable className="summary-card">
<Row gutter={[16, isMobile ? 16 : 12]}>
<Col xs={12} sm={12} md={6}>
<Statistic
title={t('pages.nodes.totalNodes')}
value={String(totals.total)}
prefix={<CloudServerOutlined aria-hidden />}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<Statistic
title={t('pages.nodes.onlineNodes')}
value={String(totals.online)}
prefix={
<CheckCircleOutlined
aria-hidden
style={{ color: 'var(--ant-color-success)' }}
/>
}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<Statistic
title={t('pages.nodes.offlineNodes')}
value={String(totals.offline)}
prefix={
<CloseCircleOutlined
aria-hidden
style={{ color: 'var(--ant-color-error)' }}
/>
}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<Statistic
title={t('pages.nodes.avgLatency')}
value={totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'}
prefix={<ThunderboltOutlined aria-hidden />}
/>
</Col>
</Row>
</Card>
</Col>
<Col span={24}>
<NodeList
nodes={nodes}
nodesUpdatedAt={nodesUpdatedAt}
loading={loading}
isMobile={isMobile}
latestVersion={latestVersion}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
onAdd={onAdd}
onMtls={() => setMtlsOpen(true)}
onEdit={onEdit}
onDelete={onDelete}
onProbe={onProbe}
onToggleEnable={onToggleEnable}
onUpdateNode={onUpdateNode}
onUpdateSelected={onUpdateSelected}
onRestart={onRestart}
restartingIds={restartingIds}
/>
</Col>
</Row>
<NodeList
nodes={nodes}
master={master}
fleet={fleet}
nodesUpdatedAt={nodesUpdatedAt}
loading={loading}
isMobile={isMobile}
latestVersion={latestVersion}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
onAdd={onAdd}
onMtls={() => setMtlsOpen(true)}
onEdit={onEdit}
onDelete={onDelete}
onProbe={onProbe}
onToggleEnable={onToggleEnable}
onUpdateNode={onUpdateNode}
onUpdateSelected={onUpdateSelected}
onRestart={onRestart}
restartingIds={restartingIds}
/>
)}
</Spin>
</Layout.Content>
+103
View File
@@ -0,0 +1,103 @@
import { useCallback, useMemo, useState, useSyncExternalStore } from 'react';
import type { NodeTelemetry } from '@/generated/types';
const FRESHNESS_MS = 30_000;
function expires(sample: NodeTelemetry, receivedAt?: number) {
return receivedAt && sample.sampleAgeMillis != null
? receivedAt + FRESHNESS_MS - sample.sampleAgeMillis
: sample.sampledAt + FRESHNESS_MS;
}
export function freshTelemetry(
sample: NodeTelemetry | null | undefined,
now: number,
receivedAt?: number,
) {
if (!sample) return undefined;
const remaining = expires(sample, receivedAt) - now;
return remaining > 0 && remaining <= FRESHNESS_MS ? sample : undefined;
}
export function useTelemetryClock(
samples: readonly (NodeTelemetry | null | undefined)[],
receivedAt?: number,
) {
const [mountedAt] = useState(Date.now);
const deadlines = useMemo(
() =>
samples
.flatMap((sample) => (sample ? [expires(sample, receivedAt)] : []))
.sort((a, b) => a - b),
[samples, receivedAt],
);
const subscribe = useCallback(
(refresh: () => void) => {
let timer: number | undefined;
const schedule = () => {
const now = Date.now();
const deadline = deadlines.find((time) => time > now && time <= now + FRESHNESS_MS);
if (deadline !== undefined) {
timer = window.setTimeout(() => {
refresh();
schedule();
}, deadline - now);
}
};
schedule();
return () => window.clearTimeout(timer);
},
[deadlines],
);
const snapshot = () => {
const now = Date.now();
const latestExpiry = deadlines.reduce((last, time) => (time <= now ? time : last), 0);
return Math.max(mountedAt, receivedAt ?? 0, latestExpiry);
};
return useSyncExternalStore(subscribe, snapshot, snapshot);
}
export function aggregateTelemetry(samples: NodeTelemetry[]) {
const cpu = samples.filter((host) => host.cpuPct != null);
const memory = samples.filter(
(host) =>
host.memTotalBytes != null &&
host.memTotalBytes > 0 &&
host.memUsedBytes != null &&
host.memUsedBytes <= host.memTotalBytes,
);
function sum(key: keyof NodeTelemetry, hosts = samples) {
let total: number | undefined;
for (const sample of hosts) {
const value = sample[key];
if (typeof value === 'number') total = (total ?? 0) + value;
}
return total;
}
const telemetry: NodeTelemetry = {
sampledAt: 0,
cpuPct: cpu.length ? (sum('cpuPct', cpu) ?? 0) / cpu.length : undefined,
logicalCores: cpu.every((host) => host.logicalCores != null)
? sum('logicalCores', cpu)
: undefined,
memUsedBytes: sum('memUsedBytes', memory),
memTotalBytes: sum('memTotalBytes', memory),
memAvailableBytes: memory.every((host) => host.memAvailableBytes != null)
? sum('memAvailableBytes', memory)
: undefined,
netUp: sum('netUp'),
netDown: sum('netDown'),
tcpCount: sum('tcpCount'),
udpCount: sum('udpCount'),
load1: sum('load1'),
load5: sum('load5'),
load15: sum('load15'),
};
return { telemetry, cpuHosts: cpu.length, memoryHosts: memory.length };
}
export function reportingSample(sample: NodeTelemetry | null | undefined): sample is NodeTelemetry {
if (!sample) return false;
const { sampledAt: _time, sampleAgeMillis: _age, resourceScope: _scope, ...metrics } = sample;
return Object.values(metrics).some((metric) => typeof metric === 'number');
}
@@ -0,0 +1,93 @@
Copyright 2010-2018 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+7
View File
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { NodeFleetCountsSchema, NodeMasterViewSchema, NodeTelemetrySchema } from '@/generated/zod';
export const NodeRecordSchema = z
.object({
@@ -23,6 +24,7 @@ export const NodeRecordSchema = z
panelVersion: z.string().optional(),
uptimeSecs: z.number().optional(),
unavailableMetrics: z.array(z.string()).optional(),
telemetry: NodeTelemetrySchema.optional(),
inboundCount: z.number().optional(),
clientCount: z.number().optional(),
onlineCount: z.number().optional(),
@@ -54,6 +56,11 @@ export const NodeRecordSchema = z
.loose();
export const NodeListSchema = z.array(NodeRecordSchema);
export const NodeOverviewSchema = z.object({
nodes: NodeListSchema,
master: NodeMasterViewSchema,
fleet: NodeFleetCountsSchema,
});
export const ProbeResultSchema = z
.object({
@@ -0,0 +1,114 @@
import { act, fireEvent, screen, within } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import NodeList from '@/pages/nodes/NodeList';
import type { NodeRecord } from '@/schemas/node';
import { renderWithProviders } from './test-utils';
const counts = {
inboundCount: 1,
clientCount: 2,
activeCount: 2,
disabledCount: 0,
depletedCount: 0,
onlineCount: 1,
};
const noop = () => {};
const actions = {
onAdd: noop,
onMtls: noop,
onEdit: noop,
onDelete: noop,
onProbe: noop,
onToggleEnable: noop,
onUpdateNode: noop,
onUpdateSelected: noop,
onRestart: noop,
};
it('keeps the master visible on an empty install and adds the summary for a disabled remote', () => {
function list(nodes: NodeRecord[]) {
return (
<NodeList
{...actions}
nodes={nodes}
master={{ counts }}
fleet={counts}
selectedIds={[]}
onSelectionChange={noop}
/>
);
}
const view = renderWithProviders(list([]));
expect(screen.queryByText('All nodes')).toBeNull();
expect(screen.getByRole('row', { name: /This panel/ })).toBeTruthy();
expect(screen.queryByRole('switch')).toBeNull();
view.rerender(list([{ id: 1, name: 'disabled edge', enable: false, status: 'online' }]));
const rows = screen.getAllByRole('row');
expect(rows[1].textContent).toContain('All nodes');
expect(rows[1].textContent).toContain('0/2 reporting');
expect(rows[2].textContent).toContain('Master');
expect(rows[3].textContent).toContain('disabled edge');
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'unmatched' } });
expect(screen.getAllByRole('row')).toHaveLength(3);
expect(screen.getByText('0/2 reporting')).toBeTruthy();
});
it('expires only the stale host and keeps weighted RAM and live byte rates separate', () => {
vi.useFakeTimers();
try {
const now = Date.now();
renderWithProviders(
<NodeList
{...actions}
selectedIds={[]}
onSelectionChange={noop}
nodesUpdatedAt={now}
nodes={[
{
id: 1,
name: 'edge',
enable: true,
status: 'online',
telemetry: {
sampledAt: now - 29_500,
sampleAgeMillis: 29_500,
memUsedBytes: 4 * 2 ** 30,
memTotalBytes: 16 * 2 ** 30,
netDown: 1024,
tcpCount: 0,
cpuPct: 20,
logicalCores: 4,
},
},
]}
master={{
counts,
telemetry: {
sampledAt: now,
sampleAgeMillis: 0,
memUsedBytes: 6 * 2 ** 30,
memTotalBytes: 8 * 2 ** 30,
cpuPct: 40,
logicalCores: 8,
netDown: 2048,
tcpCount: 10,
},
}}
fleet={counts}
/>,
);
const fleet = () => within(screen.getByRole('row', { name: /All nodes/ }));
expect(fleet().getByText(/10.00 GB \/ 24.00 GB · 41.7%/)).toBeTruthy();
expect(fleet().getByText('30.0%')).toBeTruthy();
expect(fleet().getByLabelText(/download 3.00 KB\/s/i)).toBeTruthy();
act(() => vi.advanceTimersByTime(501));
expect(fleet().getByText('1/2 reporting')).toBeTruthy();
expect(fleet().getByText('40.0%')).toBeTruthy();
expect(fleet().getByLabelText(/download 2.00 KB\/s/i)).toBeTruthy();
expect(
within(screen.getByRole('row', { name: /edge/ })).getByLabelText(/download —/i),
).toBeTruthy();
} finally {
vi.useRealTimers();
}
});
@@ -1,4 +1,4 @@
import { screen, within } from '@testing-library/react';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
@@ -70,11 +70,9 @@ describe('NodeList online total', () => {
expect(screen.queryByText(/\d \/ \d/)).toBeNull();
});
it('shows synced / total in the mobile stats dialog', async () => {
it('shows synced / total directly on the mobile row', () => {
renderNode({ onlineCount: 3, onlineTotalCount: 12 }, true);
await userEvent.click(screen.getByRole('button', { name: 'More Information' }));
expect(within(await screen.findByRole('dialog')).getByText('3 / 12 Online')).toBeTruthy();
expect(screen.getByText('3 / 12')).toBeTruthy();
});
});
@@ -38,7 +38,6 @@ describe('node metric availability', () => {
onRestart={noop}
/>,
);
if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
expect(screen.queryByText('0.0%')).toBeNull();
expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);
},
@@ -49,9 +48,7 @@ describe('node metric availability', () => {
name: 'edge',
status: 'online',
enable: true,
cpuPct: 0,
memPct: 44.4,
uptimeSecs: 0,
telemetry: { sampledAt: Date.now(), cpuPct: 0 },
});
renderWithProviders(
<NodeList
@@ -70,9 +67,8 @@ describe('node metric availability', () => {
/>,
);
expect(screen.getByText('0.0%')).not.toBeNull();
const headers = screen.getAllByRole('columnheader').map((h) => h.textContent);
const cells = within(screen.getAllByRole('row')[1]).getAllByRole('cell');
expect(cells[headers.indexOf('Uptime')].textContent).toBe('-');
const cell = within(screen.getAllByRole('row')[1]).getByText(/Uptime/);
expect(cell.textContent).toBe('Uptime · —');
});
});
@@ -99,8 +95,7 @@ describe('node network speed', () => {
enable: true,
status: 'online',
lastHeartbeat: Math.floor(Date.now() / 1000),
netDown: 2048,
netUp: 0,
telemetry: { sampledAt: Date.now(), netDown: 2048, netUp: 0 },
});
function Fixture() {
const [record, setRecord] = useState(node);
@@ -109,7 +104,10 @@ describe('node network speed', () => {
<button
type="button"
onClick={() =>
setRecord({ ...record, lastHeartbeat: (node.lastHeartbeat ?? 0) - 120 })
setRecord({
...record,
telemetry: { sampledAt: Date.now() - 120_000, netDown: 2048, netUp: 0 },
})
}
>
Age sample
@@ -119,10 +117,8 @@ describe('node network speed', () => {
);
}
renderWithProviders(<Fixture />);
if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
expect(screen.getByLabelText(/^upload .*0 B\/s$/i).textContent).toContain('0 B/s');
// A heartbeat cache update must also refresh the open mobile stats dialog.
fireEvent.click(screen.getByText('Age sample'));
expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
},
+1 -11
View File
@@ -15,22 +15,12 @@ const state = vi.hoisted(() => ({
vi.mock('@/hooks/useMediaQuery', () => ({ useMediaQuery: () => ({ isMobile: state.isMobile }) }));
vi.mock('@/api/queries/useNodesQuery', () => ({
useNodesQuery: () => ({
useNodeOverviewQuery: () => ({
nodes: state.nodes,
loading: false,
fetched: true,
fetchError: '',
refetch: state.refetch,
totals: {
total: state.nodes.length,
online: 0,
offline: 1,
avgLatency: 0,
inbounds: 0,
clients: 0,
onlineClients: 0,
depleted: 0,
},
}),
}));
vi.mock('@/pages/nodes/NodeFormModal', () => ({ default: () => null }));
+10 -6
View File
@@ -922,10 +922,11 @@ type Node struct {
MemPct float64 `json:"memPct" example:"45.1"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
// Nil on legacy rows and responses: zero remains a valid measured value.
UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
LastError string `json:"lastError"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
Telemetry *NodeTelemetry `json:"telemetry,omitempty" gorm:"serializer:json;type:text"`
NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
LastError string `json:"lastError"`
// XrayState and XrayError are captured from the remote node's /panel/api/server/status
// during heartbeats. They let the central panel distinguish "panel API reachable"
@@ -980,8 +981,11 @@ type NodeSummary struct {
PanelVersion string `json:"panelVersion"`
XrayVersion string `json:"xrayVersion"`
// XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
XrayState string `json:"xrayState"`
XrayError string `json:"xrayError,omitempty"`
XrayState string `json:"xrayState"`
XrayError string `json:"xrayError,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
BasePath string `json:"basePath,omitempty"`
Telemetry *NodeTelemetry `json:"telemetry,omitempty"`
}
type ClientReverse struct {
+22
View File
@@ -0,0 +1,22 @@
package model
// NodeTelemetry describes one host sample. Nil metrics were not measured.
type NodeTelemetry struct {
SampledAt int64 `json:"sampledAt" example:"1700000000000"`
SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
ResourceScope string `json:"resourceScope,omitempty" example:"container"`
CpuPct *float64 `json:"cpuPct,omitempty" example:"12.5"`
PhysicalCores *int `json:"physicalCores,omitempty" example:"4"`
LogicalCores *int `json:"logicalCores,omitempty" example:"8"`
MemUsedBytes *uint64 `json:"memUsedBytes,omitempty" example:"2147483648"`
MemTotalBytes *uint64 `json:"memTotalBytes,omitempty" example:"4294967296"`
MemAvailableBytes *uint64 `json:"memAvailableBytes,omitempty" example:"1073741824"`
TCPCount *int `json:"tcpCount,omitempty" example:"75"`
UDPCount *int `json:"udpCount,omitempty" example:"12"`
Load1 *float64 `json:"load1,omitempty" example:"0.25"`
Load5 *float64 `json:"load5,omitempty" example:"0.18"`
Load15 *float64 `json:"load15,omitempty" example:"0.12"`
UptimeSecs *uint64 `json:"uptimeSecs,omitempty" example:"3600"`
NetUp *uint64 `json:"netUp,omitempty" example:"1024"`
NetDown *uint64 `json:"netDown,omitempty" example:"2048"`
}
+5
View File
@@ -38,6 +38,10 @@ func NewAPIController(g *gin.RouterGroup, router http.Handler) *APIController {
return a
}
func (a *APIController) LastStatus() *service.Status {
return a.serverController.serverService.LastStatus()
}
// requireMCPEnabled hides the MCP endpoint until the operator turns it on: it hands
// a token's whole API reach to whatever agent holds that token.
func (a *APIController) requireMCPEnabled(c *gin.Context) {
@@ -236,6 +240,7 @@ func (a *APIController) initRouter(g *gin.RouterGroup, router http.Handler) {
// Nodes API — multi-panel management
nodes := api.Group("/nodes")
a.nodeController = NewNodeController(nodes)
a.nodeController.localStatus = a.LastStatus
// Hosts API — per-inbound override endpoints for subscription links
hosts := api.Group("/hosts")
+11
View File
@@ -18,6 +18,7 @@ import (
type NodeController struct {
nodeService service.NodeService
xrayService service.XrayService
localStatus func() *service.Status
}
func NewNodeController(g *gin.RouterGroup) *NodeController {
@@ -28,6 +29,7 @@ func NewNodeController(g *gin.RouterGroup) *NodeController {
func (a *NodeController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/overview", a.overview)
g.GET("/get/:id", a.get)
g.GET("/webCert/:id", a.webCert)
@@ -112,6 +114,15 @@ func (a *NodeController) get(c *gin.Context) {
jsonObj(c, n, nil)
}
func (a *NodeController) overview(c *gin.Context) {
var local *service.Status
if a.localStatus != nil {
local = a.localStatus()
}
view, err := a.nodeService.GetNodeOverview(local)
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.list"), view, err)
}
// webCert returns the node's own web TLS certificate/key file paths so the
// inbound form's "Set Cert from Panel" can fill paths that exist on the node.
func (a *NodeController) webCert(c *gin.Context) {
+3 -1
View File
@@ -110,7 +110,9 @@ func (a *ServerController) startTask() {
}
// status returns the current server status information.
func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.serverService.CurrentStatus(), nil) }
func (a *ServerController) status(c *gin.Context) {
jsonObj(c, service.StatusWithSampleAge(a.serverService.CurrentStatus()), nil)
}
func (a *ServerController) getFail2banStatus(c *gin.Context) {
jsonObj(c, a.serverService.GetFail2banStatus(), nil)
+12 -5
View File
@@ -31,6 +31,7 @@ type NodeHeartbeatJob struct {
settingService service.SettingService
running sync.Mutex
health map[int]nodeHealth
localStatus func() *service.Status
}
type nodeHealth struct {
@@ -47,6 +48,10 @@ func NewNodeHeartbeatJob() *NodeHeartbeatJob {
return &NodeHeartbeatJob{}
}
func (j *NodeHeartbeatJob) SetLocalStatusSource(read func() *service.Status) {
j.localStatus = read
}
func (j *NodeHeartbeatJob) Run() {
if !j.running.TryLock() {
return
@@ -59,9 +64,6 @@ func (j *NodeHeartbeatJob) Run() {
return
}
j.nodeService.RetainEnabledNodeDescendants(nodes)
if len(nodes) == 0 {
return
}
sem := make(chan struct{}, nodeHeartbeatConcurrency)
var wg sync.WaitGroup
@@ -89,12 +91,17 @@ func (j *NodeHeartbeatJob) Run() {
if !websocket.HasClients() {
return
}
updated, err := j.nodeService.GetNodeTreeView()
var local *service.Status
if j.localStatus != nil {
local = j.localStatus()
}
updated, err := j.nodeService.GetNodeOverview(local)
if err != nil {
logger.Warning("node heartbeat: load nodes for broadcast failed:", err)
return
}
websocket.BroadcastNodes(updated)
websocket.BroadcastNodes(updated.Nodes)
websocket.BroadcastNodesOverview(updated)
}
func (j *NodeHeartbeatJob) probeOne(n *model.Node) service.HeartbeatPatch {
+25 -171
View File
@@ -42,6 +42,7 @@ type HeartbeatPatch struct {
MemPct float64
UptimeSecs uint64
UnavailableMetrics []string
Telemetry *model.NodeTelemetry
// NetUp/NetDown are the node's current interface throughput (bytes/sec),
// summed over non-virtual interfaces, read from its status response.
NetUp uint64
@@ -138,154 +139,6 @@ func (s *NodeService) ListOperational() ([]*model.Node, error) {
return nodes, nil
}
func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) {
type clientCountRow struct {
NodeID int `gorm:"column:node_id"`
Count int `gorm:"column:count"`
}
var clientCounts []clientCountRow
if err := db.Raw(`
SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
FROM inbounds
JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
WHERE inbounds.node_id IS NOT NULL
GROUP BY inbounds.node_id
`).Scan(&clientCounts).Error; err == nil {
for _, row := range clientCounts {
for _, n := range nodes {
if n.Id == row.NodeID {
n.ClientCount = row.Count
break
}
}
}
}
}
func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) {
// Set before the early returns: a node with nothing synced still has clients online.
onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
for _, n := range nodes {
n.OnlineTotalCount = onlineTotals[n.Id]
}
type inboundRow struct {
Id int
NodeID int `gorm:"column:node_id"`
}
var inboundRows []inboundRow
if err := db.Table("inbounds").
Select("id, node_id").
Where("node_id IS NOT NULL").
Scan(&inboundRows).Error; err != nil {
return
}
if len(inboundRows) == 0 {
return
}
inboundsByNode := make(map[int][]int, len(nodes))
for _, row := range inboundRows {
inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
}
s.populateClientCounts(db, nodes)
depletedByNode := make(map[int]int)
disabledByNode := make(map[int]int)
activeByNode := make(map[int]int)
statuses, _ := s.nodeClientStatuses()
seen := make(map[int]map[int]struct{}, len(nodes))
for _, st := range statuses {
clientsSeen := seen[st.NodeID]
if clientsSeen == nil {
clientsSeen = make(map[int]struct{})
seen[st.NodeID] = clientsSeen
}
if _, dup := clientsSeen[st.ClientID]; dup {
// A client attached to several inbounds of one node counts once,
// matching the distinct ClientCount above.
continue
}
clientsSeen[st.ClientID] = struct{}{}
switch {
case st.Depleted:
depletedByNode[st.NodeID]++
case st.Disabled:
disabledByNode[st.NodeID]++
default:
activeByNode[st.NodeID]++
}
}
onlineByGuid := s.onlineEmailsByGuid()
selfGuid, _ := (&SettingService{}).GetPanelGuid()
ambiguous := ambiguousNodeGuids(nodes, selfGuid)
for _, n := range nodes {
n.InboundCount = len(inboundsByNode[n.Id])
n.DepletedCount = depletedByNode[n.Id]
n.DisabledCount = disabledByNode[n.Id]
n.ActiveCount = activeByNode[n.Id]
// Online is attributed to the node that physically hosts the client
// (by GUID): a client on a sub-node counts under the sub-node, not
// the intermediate node it syncs through (#4983).
n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
}
}
// nodeClientStatus is one node-hosted client's classification, carrying enough
// identity for callers to bucket it by node id or by attribution GUID.
type nodeClientStatus struct {
InboundID int
NodeID int
ClientID int
Depleted bool
Disabled bool
}
// nodeClientStatuses classifies every client attached to a node-hosted inbound as
// depleted / disabled / active, matching client_traffics by EMAIL rather than by
// inbound_id. client_traffics.inbound_id goes stale after an inbound is
// delete+recreated, so filtering by it silently drops most rows; the
// client_inbounds -> clients join is the reliable client set and the email join
// pulls each client's live counters. Precedence matches the inbound page:
// depleted (expired/exhausted) wins over disabled.
func (s *NodeService) nodeClientStatuses() ([]nodeClientStatus, error) {
type row struct {
InboundID int `gorm:"column:inbound_id"`
NodeID int `gorm:"column:node_id"`
ClientID int `gorm:"column:client_id"`
Enable bool `gorm:"column:enable"`
Total int64 `gorm:"column:total"`
Up int64 `gorm:"column:up"`
Down int64 `gorm:"column:down"`
ExpiryTime int64 `gorm:"column:expiry_time"`
}
var rows []row
if err := database.GetDB().Table("inbounds").
Select("inbounds.id AS inbound_id, inbounds.node_id AS node_id, clients.id AS client_id, " +
"clients.enable AS enable, ct.total AS total, ct.up AS up, ct.down AS down, ct.expiry_time AS expiry_time").
Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
Joins("LEFT JOIN client_traffics ct ON ct.email = clients.email").
Where("inbounds.node_id IS NOT NULL").
Scan(&rows).Error; err != nil {
return nil, err
}
now := time.Now().UnixMilli()
out := make([]nodeClientStatus, 0, len(rows))
for _, r := range rows {
st := nodeClientStatus{InboundID: r.InboundID, NodeID: r.NodeID, ClientID: r.ClientID}
expired := r.ExpiryTime > 0 && r.ExpiryTime <= now
exhausted := r.Total > 0 && r.Up+r.Down >= r.Total
switch {
case expired || exhausted:
st.Depleted = true
case !r.Enable:
st.Disabled = true
}
out = append(out, st)
}
return out, nil
}
func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
svc := InboundService{}
byGuid := svc.GetOnlineClientsByGuid()
@@ -1000,8 +853,13 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
if err != nil {
return err
}
telemetry, err := json.Marshal(p.Telemetry)
if err != nil {
return err
}
updates := map[string]any{
"unavailable_metrics": string(unavailable),
"telemetry": string(telemetry),
"status": p.Status,
"last_heartbeat": p.LastHeartbeat,
"latency_ms": p.LatencyMs,
@@ -1027,7 +885,7 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
}
if p.Status == "online" {
now := time.Unix(p.LastHeartbeat, 0)
if !slices.Contains(p.UnavailableMetrics, "cpu") {
if !slices.Contains(p.UnavailableMetrics, "cpu") && (p.Telemetry == nil || p.Telemetry.CpuPct != nil) {
nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
}
nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
@@ -1368,21 +1226,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
Success bool `json:"success"`
Msg string `json:"msg"`
Obj *struct {
CpuPct float64 `json:"cpu"`
UnavailableMetrics []string `json:"unavailableMetrics"`
Mem struct {
Current uint64 `json:"current"`
Total uint64 `json:"total"`
} `json:"mem"`
nodeStatusMetrics
Xray struct {
Version string `json:"version"`
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
} `json:"xray"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
Uptime uint64 `json:"uptime"`
NetIO json.RawMessage `json:"netIO"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
} `json:"obj"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
@@ -1400,10 +1251,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
o := envelope.Obj
patch.CpuPct = o.CpuPct
patch.UnavailableMetrics = o.UnavailableMetrics
if o.Mem.Total > 0 {
patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
sample := o.telemetry(time.Now())
patch.Telemetry = sample
if sample.CpuPct != nil {
patch.CpuPct = *sample.CpuPct
}
if sample.MemTotalBytes != nil && sample.MemUsedBytes != nil {
patch.MemPct = float64(*sample.MemUsedBytes) * 100 / float64(*sample.MemTotalBytes)
}
patch.XrayVersion = o.Xray.Version
patch.XrayState = o.Xray.State
@@ -1414,16 +1269,15 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
patch.Guid = o.PanelGuid
patch.UptimeSecs = o.Uptime
var network map[string]json.RawMessage
_ = json.Unmarshal(o.NetIO, &network)
if sample.UptimeSecs != nil {
patch.UptimeSecs = *sample.UptimeSecs
}
for _, metric := range []struct {
key, direction string
value *uint64
}{{"netUp", "up", &patch.NetUp}, {"netDown", "down", &patch.NetDown}} {
var value *uint64
if json.Unmarshal(network[metric.direction], &value) == nil && value != nil {
*metric.value = *value
key string
value, measured *uint64
}{{"netUp", &patch.NetUp, sample.NetUp}, {"netDown", &patch.NetDown, sample.NetDown}} {
if metric.measured != nil {
*metric.value = *metric.measured
} else if !slices.Contains(patch.UnavailableMetrics, metric.key) {
patch.UnavailableMetrics = append(patch.UnavailableMetrics, metric.key)
}
+47 -44
View File
@@ -2,6 +2,7 @@ package service
import (
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
@@ -10,50 +11,51 @@ import (
// NodeView is the browser/API read contract for nodes. Credentials are
// write-only: responses expose only whether a node has a token configured.
type NodeView struct {
Id int `json:"id" example:"1"`
Name string `json:"name" example:"edge-1"`
Remark string `json:"remark" example:"Primary edge"`
Scheme string `json:"scheme" example:"https"`
Address string `json:"address" example:"node.example.com"`
Port int `json:"port" example:"2053"`
BasePath string `json:"basePath" example:"/"`
HasApiToken bool `json:"hasApiToken" example:"true"`
Enable bool `json:"enable" example:"true"`
AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
InboundSyncMode string `json:"inboundSyncMode" example:"all"`
InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
OutboundTag string `json:"outboundTag" example:"direct"`
Guid string `json:"guid" example:"node-guid"`
Status string `json:"status" example:"online"`
LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
LatencyMs int `json:"latencyMs" example:"42"`
XrayVersion string `json:"xrayVersion" example:"25.10.31"`
PanelVersion string `json:"panelVersion" example:"v3.x.x"`
CpuPct float64 `json:"cpuPct" example:"12.5"`
MemPct float64 `json:"memPct" example:"45.2"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
NetUp uint64 `json:"netUp" example:"2097152"`
NetDown uint64 `json:"netDown" example:"1048576"`
LastError string `json:"lastError" example:""`
XrayState string `json:"xrayState" example:"running"`
XrayError string `json:"xrayError" example:""`
ConfigDirty bool `json:"configDirty" example:"false"`
ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
InboundCount int `json:"inboundCount" example:"3"`
ClientCount int `json:"clientCount" example:"25"`
OnlineCount int `json:"onlineCount" example:"5"`
OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
ActiveCount int `json:"activeCount" example:"20"`
DisabledCount int `json:"disabledCount" example:"2"`
DepletedCount int `json:"depletedCount" example:"1"`
ParentGuid string `json:"parentGuid,omitempty" example:""`
Transitive bool `json:"transitive,omitempty" example:"false"`
CreatedAt int64 `json:"createdAt" example:"1700000000"`
UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
Id int `json:"id" example:"1"`
Name string `json:"name" example:"edge-1"`
Remark string `json:"remark" example:"Primary edge"`
Scheme string `json:"scheme" example:"https"`
Address string `json:"address" example:"node.example.com"`
Port int `json:"port" example:"2053"`
BasePath string `json:"basePath" example:"/"`
HasApiToken bool `json:"hasApiToken" example:"true"`
Enable bool `json:"enable" example:"true"`
AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
InboundSyncMode string `json:"inboundSyncMode" example:"all"`
InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
OutboundTag string `json:"outboundTag" example:"direct"`
Guid string `json:"guid" example:"node-guid"`
Status string `json:"status" example:"online"`
LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
LatencyMs int `json:"latencyMs" example:"42"`
XrayVersion string `json:"xrayVersion" example:"25.10.31"`
PanelVersion string `json:"panelVersion" example:"v3.x.x"`
CpuPct float64 `json:"cpuPct" example:"12.5"`
MemPct float64 `json:"memPct" example:"45.2"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
NetUp uint64 `json:"netUp" example:"2097152"`
NetDown uint64 `json:"netDown" example:"1048576"`
LastError string `json:"lastError" example:""`
XrayState string `json:"xrayState" example:"running"`
XrayError string `json:"xrayError" example:""`
ConfigDirty bool `json:"configDirty" example:"false"`
ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
InboundCount int `json:"inboundCount" example:"3"`
ClientCount int `json:"clientCount" example:"25"`
OnlineCount int `json:"onlineCount" example:"5"`
OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
ActiveCount int `json:"activeCount" example:"20"`
DisabledCount int `json:"disabledCount" example:"2"`
DepletedCount int `json:"depletedCount" example:"1"`
ParentGuid string `json:"parentGuid,omitempty" example:""`
Transitive bool `json:"transitive,omitempty" example:"false"`
CreatedAt int64 `json:"createdAt" example:"1700000000"`
UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
}
func toNodeView(n *model.Node) *NodeView {
@@ -86,6 +88,7 @@ func toNodeView(n *model.Node) *NodeView {
MemPct: n.MemPct,
UptimeSecs: n.UptimeSecs,
UnavailableMetrics: n.UnavailableMetrics,
Telemetry: liveNodeTelemetry(n, time.Now()),
NetUp: n.NetUp,
NetDown: n.NetDown,
LastError: n.LastError,
+152
View File
@@ -0,0 +1,152 @@
package service
import (
"encoding/json"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
type NodeFleetCounts struct {
InboundCount int `json:"inboundCount" example:"8"`
ClientCount int `json:"clientCount" example:"100"`
ActiveCount int `json:"activeCount" example:"90"`
DisabledCount int `json:"disabledCount" example:"8"`
DepletedCount int `json:"depletedCount" example:"2"`
OnlineCount int `json:"onlineCount" example:"20"`
}
type NodeMasterView struct {
Counts NodeFleetCounts `json:"counts"`
Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
XrayVersion string `json:"xrayVersion,omitempty" example:"26.1.1"`
PanelVersion string `json:"panelVersion,omitempty" example:"v3.12.0"`
XrayState string `json:"xrayState,omitempty" example:"running"`
XrayError string `json:"xrayError,omitempty"`
}
type NodeOverview struct {
Nodes []*NodeView `json:"nodes"`
Master NodeMasterView `json:"master"`
Fleet NodeFleetCounts `json:"fleet"`
}
func (s *NodeService) GetNodeOverview(local *Status) (*NodeOverview, error) {
nodes, master, fleet, err := s.getNodeTreeWithCounts()
if err != nil {
return nil, err
}
overview := &NodeOverview{Nodes: nodeTreeViews(nodes), Master: NodeMasterView{Counts: master}, Fleet: fleet}
if local != nil {
overview.Master.XrayVersion = local.Xray.Version
overview.Master.PanelVersion = local.PanelVersion
overview.Master.XrayState = string(local.Xray.State)
overview.Master.XrayError = local.Xray.ErrorMsg
// Use the same typed projection and availability checks as remote heartbeats.
if payload, err := json.Marshal(local); err == nil {
var metrics nodeStatusMetrics
if json.Unmarshal(payload, &metrics) == nil && !local.T.IsZero() {
overview.Master.Telemetry = liveNodeTelemetry(&model.Node{
Enable: true, Status: "online", Telemetry: metrics.telemetry(local.T),
}, time.Now())
}
}
}
return overview, nil
}
type nodeFleetStatsRow struct {
Fleet int
Host string
NodeFleetCounts
}
func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (NodeFleetCounts, NodeFleetCounts, error) {
ambiguous := ambiguousNodeGuids(nodes, selfGUID)
// Always reserve the local GUID, including when an old topology advertises a loop.
ambiguous[selfGUID] = struct{}{}
ambiguous[""] = struct{}{}
ambiguousGUIDs := make([]string, 0, len(ambiguous))
for guid := range ambiguous {
ambiguousGUIDs = append(ambiguousGUIDs, guid)
}
slices.Sort(ambiguousGUIDs)
var rows []nodeFleetStatsRow
err := database.GetDB().Raw(`
WITH hosted AS (
SELECT i.id, CASE
WHEN i.node_id IS NULL THEN ''
WHEN COALESCE(i.origin_node_guid, '') NOT IN ? THEN i.origin_node_guid
WHEN COALESCE(i.origin_node_guid, '') = '' AND COALESCE(n.guid, '') NOT IN ? THEN n.guid
ELSE 'node:' || CAST(i.node_id AS TEXT)
END AS host
FROM inbounds i LEFT JOIN nodes n ON n.id = i.node_id
), memberships AS (
SELECT DISTINCT hosted.host, ci.client_id
FROM hosted JOIN client_inbounds ci ON ci.inbound_id = hosted.id
), scoped AS (
SELECT 0 AS fleet, host, client_id FROM memberships
UNION ALL SELECT 1, '', id FROM clients
), classified AS (
SELECT s.fleet, s.host, CASE
WHEN (ct.expiry_time > 0 AND ct.expiry_time <= ?)
OR (ct.total > 0 AND ct.up + ct.down >= ct.total) THEN 'depleted'
WHEN COALESCE(c.enable, FALSE) = FALSE THEN 'disabled'
ELSE 'active' END AS state
FROM scoped s JOIN clients c ON c.id = s.client_id
LEFT JOIN client_traffics ct ON ct.email = c.email
), clients_by_host AS (
SELECT fleet, host, COUNT(*) AS client_count,
COUNT(*) FILTER (WHERE state = 'active') AS active_count,
COUNT(*) FILTER (WHERE state = 'disabled') AS disabled_count,
COUNT(*) FILTER (WHERE state = 'depleted') AS depleted_count
FROM classified GROUP BY fleet, host
), inbound_counts AS (
SELECT 0 AS fleet, host, COUNT(*) AS inbound_count FROM hosted GROUP BY host
UNION ALL SELECT 1, '', COUNT(*) FROM hosted
)
SELECT i.fleet, i.host, i.inbound_count, c.client_count, c.active_count, c.disabled_count, c.depleted_count
FROM inbound_counts i LEFT JOIN clients_by_host c ON c.fleet = i.fleet AND c.host = i.host
`, ambiguousGUIDs, ambiguousGUIDs, time.Now().UnixMilli()).Scan(&rows).Error
if err != nil {
return NodeFleetCounts{}, NodeFleetCounts{}, err
}
byHost := make(map[string]NodeFleetCounts, len(rows))
var fleet NodeFleetCounts
for _, row := range rows {
if row.Fleet == 1 {
fleet = row.NodeFleetCounts
} else {
byHost[row.Host] = row.NodeFleetCounts
}
}
master := byHost[""]
online := s.onlineEmailsByGuid()
uniqueOnline := make(map[string]struct{})
if process := currentXrayProcess(); process != nil {
for _, email := range process.GetLocalOnlineClients() {
uniqueOnline[email] = struct{}{}
}
}
master.OnlineCount = len(uniqueOnline)
totalOnline := (&InboundService{}).GetNodeOnlineTotals()
for _, node := range nodes {
guid := effectiveNodeGuid(node, ambiguous)
stats := byHost[guid]
node.InboundCount = stats.InboundCount
node.ClientCount = stats.ClientCount
node.ActiveCount = stats.ActiveCount
node.DisabledCount = stats.DisabledCount
node.DepletedCount = stats.DepletedCount
node.OnlineCount = len(online[guid])
node.OnlineTotalCount = totalOnline[node.Id]
for email := range online[guid] {
uniqueOnline[email] = struct{}{}
}
}
fleet.OnlineCount = len(uniqueOnline)
return master, fleet, nil
}
+240
View File
@@ -0,0 +1,240 @@
package service
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"testing"
"time"
"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/testpg"
)
func TestNodeHeartbeatPublishesTelemetry(t *testing.T) {
svc, node, response := availabilityNodeFixture(t, `{"success":true,"obj":{"cpu":0,"cpuCores":4,"logicalPro":8,"mem":{"current":0,"total":4294967296},"tcpCount":0,"udpCount":7,"loads":[0,0.25,1.5],"netIO":{"up":0,"down":100}}}`)
read := func() map[string]any {
t.Helper()
patch, err := svc.Probe(t.Context(), node)
if err != nil {
t.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(node.Id, patch); err != nil {
t.Fatal(err)
}
nodes, err := svc.GetNodeTreeView()
if err != nil || len(nodes) != 1 {
t.Fatalf("views: %v, %v", nodes, err)
}
data, err := json.Marshal(nodes[0])
if err != nil {
t.Fatal(err)
}
var view struct{ Telemetry map[string]any }
if err := json.Unmarshal(data, &view); err != nil {
t.Fatal(err)
}
return view.Telemetry
}
first := read()
for key, want := range map[string]float64{"cpuPct": 0, "physicalCores": 4, "logicalCores": 8, "memUsedBytes": 0, "memTotalBytes": 4294967296, "tcpCount": 0, "udpCount": 7, "load1": 0, "load5": 0.25, "load15": 1.5, "netUp": 0, "netDown": 100} {
if got := first[key]; got != want {
t.Errorf("%s = %v, want %v", key, got, want)
}
}
response(`{"success":true,"obj":{"cpu":0,"resourceScope":"container","cpuCores":4,"logicalPro":2,"unavailableMetrics":["cpu","tcpCount"],"tcpCount":0,"loads":[1e999,-1,0]}}`)
partial := read()
for _, field := range []string{"cpuPct", "physicalCores", "tcpCount", "udpCount", "memUsedBytes", "load1", "load5", "netUp"} {
if got := partial[field]; got != nil {
t.Errorf("unavailable %s = %v", field, got)
}
}
if partial["logicalCores"] != float64(2) || partial["load15"] != float64(0) {
t.Fatalf("lost valid partial metrics: %v", partial)
}
if err := svc.UpdateHeartbeat(node.Id, HeartbeatPatch{Status: "offline", LastHeartbeat: time.Now().Unix()}); err != nil {
t.Fatal(err)
}
view, err := svc.GetViewById(node.Id)
if err != nil || view.Status != "offline" || view.Telemetry != nil {
t.Fatalf("offline transition: %+v, %v", view, err)
}
response(`{"success":true,"obj":{"sampleAgeMillis":31000,"cpu":5}}`)
if stale := read(); stale != nil {
t.Fatalf("stale sample treated as live: %v", stale)
}
response(`{"success":true,"obj":{"cpu":5}}`)
if recovered := read(); recovered["cpuPct"] != float64(5) || recovered["tcpCount"] != nil {
t.Fatalf("legacy node recovery: %v", recovered)
}
}
func TestNodeOverviewCountsHostMembershipsAndUniqueFleetClients(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_counts")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet.db"))
db := database.GetDB()
self, err := (&SettingService{}).GetPanelGuid()
if err != nil {
t.Fatal(err)
}
nodes := []model.Node{
{Name: "direct", Address: "192.0.2.1", Port: 2053, Guid: "direct"},
{Name: "cloned", Address: "192.0.2.2", Port: 2053, Guid: self},
}
if err := db.Create(&nodes).Error; err != nil {
t.Fatal(err)
}
nodeDescendantsMu.Lock()
nodeDescendantsCache[nodes[0].Id] = []model.NodeSummary{
{
Guid: "child", ParentGuid: "direct", Name: "child", Status: "online",
Telemetry: &model.NodeTelemetry{SampledAt: time.Now().UnixMilli(), UDPCount: new(0)},
},
}
nodeDescendantsMu.Unlock()
t.Cleanup(func() { (&NodeService{}).ClearDescendants(nodes[0].Id) })
createInbound := func(tag string, nodeID *int, guid string) model.Inbound {
t.Helper()
ib := model.Inbound{Tag: tag, Port: 443, NodeID: nodeID, OriginNodeGuid: guid, Settings: `{"clients":[]}`}
if err := db.Create(&ib).Error; err != nil {
t.Fatal(err)
}
return ib
}
local := createInbound("local", nil, self)
direct := createInbound("direct", &nodes[0].Id, "direct")
child := createInbound("child", &nodes[0].Id, "child")
clone := createInbound("clone", &nodes[1].Id, self)
clients := []model.ClientRecord{{Email: "shared@test"}, {Email: "child@test"}, {Email: "orphan@test"}}
if err := db.Create(&clients).Error; err != nil {
t.Fatal(err)
}
links := []model.ClientInbound{
{ClientId: clients[0].Id, InboundId: local.Id},
{ClientId: clients[0].Id, InboundId: direct.Id},
{ClientId: clients[0].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: clone.Id},
}
if err := db.Create(&links).Error; err != nil {
t.Fatal(err)
}
status := &Status{T: time.Now(), LogicalPro: 8, CpuCores: 4, Cpu: 31, Loads: []float64{1, 2, 3}}
status.Mem.Total, status.Mem.Current = 8<<30, 2<<30
overview, err := (&NodeService{}).GetNodeOverview(status)
if err != nil {
t.Fatal(err)
}
if overview.Fleet.ClientCount != 3 || overview.Fleet.InboundCount != 4 ||
overview.Master.Counts.ClientCount != 1 || overview.Master.Counts.InboundCount != 1 {
t.Fatalf("wrong host counts: %+v", overview)
}
want := map[string]int{"direct": 1, "cloned": 1, "child": 2}
for _, node := range overview.Nodes {
if node.ClientCount != want[node.Name] || node.InboundCount != 1 {
t.Errorf("wrong placement for %s: %+v", node.Name, node)
}
if node.Transitive && (node.Telemetry == nil || node.Telemetry.UDPCount == nil || *node.Telemetry.UDPCount != 0) {
t.Fatalf("missing descendant's own sample: %+v", node)
}
delete(want, node.Name)
}
if len(want) != 0 || overview.Master.Telemetry == nil || *overview.Master.Telemetry.Load15 != 3 {
t.Fatalf("missing view rows or master sample: %+v, missing=%v", overview.Master, want)
}
}
func BenchmarkNodeOverviewFleetScale(b *testing.B) {
dbtest.InitDB(b, filepath.Join(b.TempDir(), "fleet-scale.db"))
db := database.GetDB()
statusJSON := `{"success":true,"obj":{"cpu":25,"cpuCores":4,"logicalPro":8,"mem":{"current":2147483648,"total":8589934592,"available":6442450944},"tcpCount":132,"udpCount":22,"loads":[0.2,0.3,0.4],"uptime":90000,"netIO":{"up":12582912,"down":512}}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(statusJSON))
}))
b.Cleanup(server.Close)
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
nodes := make([]model.Node, 4)
for i := range nodes {
nodes[i] = model.Node{
Name: fmt.Sprint("remote-", i), Guid: fmt.Sprint("remote-guid-", i),
Scheme: "http", Address: u.Hostname(), Port: port, AllowPrivateAddress: true,
}
}
if err := db.Create(&nodes).Error; err != nil {
b.Fatal(err)
}
inbounds := make([]model.Inbound, 40)
for i := range inbounds {
inbounds[i] = model.Inbound{Tag: fmt.Sprint("inbound-", i), Port: 2000 + i, Settings: `{"clients":[]}`}
if i%5 != 0 {
node := &nodes[i%5-1]
inbounds[i].NodeID, inbounds[i].OriginNodeGuid = &node.Id, node.Guid
}
}
if err := db.CreateInBatches(&inbounds, 40).Error; err != nil {
b.Fatal(err)
}
clients := make([]model.ClientRecord, 7100)
for i := range clients {
clients[i].Email = fmt.Sprintf("client-%05d@test", i)
}
if err := db.CreateInBatches(&clients, 100).Error; err != nil {
b.Fatal(err)
}
links := make([]model.ClientInbound, 115000)
for i := range links {
client := clients[i%len(clients)]
ib := inbounds[(i/len(clients)+i)%len(inbounds)]
links[i] = model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}
}
if err := db.CreateInBatches(&links, 250).Error; err != nil {
b.Fatal(err)
}
svc := &NodeService{}
cycle := func() {
for i := range nodes {
patch, err := svc.Probe(b.Context(), &nodes[i])
if err != nil {
b.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(nodes[i].Id, patch); err != nil {
b.Fatal(err)
}
}
}
cycle()
b.Run("FourHeartbeatProbesAndWrites", func(b *testing.B) {
for b.Loop() {
cycle()
}
b.ReportMetric(float64(4*len(statusJSON)), "status-wire-B/cycle")
})
b.Run("OverviewAndJSON", func(b *testing.B) {
var payload []byte
for b.Loop() {
result, err := svc.GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
if err != nil {
b.Fatal(err)
}
payload, err = json.Marshal(result)
if err != nil || result.Fleet.ClientCount != 7100 {
b.Fatalf("fixture: %v", err)
}
}
b.ReportMetric(float64(len(payload)), "overview-wire-B/op")
})
}
@@ -117,7 +117,9 @@ func TestRecountByGuid_SplitsClonedNodesWithSharedGuid(t *testing.T) {
}
nodes := []*model.Node{n1, n2, n3}
svc.recountByGuid(nodes, selfGuid)
if _, _, err := svc.countNodeFleet(nodes, selfGuid); err != nil {
t.Fatal(err)
}
if n1.InboundCount != 1 || n2.InboundCount != 1 {
t.Errorf("cloned nodes must not share inbound counts: n1=%d n2=%d, want 1,1", n1.InboundCount, n2.InboundCount)
+123
View File
@@ -0,0 +1,123 @@
package service
import (
"encoding/json"
"math"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const nodeTelemetryFreshness = 30 * time.Second
func validNodeLoad(load float64) bool {
return load >= 0 && !math.IsInf(load, 0)
}
type nodeStatusMetrics struct {
Cpu json.RawMessage `json:"cpu"`
CpuCores json.RawMessage `json:"cpuCores"`
LogicalPro json.RawMessage `json:"logicalPro"`
Mem json.RawMessage `json:"mem"`
TcpCount json.RawMessage `json:"tcpCount"`
UdpCount json.RawMessage `json:"udpCount"`
Loads json.RawMessage `json:"loads"`
Uptime json.RawMessage `json:"uptime"`
NetIO json.RawMessage `json:"netIO"`
ResourceScope string `json:"resourceScope"`
SampleAgeMillis *int64 `json:"sampleAgeMillis"`
UnavailableMetrics []string `json:"unavailableMetrics"`
}
type nodeMetricNumber interface {
int | uint64 | float64
}
func readNodeMetric[T nodeMetricNumber](raw json.RawMessage, unavailable []string, key string) *T {
var v *T
if slices.Contains(unavailable, key) || json.Unmarshal(raw, &v) != nil || v == nil || *v < 0 {
return nil
}
return v
}
func (m nodeStatusMetrics) telemetry(received time.Time) *model.NodeTelemetry {
unavailable := m.UnavailableMetrics
var memory struct {
Current json.RawMessage `json:"current"`
Total json.RawMessage `json:"total"`
Available json.RawMessage `json:"available"`
}
var network struct {
Up json.RawMessage `json:"up"`
Down json.RawMessage `json:"down"`
}
var loads [3]json.RawMessage
_ = json.Unmarshal(m.Mem, &memory)
_ = json.Unmarshal(m.NetIO, &network)
_ = json.Unmarshal(m.Loads, &loads)
age := int64(0)
if m.SampleAgeMillis != nil {
age = min(max(0, *m.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
}
sample := &model.NodeTelemetry{
SampledAt: received.UnixMilli() - age,
ResourceScope: m.ResourceScope,
CpuPct: readNodeMetric[float64](m.Cpu, unavailable, "cpu"),
PhysicalCores: readNodeMetric[int](m.CpuCores, unavailable, "cpuCores"),
LogicalCores: readNodeMetric[int](m.LogicalPro, unavailable, "logicalPro"),
MemUsedBytes: readNodeMetric[uint64](memory.Current, unavailable, "mem"),
MemTotalBytes: readNodeMetric[uint64](memory.Total, unavailable, "mem"),
MemAvailableBytes: readNodeMetric[uint64](memory.Available, unavailable, "mem"),
TCPCount: readNodeMetric[int](m.TcpCount, unavailable, "tcpCount"),
UDPCount: readNodeMetric[int](m.UdpCount, unavailable, "udpCount"),
Load1: readNodeMetric[float64](loads[0], unavailable, "loads"),
Load5: readNodeMetric[float64](loads[1], unavailable, "loads"),
Load15: readNodeMetric[float64](loads[2], unavailable, "loads"),
UptimeSecs: readNodeMetric[uint64](m.Uptime, unavailable, "uptime"),
NetUp: readNodeMetric[uint64](network.Up, unavailable, "netUp"),
NetDown: readNodeMetric[uint64](network.Down, unavailable, "netDown"),
}
if sample.CpuPct != nil && *sample.CpuPct > 100 {
sample.CpuPct = nil
}
if sample.ResourceScope != "" || (sample.PhysicalCores != nil && *sample.PhysicalCores == 0) {
sample.PhysicalCores = nil
}
if sample.LogicalCores != nil && *sample.LogicalCores == 0 {
sample.LogicalCores = nil
}
if sample.MemTotalBytes == nil || *sample.MemTotalBytes == 0 ||
sample.MemUsedBytes == nil || *sample.MemUsedBytes > *sample.MemTotalBytes {
sample.MemUsedBytes, sample.MemTotalBytes, sample.MemAvailableBytes = nil, nil, nil
} else if sample.MemAvailableBytes != nil && *sample.MemAvailableBytes > *sample.MemTotalBytes {
sample.MemAvailableBytes = nil
}
return sample
}
func liveNodeTelemetry(node *model.Node, now time.Time) *model.NodeTelemetry {
sample := node.Telemetry
if sample == nil || !node.Enable || node.Status != "online" {
return nil
}
age := now.UnixMilli() - sample.SampledAt
if age < 0 || age >= nodeTelemetryFreshness.Milliseconds() {
return nil
}
view := *sample
view.SampleAgeMillis = &age
return &view
}
// StatusWithSampleAge publishes age relative to the sampler's clock.
func StatusWithSampleAge(status *Status) *Status {
if status == nil {
return nil
}
result := *status
result.SampleAgeMillis = new(max(0, time.Since(status.T).Milliseconds()))
return &result
}
+27 -104
View File
@@ -42,6 +42,9 @@ func (s *NodeService) LocalDescendants() ([]model.NodeSummary, error) {
XrayVersion: n.XrayVersion,
XrayState: n.XrayState,
XrayError: n.XrayError,
BasePath: n.BasePath,
Enabled: &n.Enable,
Telemetry: liveNodeTelemetry(n, time.Now()),
})
}
return out, nil
@@ -71,6 +74,12 @@ func (s *NodeService) RefreshDescendants(ctx context.Context, n *model.Node) {
if err != nil {
return
}
now := time.Now().UnixMilli()
for i := range summaries {
if sample := summaries[i].Telemetry; sample != nil && sample.SampleAgeMillis != nil {
sample.SampledAt = now - min(max(0, *sample.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
}
}
nodeDescendantsMu.Lock()
if len(summaries) == 0 {
delete(nodeDescendantsCache, n.Id)
@@ -120,9 +129,14 @@ func cachedDescendants() []model.NodeSummary {
// nodes are read-only projections (Id == 0). Used by the Nodes page and the
// heartbeat broadcast — never for probing/syncing, which stay on ListOperational.
func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
nodes, _, _, err := s.getNodeTreeWithCounts()
return nodes, err
}
func (s *NodeService) getNodeTreeWithCounts() ([]*model.Node, NodeFleetCounts, NodeFleetCounts, error) {
nodes, err := s.ListOperational()
if err != nil {
return nodes, err
return nodes, NodeFleetCounts{}, NodeFleetCounts{}, err
}
selfGuid, _ := (&SettingService{}).GetPanelGuid()
directGuids := make(map[string]struct{}, len(nodes))
@@ -136,7 +150,7 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
seen := make(map[string]struct{})
var transitive []*model.Node
for _, sum := range cachedDescendants() {
if sum.Guid == "" {
if sum.Guid == "" || sum.Guid == selfGuid {
continue
}
if _, ok := directGuids[sum.Guid]; ok {
@@ -161,23 +175,14 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
XrayState: sum.XrayState,
XrayError: sum.XrayError,
Transitive: true,
Enable: sum.Enabled == nil || *sum.Enabled,
BasePath: sum.BasePath,
Telemetry: sum.Telemetry,
})
}
if len(transitive) == 0 {
if len(nodes) > 0 {
s.enrichDashboardStats(database.GetDB(), nodes)
}
return nodes, nil
}
if len(nodes) > 0 {
s.populateClientCounts(database.GetDB(), nodes)
}
all := make([]*model.Node, 0, len(nodes)+len(transitive))
all = append(all, nodes...)
all = append(all, transitive...)
s.recountByGuid(all, selfGuid)
return all, nil
all := append(nodes, transitive...)
master, fleet, err := s.countNodeFleet(all, selfGuid)
return all, master, fleet, err
}
func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
@@ -185,6 +190,10 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
if err != nil {
return nil, err
}
return nodeTreeViews(nodes), nil
}
func nodeTreeViews(nodes []*model.Node) []*NodeView {
views := toNodeViews(nodes)
now := time.Now()
for _, view := range views {
@@ -192,91 +201,5 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
view.HeartbeatAgeMillis = new(max(0, now.Sub(time.Unix(view.LastHeartbeat, 0)).Milliseconds()))
}
}
return views, nil
}
// recountByGuid recomputes InboundCount/OnlineCount/DepletedCount for every node
// in the tree, keyed by the GUID that physically hosts each inbound, so a direct
// node shows only its own inbounds and each transitive node shows its own
// (#4983). In a flat topology the per-GUID and per-node-id counts coincide, so
// this only changes behaviour once a transitive node exists.
func (s *NodeService) recountByGuid(nodes []*model.Node, selfGuid string) {
db := database.GetDB()
type ibRow struct {
Id int
NodeID *int `gorm:"column:node_id"`
OriginNodeGuid string `gorm:"column:origin_node_guid"`
}
var ibRows []ibRow
if err := db.Table("inbounds").Select("id, node_id, origin_node_guid").Scan(&ibRows).Error; err != nil {
return
}
ambiguous := ambiguousNodeGuids(nodes, selfGuid)
effByInbound := make(map[int]string, len(ibRows))
inboundCountByGuid := make(map[string]int)
for _, r := range ibRows {
guid := r.OriginNodeGuid
if guid == "" {
if r.NodeID != nil {
guid = synthNodeGuid(*r.NodeID)
} else {
guid = selfGuid
}
} else if r.NodeID != nil {
// Origin still holds an ambiguous GUID (cloned server / master-shared,
// not yet re-attributed): bucket under the hosting node's unique id so
// the clones don't merge.
if _, bad := ambiguous[guid]; bad {
guid = synthNodeGuid(*r.NodeID)
}
}
effByInbound[r.Id] = guid
inboundCountByGuid[guid]++
}
// Classify by EMAIL (not the stale client_traffics.inbound_id) and bucket
// each client under its inbound's effective attribution GUID, deduping a
// client attached to several inbounds under the same GUID.
depletedByGuid := make(map[string]int)
disabledByGuid := make(map[string]int)
activeByGuid := make(map[string]int)
if statuses, err := s.nodeClientStatuses(); err == nil {
seen := make(map[string]map[int]struct{})
for _, st := range statuses {
guid, ok := effByInbound[st.InboundID]
if !ok {
continue
}
clientsSeen := seen[guid]
if clientsSeen == nil {
clientsSeen = make(map[int]struct{})
seen[guid] = clientsSeen
}
if _, dup := clientsSeen[st.ClientID]; dup {
continue
}
clientsSeen[st.ClientID] = struct{}{}
switch {
case st.Depleted:
depletedByGuid[guid]++
case st.Disabled:
disabledByGuid[guid]++
default:
activeByGuid[guid]++
}
}
}
onlineByGuid := s.onlineEmailsByGuid()
onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
for _, n := range nodes {
guid := effectiveNodeGuid(n, ambiguous)
n.InboundCount = inboundCountByGuid[guid]
n.OnlineCount = len(onlineByGuid[guid])
// Keyed by node id, so a transitive sub-node (id 0) never has one.
n.OnlineTotalCount = onlineTotals[n.Id]
n.DepletedCount = depletedByGuid[guid]
n.DisabledCount = disabledByGuid[guid]
n.ActiveCount = activeByGuid[guid]
}
return views
}
+10 -3
View File
@@ -71,6 +71,7 @@ type Status struct {
networkTrafficSample *networkTrafficSample `json:"-"`
ResourceScope string `json:"resourceScope,omitempty"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
T time.Time `json:"-"`
Cpu float64 `json:"cpu"`
@@ -78,8 +79,9 @@ type Status struct {
LogicalPro int `json:"logicalPro"`
CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
Mem struct {
Current uint64 `json:"current"`
Total uint64 `json:"total"`
Current uint64 `json:"current"`
Total uint64 `json:"total"`
Available *uint64 `json:"available,omitempty"`
} `json:"mem"`
Swap struct {
Current uint64 `json:"current"`
@@ -675,6 +677,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
util, err := s.sampleCPUUtilization()
if err != nil {
logger.Warning("get cpu percent failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "cpu")
} else {
status.Cpu = util
}
@@ -716,6 +719,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
upTime, err := host.Uptime()
if err != nil {
logger.Warning("get uptime failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "uptime")
} else {
status.Uptime = upTime
}
@@ -728,6 +732,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
} else {
status.Mem.Current = memInfo.Used
status.Mem.Total = memInfo.Total
status.Mem.Available = new(memInfo.Available)
}
if scoped == nil {
@@ -777,7 +782,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
avgState, err := load.Avg()
if err != nil {
logger.Warning("get load avg failed:", err)
} else {
} else if validNodeLoad(avgState.Load1) && validNodeLoad(avgState.Load5) && validNodeLoad(avgState.Load15) {
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
}
@@ -787,11 +792,13 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
status.TcpCount, err = sys.GetTCPCount()
if err != nil {
logger.Warning("get tcp connections failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "tcpCount")
}
status.UdpCount, err = sys.GetUDPCount()
if err != nil {
logger.Warning("get udp connections failed:", err)
status.UnavailableMetrics = append(status.UnavailableMetrics, "udpCount")
}
s.resolvePublicIPsInBackground()
+2 -2
View File
@@ -51,7 +51,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
if got.ResourceScope != "container" || got.CpuCores != 2 || got.LogicalPro != 2 || got.CpuSpeedMhz != 0 || got.Swap.Total != 512<<20 || got.Swap.Current != 19357696 || got.Uptime != 52624 {
t.Fatalf("incorrect corrected resources: %+v", got)
}
if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || got.Mem.Available == nil || *got.Mem.Available != 1966080<<10 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
t.Fatalf("unrelated metric path changed: %+v", got)
}
if !slices.Equal(got.UnavailableMetrics, []string{"cpu"}) {
@@ -74,7 +74,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
t.Fatal(err)
}
native := svc.GetStatus(previous)
if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || native.Mem != got.Mem || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || !reflect.DeepEqual(native.Mem, got.Mem) || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
t.Fatalf("native regression: %+v", native)
}
}
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "ستتم إعادة تشغيل لوحة العقدة وخدمات الاشتراك وقد تتوقف مؤقتًا. يتطلب رمز API بصلاحية node-admin أو admin على العقدة.",
"addNode": "إضافة نود",
"editNode": "تحرير العقدة",
"totalNodes": "إجمالي النودز",
"onlineNodes": "متصل",
"offlineNodes": "غير متصل",
"avgLatency": "متوسط الكمون",
"onlineOnNode": "{synced} متصل على الاتصالات الواردة المستوردة إلى هذه اللوحة، و{total} متصل على العقدة إجمالاً",
"name": "الاسم",
"namePlaceholder": "مثال: de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "للقراءة فقط: نود تابع يتم الوصول إليه عبر {parent}. تتم إدارته من لوحة {parent} نفسها.",
"deleteConfirmTitle": "تحذف النود \"{name}\"؟",
"deleteConfirmContent": "ده هيوقّف مراقبة النود. البانل البعيد نفسه مش هيتأثر.",
"fleet": {
"subtitle": "راقب هذه اللوحة والعُقد البعيدة.",
"allNodes": "جميع العُقد",
"master": "الرئيسية",
"thisPanel": "هذه اللوحة",
"fleetScope": "الرئيسية + {remotes} عُقد بعيدة",
"reporting": "{live} من {total} ترسل بيانات",
"registered": "{shown} من {total} عُقد مسجلة",
"allStatuses": "جميع الحالات",
"open": "فتح",
"hardware": "المعالج / الذاكرة",
"cpuAverage": "متوسط المعالج",
"logicalCores": "{cores} معالج منطقي",
"availableMemory": "{size} متاح",
"remainingMemory": "{size} متبقٍ",
"connections": "TCP / UDP / الحمل",
"load": "الحمل",
"loadSum": "مجموع الحمل",
"loadWindow": "حمل النظام على مدار ١ و٥ و١٥ دقيقة",
"hostMetrics": "تُجمع السرعات والاتصالات لكل مضيف.",
"runtime": "وقت التشغيل",
"mixed": "إصدارات متعددة",
"history": "السجل"
},
"statusValues": {
"online": "متصل",
"offline": "غير متصل",
+24 -4
View File
@@ -1339,10 +1339,6 @@
"restartPanelContent": "The node panel and subscription services will restart and may be temporarily unavailable. Requires a node-admin or admin API token on the node.",
"addNode": "Add Node",
"editNode": "Edit Node",
"totalNodes": "Total Nodes",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Avg Latency",
"onlineOnNode": "{synced} online on inbounds imported into this panel, {total} online on the node in total",
"name": "Name",
"namePlaceholder": "e.g. de-frankfurt-1",
@@ -1400,6 +1396,30 @@
"subNodeTip": "Read-only: a downstream node reached through {parent}. Manage it from {parent}'s own panel.",
"deleteConfirmTitle": "Delete node \"{name}\"?",
"deleteConfirmContent": "This stops monitoring the node. The remote panel itself is unaffected.",
"fleet": {
"subtitle": "Monitor this panel and its remote nodes.",
"allNodes": "All nodes",
"master": "Master",
"thisPanel": "This panel",
"fleetScope": "Master + {remotes} remote nodes",
"reporting": "{live}/{total} reporting",
"registered": "{shown}/{total} registered nodes",
"allStatuses": "All statuses",
"open": "Open",
"hardware": "CPU / RAM",
"cpuAverage": "Avg CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} available",
"remainingMemory": "{size} remaining",
"connections": "TCP / UDP / Load",
"load": "Load",
"loadSum": "Load sum",
"loadWindow": "System load over 1, 5 and 15 minutes",
"hostMetrics": "Rates and connections are summed per host.",
"runtime": "Runtime",
"mixed": "Mixed",
"history": "History"
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "El panel y los servicios de suscripción del nodo se reiniciarán y podrían dejar de estar disponibles temporalmente. Requiere un token API node-admin o admin en el nodo.",
"addNode": "Agregar nodo",
"editNode": "Editar nodo",
"totalNodes": "Total de nodos",
"onlineNodes": "En línea",
"offlineNodes": "Sin conexión",
"avgLatency": "Latencia media",
"onlineOnNode": "{synced} en línea en los inbounds importados a este panel, {total} en línea en total en el nodo",
"name": "Nombre",
"namePlaceholder": "p. ej. de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Solo lectura: un nodo descendente al que se llega a través de {parent}. Gestiónalo desde el propio panel de {parent}.",
"deleteConfirmTitle": "¿Eliminar el nodo \"{name}\"?",
"deleteConfirmContent": "Esto detiene la monitorización del nodo. El panel remoto en sí no se ve afectado.",
"fleet": {
"subtitle": "Supervisa este panel y sus nodos remotos.",
"allNodes": "Todos los nodos",
"master": "Principal",
"thisPanel": "Este panel",
"fleetScope": "Principal + {remotes} nodos remotos",
"reporting": "{live}/{total} con datos",
"registered": "{shown}/{total} nodos registrados",
"allStatuses": "Todos los estados",
"open": "Abrir",
"hardware": "CPU / RAM",
"cpuAverage": "CPU media",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} disponibles",
"remainingMemory": "{size} restantes",
"connections": "TCP / UDP / Carga",
"load": "Carga",
"loadSum": "Suma de cargas",
"loadWindow": "Carga del sistema en 1, 5 y 15 minutos",
"hostMetrics": "Las tasas y conexiones se suman por servidor.",
"runtime": "Ejecución",
"mixed": "Mixto",
"history": "Historial"
},
"statusValues": {
"online": "En línea",
"offline": "Sin conexión",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "پنل و سرویس اشتراک نود مجدداً راه‌اندازی می‌شوند و ممکن است موقتاً در دسترس نباشند. توکن API نود باید دسترسی node-admin یا admin داشته باشد.",
"addNode": "افزودن نود",
"editNode": "ویرایش نود",
"totalNodes": "کل نودها",
"onlineNodes": "آنلاین",
"offlineNodes": "آفلاین",
"avgLatency": "میانگین تاخیر",
"onlineOnNode": "{synced} آنلاین روی اینباندهای واردشده به این پنل، {total} آنلاین در کل نود",
"name": "نام",
"namePlaceholder": "مثلاً de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "فقط‌خواندنی: یک نود پایین‌دستی که از طریق {parent} در دسترس است. آن را از پنل خودِ {parent} مدیریت کنید.",
"deleteConfirmTitle": "نود «{name}» حذف شود؟",
"deleteConfirmContent": "نظارت روی این نود متوقف می‌شود. خود پنل ریموت تغییری نمی‌کند.",
"fleet": {
"subtitle": "وضعیت این پنل و نودهای راه دور را پایش کنید.",
"allNodes": "همهٔ نودها",
"master": "مستر",
"thisPanel": "این پنل",
"fleetScope": "مستر + {remotes} نود راه دور",
"reporting": "{live} از {total} در حال گزارش",
"registered": "{shown} از {total} نود ثبت‌شده",
"allStatuses": "همهٔ وضعیت‌ها",
"open": "باز کردن",
"hardware": "پردازنده / حافظه",
"cpuAverage": "میانگین CPU",
"logicalCores": "{cores} پردازندهٔ منطقی",
"availableMemory": "{size} در دسترس",
"remainingMemory": "{size} باقی‌مانده",
"connections": "TCP / UDP / بار",
"load": "بار سیستم",
"loadSum": "مجموع بار",
"loadWindow": "بار سیستم در بازه‌های ۱، ۵ و ۱۵ دقیقه",
"hostMetrics": "نرخ‌ها و اتصال‌ها به تفکیک میزبان جمع می‌شوند.",
"runtime": "زمان اجرا",
"mixed": "چند نسخه",
"history": "تاریخچه"
},
"statusValues": {
"online": "آنلاین",
"offline": "آفلاین",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Panel node dan layanan langganan akan dimulai ulang dan mungkin tidak tersedia sementara. Memerlukan token API node-admin atau admin pada node.",
"addNode": "Tambah Node",
"editNode": "Edit node",
"totalNodes": "Total Node",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Latensi Rata-rata",
"onlineOnNode": "{synced} online pada inbound yang diimpor ke panel ini, total {total} online di node",
"name": "Nama",
"namePlaceholder": "mis. de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Hanya-baca: node turunan yang dijangkau melalui {parent}. Kelola dari panel {parent} sendiri.",
"deleteConfirmTitle": "Hapus node \"{name}\"?",
"deleteConfirmContent": "Ini menghentikan pemantauan node. Panel jarak jauh itu sendiri tidak terpengaruh.",
"fleet": {
"subtitle": "Pantau panel ini dan node jarak jauhnya.",
"allNodes": "Semua node",
"master": "Utama",
"thisPanel": "Panel ini",
"fleetScope": "Utama + {remotes} node jarak jauh",
"reporting": "{live}/{total} melapor",
"registered": "{shown}/{total} node terdaftar",
"allStatuses": "Semua status",
"open": "Buka",
"hardware": "CPU / RAM",
"cpuAverage": "Rata-rata CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} tersedia",
"remainingMemory": "{size} tersisa",
"connections": "TCP / UDP / Beban",
"load": "Beban",
"loadSum": "Total beban",
"loadWindow": "Beban sistem selama 1, 5, dan 15 menit",
"hostMetrics": "Laju dan koneksi dijumlahkan per host.",
"runtime": "Runtime",
"mixed": "Campuran",
"history": "Riwayat"
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "ノードのパネルとサブスクリプションサービスを再起動するため、一時的に利用できなくなる場合があります。ノードのnode-adminまたはadmin APIトークンが必要です。",
"addNode": "ノードを追加",
"editNode": "ノード編集",
"totalNodes": "ノード総数",
"onlineNodes": "オンライン",
"offlineNodes": "オフライン",
"avgLatency": "平均レイテンシ",
"onlineOnNode": "このパネルにインポートしたインバウンドでオンライン: {synced}、ノード全体でオンライン: {total}",
"name": "名前",
"namePlaceholder": "例: de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "読み取り専用: {parent} を経由して到達する下位ノードです。{parent} 自身のパネルから管理してください。",
"deleteConfirmTitle": "ノード「{name}」を削除しますか?",
"deleteConfirmContent": "ノードの監視を停止します。リモートパネル自体には影響しません。",
"fleet": {
"subtitle": "このパネルとリモートノードを監視します。",
"allNodes": "全ノード",
"master": "マスター",
"thisPanel": "このパネル",
"fleetScope": "マスターとリモート {remotes} 台",
"reporting": "{live}/{total} 台が報告中",
"registered": "登録済み {shown}/{total} 台",
"allStatuses": "すべての状態",
"open": "開く",
"hardware": "CPU / RAM",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} 利用可能",
"remainingMemory": "{size} 残り",
"connections": "TCP / UDP / 負荷",
"load": "負荷",
"loadSum": "負荷合計",
"loadWindow": "1 分・5 分・15 分のシステム負荷",
"hostMetrics": "転送速度と接続数はホストごとの値を合計しています。",
"runtime": "実行環境",
"mixed": "混在",
"history": "履歴"
},
"statusValues": {
"online": "オンライン",
"offline": "オフライン",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "O painel e os serviços de assinatura do nó serão reiniciados e poderão ficar indisponíveis temporariamente. Requer um token de API node-admin ou admin no nó.",
"addNode": "Adicionar nó",
"editNode": "Editar nó",
"totalNodes": "Total de nós",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Latência média",
"onlineOnNode": "{synced} online nos inbounds importados para este painel, {total} online no nó no total",
"name": "Nome",
"namePlaceholder": "ex.: de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Somente leitura: um nó descendente acessado através de {parent}. Gerencie-o pelo próprio painel de {parent}.",
"deleteConfirmTitle": "Excluir o nó \"{name}\"?",
"deleteConfirmContent": "Isso interrompe o monitoramento do nó. O painel remoto em si não é afetado.",
"fleet": {
"subtitle": "Monitore este painel e seus nós remotos.",
"allNodes": "Todos os nós",
"master": "Principal",
"thisPanel": "Este painel",
"fleetScope": "Principal + {remotes} nós remotos",
"reporting": "{live}/{total} enviando dados",
"registered": "{shown}/{total} nós registrados",
"allStatuses": "Todos os estados",
"open": "Abrir",
"hardware": "CPU / RAM",
"cpuAverage": "CPU média",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} disponíveis",
"remainingMemory": "{size} restantes",
"connections": "TCP / UDP / Carga",
"load": "Carga",
"loadSum": "Soma das cargas",
"loadWindow": "Carga do sistema em 1, 5 e 15 minutos",
"hostMetrics": "As taxas e conexões são somadas por host.",
"runtime": "Execução",
"mixed": "Misto",
"history": "Histórico"
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Панель узла и службы подписки будут перезапущены и могут быть временно недоступны. Требуется API-токен node-admin или admin на узле.",
"addNode": "Добавить узел",
"editNode": "Изменить узел",
"totalNodes": "Всего узлов",
"onlineNodes": "В сети",
"offlineNodes": "Не в сети",
"avgLatency": "Средняя задержка",
"onlineOnNode": "В сети на инбаундах, импортированных в эту панель: {synced}; всего в сети на узле: {total}",
"name": "Имя",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Только для чтения: подчинённый узел, доступный через {parent}. Управляйте им из собственной панели {parent}.",
"deleteConfirmTitle": "Удалить узел \"{name}\"?",
"deleteConfirmContent": "Это остановит мониторинг узла. Сама удалённая панель не будет затронута.",
"fleet": {
"subtitle": "Мониторинг этой панели и её удалённых узлов.",
"allNodes": "Все узлы",
"master": "Главный",
"thisPanel": "Эта панель",
"fleetScope": "Главный + удалённых узлов: {remotes}",
"reporting": "Передают данные: {live}/{total}",
"registered": "Зарегистрированные узлы: {shown}/{total}",
"allStatuses": "Все статусы",
"open": "Открыть",
"hardware": "ЦП / ОЗУ",
"cpuAverage": "Средняя загрузка ЦП",
"logicalCores": "{cores} vCPU",
"availableMemory": "Доступно {size}",
"remainingMemory": "Осталось {size}",
"connections": "TCP / UDP / Нагрузка",
"load": "Нагрузка",
"loadSum": "Суммарная нагрузка",
"loadWindow": "Нагрузка системы за 1, 5 и 15 минут",
"hostMetrics": "Скорости и соединения суммируются по хостам.",
"runtime": "Среда выполнения",
"mixed": "Разные версии",
"history": "История"
},
"statusValues": {
"online": "В сети",
"offline": "Не в сети",
+24 -4
View File
@@ -1339,10 +1339,6 @@
"restartPanelContent": "Panel uzla a služby odberov sa reštartujú a môžu byť dočasne nedostupné. Vyžaduje sa API token node-admin alebo admin na uzle.",
"addNode": "Pridať server",
"editNode": "Upraviť server",
"totalNodes": "Počet serverov",
"onlineNodes": "Online",
"offlineNodes": "Offline",
"avgLatency": "Priemerná odozva",
"onlineOnNode": "{synced} online na vstupoch importovaných do tohto panela, celkovo {total} online na uzle",
"name": "Názov",
"namePlaceholder": "napr. de-frankfurt-1",
@@ -1400,6 +1396,30 @@
"subNodeTip": "Iba na čítanie: podriadený server dostupný cez {parent}. Spravujte ho z panelu servera {parent}.",
"deleteConfirmTitle": "Odstrániť server „{name}“?",
"deleteConfirmContent": "Prestane sa sledovať tento server. Samotný vzdialený panel sa nezmení.",
"fleet": {
"subtitle": "Monitorujte tento panel a jeho vzdialené uzly.",
"allNodes": "Všetky uzly",
"master": "Hlavný uzol",
"thisPanel": "Tento panel",
"fleetScope": "Hlavný uzol + {remotes} vzdialených uzlov",
"reporting": "{live}/{total} hlási údaje",
"registered": "{shown}/{total} registrovaných uzlov",
"allStatuses": "Všetky stavy",
"open": "Otvoriť",
"hardware": "CPU / RAM",
"cpuAverage": "Priemer CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} dostupných",
"remainingMemory": "{size} zostáva",
"connections": "TCP / UDP / Záťaž",
"load": "Záťaž",
"loadSum": "Súčet záťaže",
"loadWindow": "Systémová záťaž za 1, 5 a 15 minút",
"hostMetrics": "Rýchlosti a spojenia sa sčítavajú za jednotlivé hostitele.",
"runtime": "Beh",
"mixed": "Rôzne verzie",
"history": "História"
},
"statusValues": {
"online": "Online",
"offline": "Offline",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Düğüm paneli ve abonelik hizmetleri yeniden başlatılacak ve geçici olarak kullanılamayabilir. Düğümde node-admin veya admin API belirteci gerekir.",
"addNode": "Düğüm Ekle",
"editNode": "Düğümü Düzenle",
"totalNodes": "Toplam Düğüm",
"onlineNodes": "Çevrimiçi",
"offlineNodes": "Çevrimdışı",
"avgLatency": "Ortalama Gecikme",
"onlineOnNode": "Bu panele içe aktarılan inbound'larda {synced} çevrimiçi, düğümde toplam {total} çevrimiçi",
"name": "Ad",
"namePlaceholder": "ör. de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Salt okunur: {parent} üzerinden erişilen bir alt düğüm. Bunu {parent} panelinden yönetin.",
"deleteConfirmTitle": "\"{name}\" düğümü silinsin mi?",
"deleteConfirmContent": "Bu işlem düğüm izlemeyi durdurur. Uzak panelin kendisi etkilenmez.",
"fleet": {
"subtitle": "Bu paneli ve uzak düğümlerini izleyin.",
"allNodes": "Tüm düğümler",
"master": "Ana düğüm",
"thisPanel": "Bu panel",
"fleetScope": "Ana düğüm + {remotes} uzak düğüm",
"reporting": "{live}/{total} veri gönderiyor",
"registered": "{shown}/{total} kayıtlı düğüm",
"allStatuses": "Tüm durumlar",
"open": "Aç",
"hardware": "CPU / RAM",
"cpuAverage": "Ort. CPU",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} kullanılabilir",
"remainingMemory": "{size} kalan",
"connections": "TCP / UDP / Yük",
"load": "Yük",
"loadSum": "Toplam yük",
"loadWindow": "1, 5 ve 15 dakikalık sistem yükü",
"hostMetrics": "Hızlar ve bağlantılar ana makine bazında toplanır.",
"runtime": "Çalışma zamanı",
"mixed": "Karma",
"history": "Geçmiş"
},
"statusValues": {
"online": "Çevrimiçi",
"offline": "Çevrimdışı",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Панель вузла та служби підписки буде перезапущено, і вони можуть бути тимчасово недоступні. Потрібен API-токен node-admin або admin на вузлі.",
"addNode": "Додати вузол",
"editNode": "Змінити вузол",
"totalNodes": "Усього вузлів",
"onlineNodes": "У мережі",
"offlineNodes": "Не в мережі",
"avgLatency": "Середня затримка",
"onlineOnNode": "У мережі на інбаундах, імпортованих у цю панель: {synced}; усього в мережі на вузлі: {total}",
"name": "Назва",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Лише для читання: підлеглий вузол, доступний через {parent}. Керуйте ним із власної панелі {parent}.",
"deleteConfirmTitle": "Видалити вузол \"{name}\"?",
"deleteConfirmContent": "Це зупинить моніторинг вузла. Сама віддалена панель не зазнає змін.",
"fleet": {
"subtitle": "Моніторинг цієї панелі та її віддалених вузлів.",
"allNodes": "Усі вузли",
"master": "Головний",
"thisPanel": "Ця панель",
"fleetScope": "Головний + віддалених вузлів: {remotes}",
"reporting": "Передають дані: {live}/{total}",
"registered": "Зареєстровані вузли: {shown}/{total}",
"allStatuses": "Усі стани",
"open": "Відкрити",
"hardware": "ЦП / ОЗП",
"cpuAverage": "Середнє ЦП",
"logicalCores": "{cores} vCPU",
"availableMemory": "Доступно {size}",
"remainingMemory": "Залишилося {size}",
"connections": "TCP / UDP / Навантаження",
"load": "Навантаження",
"loadSum": "Сумарне навантаження",
"loadWindow": "Навантаження системи за 1, 5 та 15 хвилин",
"hostMetrics": "Швидкості та з’єднання підсумовуються за хостами.",
"runtime": "Середовище виконання",
"mixed": "Різні версії",
"history": "Історія"
},
"statusValues": {
"online": "У мережі",
"offline": "Не в мережі",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "Bảng điều khiển và dịch vụ đăng ký của nút sẽ khởi động lại và có thể tạm thời không khả dụng. Yêu cầu mã API node-admin hoặc admin trên nút.",
"addNode": "Thêm nút",
"editNode": "Sửa node",
"totalNodes": "Tổng số nút",
"onlineNodes": "Trực tuyến",
"offlineNodes": "Ngoại tuyến",
"avgLatency": "Độ trễ trung bình",
"onlineOnNode": "{synced} trực tuyến trên các inbound đã nhập vào bảng điều khiển này, tổng cộng {total} trực tuyến trên nút",
"name": "Tên",
"namePlaceholder": "vd: de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "Chỉ đọc: một nút phía dưới được kết nối qua {parent}. Quản lý nó từ bảng điều khiển của chính {parent}.",
"deleteConfirmTitle": "Xóa nút \"{name}\"?",
"deleteConfirmContent": "Việc này dừng giám sát nút. Panel từ xa không bị ảnh hưởng.",
"fleet": {
"subtitle": "Giám sát bảng điều khiển này và các nút từ xa.",
"allNodes": "Tất cả nút",
"master": "Nút chính",
"thisPanel": "Bảng điều khiển này",
"fleetScope": "Nút chính + {remotes} nút từ xa",
"reporting": "{live}/{total} đang báo cáo",
"registered": "{shown}/{total} nút đã đăng ký",
"allStatuses": "Mọi trạng thái",
"open": "Mở",
"hardware": "CPU / RAM",
"cpuAverage": "CPU trung bình",
"logicalCores": "{cores} vCPU",
"availableMemory": "{size} khả dụng",
"remainingMemory": "Còn lại {size}",
"connections": "TCP / UDP / Tải",
"load": "Tải",
"loadSum": "Tổng tải",
"loadWindow": "Tải hệ thống trong 1, 5 và 15 phút",
"hostMetrics": "Tốc độ và kết nối được cộng theo từng máy chủ.",
"runtime": "Môi trường chạy",
"mixed": "Nhiều phiên bản",
"history": "Lịch sử"
},
"statusValues": {
"online": "Trực tuyến",
"offline": "Ngoại tuyến",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "节点面板和订阅服务将重启,并可能暂时不可用。需要节点上的 node-admin 或 admin API 令牌。",
"addNode": "添加节点",
"editNode": "编辑节点",
"totalNodes": "节点总数",
"onlineNodes": "在线",
"offlineNodes": "离线",
"avgLatency": "平均延迟",
"onlineOnNode": "导入此面板的入站上有 {synced} 个在线,该节点上共有 {total} 个在线",
"name": "名称",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "只读:通过 {parent} 接入的下游节点。请在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "删除节点 \"{name}\"?",
"deleteConfirmContent": "这将停止监控该节点。远程面板本身不受影响。",
"fleet": {
"subtitle": "监控本面板和远程节点。",
"allNodes": "所有节点",
"master": "主节点",
"thisPanel": "本面板",
"fleetScope": "主节点 + {remotes} 个远程节点",
"reporting": "{live}/{total} 正在上报",
"registered": "{shown}/{total} 个已注册节点",
"allStatuses": "所有状态",
"open": "打开",
"hardware": "CPU / 内存",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} 个逻辑核心",
"availableMemory": "可用 {size}",
"remainingMemory": "剩余 {size}",
"connections": "TCP / UDP / 负载",
"load": "负载",
"loadSum": "总负载",
"loadWindow": "1、5 和 15 分钟系统负载",
"hostMetrics": "速率和连接数按主机汇总。",
"runtime": "运行状态",
"mixed": "多个版本",
"history": "历史"
},
"statusValues": {
"online": "在线",
"offline": "离线",
+24 -4
View File
@@ -1218,10 +1218,6 @@
"restartPanelContent": "節點面板與訂閱服務將重新啟動,可能暫時無法使用。需要節點上的 node-admin 或 admin API 權杖。",
"addNode": "新增節點",
"editNode": "編輯節點",
"totalNodes": "節點總數",
"onlineNodes": "上線",
"offlineNodes": "離線",
"avgLatency": "平均延遲",
"onlineOnNode": "匯入此面板的入站上有 {synced} 個上線,該節點上共有 {total} 個上線",
"name": "名稱",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1279,6 +1275,30 @@
"subNodeTip": "唯讀:透過 {parent} 連接的下游節點。請在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "刪除節點「{name}」?",
"deleteConfirmContent": "這將停止監控該節點。遠端面板本身不受影響。",
"fleet": {
"subtitle": "監控本面板與遠端節點。",
"allNodes": "所有節點",
"master": "主節點",
"thisPanel": "本面板",
"fleetScope": "主節點 + {remotes} 個遠端節點",
"reporting": "{live}/{total} 正在回報",
"registered": "{shown}/{total} 個已註冊節點",
"allStatuses": "所有狀態",
"open": "開啟",
"hardware": "CPU / 記憶體",
"cpuAverage": "平均 CPU",
"logicalCores": "{cores} 個邏輯核心",
"availableMemory": "可用 {size}",
"remainingMemory": "剩餘 {size}",
"connections": "TCP / UDP / 負載",
"load": "負載",
"loadSum": "總負載",
"loadWindow": "1、5 和 15 分鐘系統負載",
"hostMetrics": "速率和連線數按主機加總。",
"runtime": "執行狀態",
"mixed": "多個版本",
"history": "歷史"
},
"statusValues": {
"online": "上線",
"offline": "離線",
+3 -1
View File
@@ -362,7 +362,9 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
// check client ips from log file every 10 sec
_, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
_, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
nodeHeartbeat := job.NewNodeHeartbeatJob()
nodeHeartbeat.SetLocalStatusSource(s.api.LastStatus)
_, _ = s.cron.AddJob(cadenceNodeHeartbeat, nodeHeartbeat)
_, _ = s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob())
+12 -11
View File
@@ -14,17 +14,18 @@ import (
type MessageType string
const (
MessageTypeStatus MessageType = "status"
MessageTypeTraffic MessageType = "traffic"
MessageTypeInbounds MessageType = "inbounds"
MessageTypeOutbounds MessageType = "outbounds"
MessageTypeNodes MessageType = "nodes"
MessageTypeNotification MessageType = "notification"
MessageTypeXrayState MessageType = "xray_state"
MessageTypeClientStats MessageType = "client_stats"
MessageTypeClients MessageType = "clients"
MessageTypeInvalidate MessageType = "invalidate"
maxMessageSize = 10 * 1024 * 1024 // 10MB
MessageTypeStatus MessageType = "status"
MessageTypeTraffic MessageType = "traffic"
MessageTypeInbounds MessageType = "inbounds"
MessageTypeOutbounds MessageType = "outbounds"
MessageTypeNodes MessageType = "nodes"
MessageTypeNodesOverview MessageType = "nodesOverview"
MessageTypeNotification MessageType = "notification"
MessageTypeXrayState MessageType = "xray_state"
MessageTypeClientStats MessageType = "client_stats"
MessageTypeClients MessageType = "clients"
MessageTypeInvalidate MessageType = "invalidate"
maxMessageSize = 10 * 1024 * 1024 // 10MB
enqueueTimeout = 100 * time.Millisecond
clientSendQueue = 512 // ~50s of buffering for a momentarily slow browser.
+6
View File
@@ -69,6 +69,12 @@ func BroadcastNodes(nodes any) {
}
}
func BroadcastNodesOverview(overview any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeNodesOverview, overview)
}
}
// BroadcastOutbounds broadcasts outbounds list update to all connected clients.
func BroadcastOutbounds(outbounds any) {
if hub := GetHub(); hub != nil {
+4
View File
@@ -37,6 +37,7 @@ func run(root, outDir string) error {
"WireguardDevice",
"Client",
"ClientRecord",
"NodeTelemetry",
"ClientInbound",
"InboundFallback",
"Host",
@@ -127,6 +128,9 @@ func run(root, outDir string) error {
"MLKEM768Response",
"NodeMutationRequest",
"NodeView",
"NodeOverview",
"NodeMasterView",
"NodeFleetCounts",
"ProbeResultUI",
"RealityScanResult",
"RealityWatchEntry",