v1.6.0 #221
@@ -687,7 +687,14 @@
|
||||
"failedToFetchHostConfig": "Failed to fetch host configuration",
|
||||
"failedToFetchStatus": "Failed to fetch server status",
|
||||
"failedToFetchMetrics": "Failed to fetch server metrics",
|
||||
"failedToFetchHomeData": "Failed to fetch home data"
|
||||
"failedToFetchHomeData": "Failed to fetch home data",
|
||||
"loadingMetrics": "Loading metrics...",
|
||||
"refreshing": "Refreshing...",
|
||||
"serverOffline": "Server Offline",
|
||||
"cannotFetchMetrics": "Cannot fetch metrics from offline server",
|
||||
"load": "Load",
|
||||
"free": "Free",
|
||||
"available": "Available"
|
||||
},
|
||||
"auth": {
|
||||
"loginTitle": "Login to Termix",
|
||||
|
||||
@@ -701,7 +701,14 @@
|
||||
"memoryUsage": "内存使用率",
|
||||
"rootStorageSpace": "根目录存储空间",
|
||||
"of": "的",
|
||||
"feedbackMessage": "对服务器管理的下一步功能有想法?在这里分享吧"
|
||||
"feedbackMessage": "对服务器管理的下一步功能有想法?在这里分享吧",
|
||||
"loadingMetrics": "正在加载指标...",
|
||||
"refreshing": "正在刷新...",
|
||||
"serverOffline": "服务器离线",
|
||||
"cannotFetchMetrics": "无法从离线服务器获取指标",
|
||||
"load": "负载",
|
||||
"free": "空闲",
|
||||
"available": "可用"
|
||||
},
|
||||
"auth": {
|
||||
"loginTitle": "登录 Termix",
|
||||
|
||||
@@ -8,6 +8,237 @@ import {sshData, sshCredentials} from '../database/db/schema.js';
|
||||
import {eq, and} from 'drizzle-orm';
|
||||
import { statsLogger } from '../utils/logger.js';
|
||||
|
||||
// Rate limiting
|
||||
const requestCounts = new Map<string, { count: number; resetTime: number }>();
|
||||
const RATE_LIMIT_WINDOW = 15 * 60 * 1000; // 15 minutes
|
||||
const RATE_LIMIT_MAX = 100; // 100 requests per window
|
||||
|
||||
// Connection pooling
|
||||
interface PooledConnection {
|
||||
client: Client;
|
||||
lastUsed: number;
|
||||
inUse: boolean;
|
||||
hostKey: string;
|
||||
}
|
||||
|
||||
class SSHConnectionPool {
|
||||
private connections = new Map<string, PooledConnection[]>();
|
||||
private maxConnectionsPerHost = 3;
|
||||
private connectionTimeout = 30000;
|
||||
private cleanupInterval: NodeJS.Timeout;
|
||||
|
||||
constructor() {
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
this.cleanup();
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
private getHostKey(host: SSHHostWithCredentials): string {
|
||||
return `${host.ip}:${host.port}:${host.username}`;
|
||||
}
|
||||
|
||||
async getConnection(host: SSHHostWithCredentials): Promise<Client> {
|
||||
const hostKey = this.getHostKey(host);
|
||||
const connections = this.connections.get(hostKey) || [];
|
||||
|
||||
const available = connections.find(conn => !conn.inUse);
|
||||
if (available) {
|
||||
available.inUse = true;
|
||||
available.lastUsed = Date.now();
|
||||
return available.client;
|
||||
}
|
||||
|
||||
if (connections.length < this.maxConnectionsPerHost) {
|
||||
const client = await this.createConnection(host);
|
||||
const pooled: PooledConnection = {
|
||||
client,
|
||||
lastUsed: Date.now(),
|
||||
inUse: true,
|
||||
hostKey
|
||||
};
|
||||
connections.push(pooled);
|
||||
this.connections.set(hostKey, connections);
|
||||
return client;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const checkAvailable = () => {
|
||||
const available = connections.find(conn => !conn.inUse);
|
||||
if (available) {
|
||||
available.inUse = true;
|
||||
available.lastUsed = Date.now();
|
||||
resolve(available.client);
|
||||
} else {
|
||||
setTimeout(checkAvailable, 100);
|
||||
}
|
||||
};
|
||||
checkAvailable();
|
||||
});
|
||||
}
|
||||
|
||||
private async createConnection(host: SSHHostWithCredentials): Promise<Client> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new Client();
|
||||
const timeout = setTimeout(() => {
|
||||
client.end();
|
||||
reject(new Error('SSH connection timeout'));
|
||||
}, this.connectionTimeout);
|
||||
|
||||
client.on('ready', () => {
|
||||
clearTimeout(timeout);
|
||||
resolve(client);
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
});
|
||||
|
||||
try {
|
||||
client.connect(buildSshConfig(host));
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
releaseConnection(host: SSHHostWithCredentials, client: Client): void {
|
||||
const hostKey = this.getHostKey(host);
|
||||
const connections = this.connections.get(hostKey) || [];
|
||||
const pooled = connections.find(conn => conn.client === client);
|
||||
if (pooled) {
|
||||
pooled.inUse = false;
|
||||
pooled.lastUsed = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
const now = Date.now();
|
||||
const maxAge = 10 * 60 * 1000; // 10 minutes
|
||||
|
||||
for (const [hostKey, connections] of this.connections.entries()) {
|
||||
const activeConnections = connections.filter(conn => {
|
||||
if (!conn.inUse && (now - conn.lastUsed) > maxAge) {
|
||||
try {
|
||||
conn.client.end();
|
||||
} catch {
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if (activeConnections.length === 0) {
|
||||
this.connections.delete(hostKey);
|
||||
} else {
|
||||
this.connections.set(hostKey, activeConnections);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
clearInterval(this.cleanupInterval);
|
||||
for (const connections of this.connections.values()) {
|
||||
for (const conn of connections) {
|
||||
try {
|
||||
conn.client.end();
|
||||
} catch {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
this.connections.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Request queuing to prevent race conditions
|
||||
class RequestQueue {
|
||||
private queues = new Map<number, Array<() => Promise<any>>>();
|
||||
private processing = new Set<number>();
|
||||
|
||||
async queueRequest<T>(hostId: number, request: () => Promise<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const queue = this.queues.get(hostId) || [];
|
||||
queue.push(async () => {
|
||||
try {
|
||||
const result = await request();
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
this.queues.set(hostId, queue);
|
||||
this.processQueue(hostId);
|
||||
});
|
||||
}
|
||||
|
||||
private async processQueue(hostId: number): Promise<void> {
|
||||
if (this.processing.has(hostId)) return;
|
||||
|
||||
this.processing.add(hostId);
|
||||
const queue = this.queues.get(hostId) || [];
|
||||
|
||||
while (queue.length > 0) {
|
||||
const request = queue.shift();
|
||||
if (request) {
|
||||
try {
|
||||
await request();
|
||||
} catch (error) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.processing.delete(hostId);
|
||||
if (queue.length > 0) {
|
||||
this.processQueue(hostId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Metrics caching
|
||||
interface CachedMetrics {
|
||||
data: any;
|
||||
timestamp: number;
|
||||
hostId: number;
|
||||
}
|
||||
|
||||
class MetricsCache {
|
||||
private cache = new Map<number, CachedMetrics>();
|
||||
private ttl = 30000; // 30 seconds
|
||||
|
||||
get(hostId: number): any | null {
|
||||
const cached = this.cache.get(hostId);
|
||||
if (cached && (Date.now() - cached.timestamp) < this.ttl) {
|
||||
return cached.data;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
set(hostId: number, data: any): void {
|
||||
this.cache.set(hostId, {
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
hostId
|
||||
});
|
||||
}
|
||||
|
||||
clear(hostId?: number): void {
|
||||
if (hostId) {
|
||||
this.cache.delete(hostId);
|
||||
} else {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Global instances
|
||||
const connectionPool = new SSHConnectionPool();
|
||||
const requestQueue = new RequestQueue();
|
||||
const metricsCache = new MetricsCache();
|
||||
|
||||
type HostStatus = 'online' | 'offline';
|
||||
|
||||
interface SSHHostWithCredentials {
|
||||
@@ -40,6 +271,37 @@ type StatusEntry = {
|
||||
lastChecked: string;
|
||||
};
|
||||
|
||||
// Rate limiting middleware
|
||||
function rateLimitMiddleware(req: express.Request, res: express.Response, next: express.NextFunction) {
|
||||
const clientId = req.ip || 'unknown';
|
||||
const now = Date.now();
|
||||
const clientData = requestCounts.get(clientId);
|
||||
|
||||
if (!clientData || now > clientData.resetTime) {
|
||||
requestCounts.set(clientId, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
|
||||
return next();
|
||||
}
|
||||
|
||||
if (clientData.count >= RATE_LIMIT_MAX) {
|
||||
return res.status(429).json({
|
||||
error: 'Too many requests',
|
||||
retryAfter: Math.ceil((clientData.resetTime - now) / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
clientData.count++;
|
||||
next();
|
||||
}
|
||||
|
||||
// Input validation middleware
|
||||
function validateHostId(req: express.Request, res: express.Response, next: express.NextFunction) {
|
||||
const id = Number(req.params.id);
|
||||
if (!id || !Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'Invalid host ID' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.use(cors({
|
||||
origin: '*',
|
||||
@@ -55,7 +317,8 @@ app.use((req, res, next) => {
|
||||
}
|
||||
next();
|
||||
});
|
||||
app.use(express.json());
|
||||
app.use(express.json({ limit: '1mb' })); // Add request size limit
|
||||
app.use(rateLimitMiddleware);
|
||||
|
||||
|
||||
const hostStatuses: Map<number, StatusEntry> = new Map();
|
||||
@@ -219,45 +482,13 @@ function buildSshConfig(host: SSHHostWithCredentials): ConnectConfig {
|
||||
}
|
||||
|
||||
async function withSshConnection<T>(host: SSHHostWithCredentials, fn: (client: Client) => Promise<T>): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const client = new Client();
|
||||
let settled = false;
|
||||
|
||||
const onError = (err: Error) => {
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
try {
|
||||
client.end();
|
||||
} catch {
|
||||
}
|
||||
reject(err);
|
||||
}
|
||||
};
|
||||
|
||||
client.on('ready', async () => {
|
||||
const client = await connectionPool.getConnection(host);
|
||||
try {
|
||||
const result = await fn(client);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
try {
|
||||
client.end();
|
||||
} catch {
|
||||
return result;
|
||||
} finally {
|
||||
connectionPool.releaseConnection(host, client);
|
||||
}
|
||||
resolve(result);
|
||||
}
|
||||
} catch (err: any) {
|
||||
onError(err);
|
||||
}
|
||||
});
|
||||
|
||||
client.on('error', onError);
|
||||
client.on('timeout', () => onError(new Error('SSH connection timeout')));
|
||||
try {
|
||||
client.connect(buildSshConfig(host));
|
||||
} catch (err: any) {
|
||||
onError(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function execCommand(client: Client, command: string): Promise<{
|
||||
@@ -307,16 +538,29 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
memory: { percent: number | null; usedGiB: number | null; totalGiB: number | null };
|
||||
disk: { percent: number | null; usedHuman: string | null; totalHuman: string | null };
|
||||
}> {
|
||||
// Check cache first
|
||||
const cached = metricsCache.get(host.id);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
return requestQueue.queueRequest(host.id, async () => {
|
||||
return withSshConnection(host, async (client) => {
|
||||
let cpuPercent: number | null = null;
|
||||
let cores: number | null = null;
|
||||
let loadTriplet: [number, number, number] | null = null;
|
||||
|
||||
try {
|
||||
const stat1 = await execCommand(client, 'cat /proc/stat');
|
||||
// Execute all commands in parallel for better performance
|
||||
const [stat1, loadAvgOut, coresOut] = await Promise.all([
|
||||
execCommand(client, 'cat /proc/stat'),
|
||||
execCommand(client, 'cat /proc/loadavg'),
|
||||
execCommand(client, 'nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo')
|
||||
]);
|
||||
|
||||
// Wait for CPU calculation
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
const stat2 = await execCommand(client, 'cat /proc/stat');
|
||||
const loadAvgOut = await execCommand(client, 'cat /proc/loadavg');
|
||||
const coresOut = await execCommand(client, 'nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo');
|
||||
|
||||
const cpuLine1 = (stat1.stdout.split('\n').find(l => l.startsWith('cpu ')) || '').trim();
|
||||
const cpuLine2 = (stat2.stdout.split('\n').find(l => l.startsWith('cpu ')) || '').trim();
|
||||
@@ -337,6 +581,7 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
const coresNum = Number((coresOut.stdout || '').trim());
|
||||
cores = Number.isFinite(coresNum) && coresNum > 0 ? coresNum : null;
|
||||
} catch (e) {
|
||||
statsLogger.warn(`Failed to collect CPU metrics for host ${host.id}`, e);
|
||||
cpuPercent = null;
|
||||
cores = null;
|
||||
loadTriplet = null;
|
||||
@@ -363,6 +608,7 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
totalGiB = kibToGiB(totalKb);
|
||||
}
|
||||
} catch (e) {
|
||||
statsLogger.warn(`Failed to collect memory metrics for host ${host.id}`, e);
|
||||
memPercent = null;
|
||||
usedGiB = null;
|
||||
totalGiB = null;
|
||||
@@ -372,8 +618,10 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
let usedHuman: string | null = null;
|
||||
let totalHuman: string | null = null;
|
||||
try {
|
||||
const diskOutHuman = await execCommand(client, 'df -h -P / | tail -n +2');
|
||||
const diskOutBytes = await execCommand(client, 'df -B1 -P / | tail -n +2');
|
||||
const [diskOutHuman, diskOutBytes] = await Promise.all([
|
||||
execCommand(client, 'df -h -P / | tail -n +2'),
|
||||
execCommand(client, 'df -B1 -P / | tail -n +2')
|
||||
]);
|
||||
|
||||
const humanLine = diskOutHuman.stdout.split('\n').map(l => l.trim()).filter(Boolean)[0] || '';
|
||||
const bytesLine = diskOutBytes.stdout.split('\n').map(l => l.trim()).filter(Boolean)[0] || '';
|
||||
@@ -393,12 +641,13 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
statsLogger.warn(`Failed to collect disk metrics for host ${host.id}`, e);
|
||||
diskPercent = null;
|
||||
usedHuman = null;
|
||||
totalHuman = null;
|
||||
}
|
||||
|
||||
return {
|
||||
const result = {
|
||||
cpu: {percent: toFixedNum(cpuPercent, 0), cores, load: loadTriplet},
|
||||
memory: {
|
||||
percent: toFixedNum(memPercent, 0),
|
||||
@@ -407,6 +656,11 @@ async function collectMetrics(host: SSHHostWithCredentials): Promise<{
|
||||
},
|
||||
disk: {percent: toFixedNum(diskPercent, 0), usedHuman, totalHuman},
|
||||
};
|
||||
|
||||
// Cache the result
|
||||
metricsCache.set(host.id, result);
|
||||
return result;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -468,11 +722,8 @@ app.get('/status', async (req, res) => {
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
app.get('/status/:id', async (req, res) => {
|
||||
app.get('/status/:id', validateHostId, async (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({error: 'Invalid id'});
|
||||
}
|
||||
|
||||
try {
|
||||
const host = await fetchHostById(id);
|
||||
@@ -497,27 +748,64 @@ app.post('/refresh', async (req, res) => {
|
||||
res.json({message: 'Refreshed'});
|
||||
});
|
||||
|
||||
app.get('/metrics/:id', async (req, res) => {
|
||||
app.get('/metrics/:id', validateHostId, async (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!id) {
|
||||
return res.status(400).json({error: 'Invalid id'});
|
||||
}
|
||||
|
||||
try {
|
||||
const host = await fetchHostById(id);
|
||||
if (!host) {
|
||||
return res.status(404).json({error: 'Host not found'});
|
||||
}
|
||||
const metrics = await collectMetrics(host);
|
||||
res.json({...metrics, lastChecked: new Date().toISOString()});
|
||||
} catch (err) {
|
||||
statsLogger.error('Failed to collect metrics', err);
|
||||
return res.json({
|
||||
|
||||
// Check if host is online first
|
||||
const isOnline = await tcpPing(host.ip, host.port, 5000);
|
||||
if (!isOnline) {
|
||||
return res.status(503).json({
|
||||
error: 'Host is offline',
|
||||
cpu: {percent: null, cores: null, load: null},
|
||||
memory: {percent: null, usedGiB: null, totalGiB: null},
|
||||
disk: {percent: null, usedHuman: null, totalHuman: null},
|
||||
lastChecked: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
const metrics = await collectMetrics(host);
|
||||
res.json({...metrics, lastChecked: new Date().toISOString()});
|
||||
} catch (err) {
|
||||
statsLogger.error('Failed to collect metrics', err);
|
||||
|
||||
// Return proper error response instead of empty data
|
||||
if (err instanceof Error && err.message.includes('timeout')) {
|
||||
return res.status(504).json({
|
||||
error: 'Metrics collection timeout',
|
||||
cpu: {percent: null, cores: null, load: null},
|
||||
memory: {percent: null, usedGiB: null, totalGiB: null},
|
||||
disk: {percent: null, usedHuman: null, totalHuman: null},
|
||||
lastChecked: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(500).json({
|
||||
error: 'Failed to collect metrics',
|
||||
cpu: {percent: null, cores: null, load: null},
|
||||
memory: {percent: null, usedGiB: null, totalGiB: null},
|
||||
disk: {percent: null, usedHuman: null, totalHuman: null},
|
||||
lastChecked: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGINT', () => {
|
||||
statsLogger.info('Received SIGINT, shutting down gracefully');
|
||||
connectionPool.destroy();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.on('SIGTERM', () => {
|
||||
statsLogger.info('Received SIGTERM, shutting down gracefully');
|
||||
connectionPool.destroy();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
const PORT = 8085;
|
||||
|
||||
@@ -32,6 +32,8 @@ export function Server({
|
||||
const [serverStatus, setServerStatus] = React.useState<'online' | 'offline'>('offline');
|
||||
const [metrics, setMetrics] = React.useState<ServerMetrics | null>(null);
|
||||
const [currentHostConfig, setCurrentHostConfig] = React.useState(hostConfig);
|
||||
const [isLoadingMetrics, setIsLoadingMetrics] = React.useState(false);
|
||||
const [isRefreshing, setIsRefreshing] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
setCurrentHostConfig(hostConfig);
|
||||
@@ -98,6 +100,7 @@ export function Server({
|
||||
const fetchMetrics = async () => {
|
||||
if (!currentHostConfig?.id) return;
|
||||
try {
|
||||
setIsLoadingMetrics(true);
|
||||
const data = await getServerMetricsById(currentHostConfig.id);
|
||||
if (!cancelled) {
|
||||
setMetrics(data);
|
||||
@@ -108,6 +111,10 @@ export function Server({
|
||||
setMetrics(null);
|
||||
toast.error(t('serverStats.failedToFetchMetrics'));
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsLoadingMetrics(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,21 +167,25 @@ export function Server({
|
||||
<div className="h-full w-full flex flex-col">
|
||||
|
||||
{/* Top Header */}
|
||||
<div className="flex items-center justify-between px-3 pt-2 pb-2">
|
||||
<div className="flex items-center gap-4">
|
||||
<h1 className="font-bold text-lg">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between px-4 pt-3 pb-3 gap-3">
|
||||
<div className="flex items-center gap-4 min-w-0">
|
||||
<div className="min-w-0">
|
||||
<h1 className="font-bold text-lg truncate">
|
||||
{currentHostConfig?.folder} / {title}
|
||||
</h1>
|
||||
</div>
|
||||
<Status status={serverStatus} className="!bg-transparent !p-0.75 flex-shrink-0">
|
||||
<StatusIndicator/>
|
||||
</Status>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={isRefreshing}
|
||||
onClick={async () => {
|
||||
if (currentHostConfig?.id) {
|
||||
try {
|
||||
setIsRefreshing(true);
|
||||
const res = await getServerStatusById(currentHostConfig.id);
|
||||
setServerStatus(res?.status === 'online' ? 'online' : 'offline');
|
||||
const data = await getServerMetricsById(currentHostConfig.id);
|
||||
@@ -182,12 +193,21 @@ export function Server({
|
||||
} catch {
|
||||
setServerStatus('offline');
|
||||
setMetrics(null);
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
}
|
||||
}}
|
||||
title={t('serverStats.refreshStatusAndMetrics')}
|
||||
>
|
||||
{t('serverStats.refreshStatus')}
|
||||
{isRefreshing ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-4 h-4 border-2 border-gray-300 border-t-transparent rounded-full animate-spin"></div>
|
||||
{t('serverStats.refreshing')}
|
||||
</div>
|
||||
) : (
|
||||
t('serverStats.refreshStatus')
|
||||
)}
|
||||
</Button>
|
||||
{currentHostConfig?.enableFileManager && (
|
||||
<Button
|
||||
@@ -215,53 +235,118 @@ export function Server({
|
||||
<Separator className="p-0.25 w-full"/>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="rounded-lg border-2 border-dark-border m-3 bg-dark-bg-darker flex flex-row items-stretch">
|
||||
{/* CPU */}
|
||||
<div className="flex-1 min-w-0 px-2 py-2">
|
||||
<h1 className="font-bold xt-lg flex flex-row gap-2 mb-2">
|
||||
<Cpu/>
|
||||
<div className="rounded-lg border-2 border-dark-border m-3 bg-dark-bg-darker p-4">
|
||||
{isLoadingMetrics && !metrics ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-6 h-6 border-2 border-blue-400 border-t-transparent rounded-full animate-spin"></div>
|
||||
<span className="text-gray-300">{t('serverStats.loadingMetrics')}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : !metrics && serverStatus === 'offline' ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="text-center">
|
||||
<div className="w-12 h-12 mx-auto mb-3 rounded-full bg-red-500/20 flex items-center justify-center">
|
||||
<div className="w-6 h-6 border-2 border-red-400 rounded-full"></div>
|
||||
</div>
|
||||
<p className="text-gray-300 mb-1">{t('serverStats.serverOffline')}</p>
|
||||
<p className="text-sm text-gray-500">{t('serverStats.cannotFetchMetrics')}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 lg:gap-6">
|
||||
{/* CPU Stats */}
|
||||
<div className="space-y-3 p-4 rounded-lg bg-dark-bg/50 border border-dark-border/50 hover:bg-dark-bg/70 transition-colors duration-200">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Cpu className="h-5 w-5 text-blue-400" />
|
||||
<h3 className="font-semibold text-lg text-white">{t('serverStats.cpuUsage')}</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-gray-300">
|
||||
{(() => {
|
||||
const pct = metrics?.cpu?.percent;
|
||||
const cores = metrics?.cpu?.cores;
|
||||
const la = metrics?.cpu?.load;
|
||||
const pctText = (typeof pct === 'number') ? `${pct}%` : 'N/A';
|
||||
const coresText = (typeof cores === 'number') ? t('serverStats.cpuCores', {count: cores}) : t('serverStats.naCpus');
|
||||
const laText = (la && la.length === 3)
|
||||
? t('serverStats.loadAverage', {avg1: la[0].toFixed(2), avg5: la[1].toFixed(2), avg15: la[2].toFixed(2)})
|
||||
: t('serverStats.loadAverageNA');
|
||||
return `${t('serverStats.cpuUsage')} - ${pctText} ${t('serverStats.of')} ${coresText} (${laText})`;
|
||||
return `${pctText} ${t('serverStats.of')} ${coresText}`;
|
||||
})()}
|
||||
</h1>
|
||||
|
||||
<Progress value={typeof metrics?.cpu?.percent === 'number' ? metrics!.cpu!.percent! : 0}/>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Separator className="p-0.5 self-stretch" orientation="vertical"/>
|
||||
<div className="relative">
|
||||
<Progress
|
||||
value={typeof metrics?.cpu?.percent === 'number' ? metrics!.cpu!.percent! : 0}
|
||||
className="h-2"
|
||||
/>
|
||||
{typeof metrics?.cpu?.percent === 'number' && metrics.cpu.percent > 80 && (
|
||||
<div className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Memory */}
|
||||
<div className="flex-1 min-w-0 px-2 py-2">
|
||||
<h1 className="font-bold xt-lg flex flex-row gap-2 mb-2">
|
||||
<MemoryStick/>
|
||||
<div className="text-xs text-gray-500">
|
||||
{metrics?.cpu?.load ?
|
||||
`Load: ${metrics.cpu.load[0].toFixed(2)}, ${metrics.cpu.load[1].toFixed(2)}, ${metrics.cpu.load[2].toFixed(2)}` :
|
||||
'Load: N/A'
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Memory Stats */}
|
||||
<div className="space-y-3 p-4 rounded-lg bg-dark-bg/50 border border-dark-border/50 hover:bg-dark-bg/70 transition-colors duration-200">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<MemoryStick className="h-5 w-5 text-green-400" />
|
||||
<h3 className="font-semibold text-lg text-white">{t('serverStats.memoryUsage')}</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-gray-300">
|
||||
{(() => {
|
||||
const pct = metrics?.memory?.percent;
|
||||
const used = metrics?.memory?.usedGiB;
|
||||
const total = metrics?.memory?.totalGiB;
|
||||
const pctText = (typeof pct === 'number') ? `${pct}%` : 'N/A';
|
||||
const usedText = (typeof used === 'number') ? `${used} GiB` : 'N/A';
|
||||
const totalText = (typeof total === 'number') ? `${total} GiB` : 'N/A';
|
||||
return `${t('serverStats.memoryUsage')} - ${pctText} (${usedText} ${t('serverStats.of')} ${totalText})`;
|
||||
const usedText = (typeof used === 'number') ? `${used.toFixed(1)} GiB` : 'N/A';
|
||||
const totalText = (typeof total === 'number') ? `${total.toFixed(1)} GiB` : 'N/A';
|
||||
return `${pctText} (${usedText} ${t('serverStats.of')} ${totalText})`;
|
||||
})()}
|
||||
</h1>
|
||||
|
||||
<Progress value={typeof metrics?.memory?.percent === 'number' ? metrics!.memory!.percent! : 0}/>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Separator className="p-0.5 self-stretch" orientation="vertical"/>
|
||||
<div className="relative">
|
||||
<Progress
|
||||
value={typeof metrics?.memory?.percent === 'number' ? metrics!.memory!.percent! : 0}
|
||||
className="h-2"
|
||||
/>
|
||||
{typeof metrics?.memory?.percent === 'number' && metrics.memory.percent > 85 && (
|
||||
<div className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Root Storage */}
|
||||
<div className="flex-1 min-w-0 px-2 py-2">
|
||||
<h1 className="font-bold xt-lg flex flex-row gap-2 mb-2">
|
||||
<HardDrive/>
|
||||
<div className="text-xs text-gray-500">
|
||||
{(() => {
|
||||
const used = metrics?.memory?.usedGiB;
|
||||
const total = metrics?.memory?.totalGiB;
|
||||
const free = (typeof used === 'number' && typeof total === 'number') ? (total - used).toFixed(1) : 'N/A';
|
||||
return `Free: ${free} GiB`;
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Disk Stats */}
|
||||
<div className="space-y-3 p-4 rounded-lg bg-dark-bg/50 border border-dark-border/50 hover:bg-dark-bg/70 transition-colors duration-200">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<HardDrive className="h-5 w-5 text-orange-400" />
|
||||
<h3 className="font-semibold text-lg text-white">{t('serverStats.rootStorageSpace')}</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-gray-300">
|
||||
{(() => {
|
||||
const pct = metrics?.disk?.percent;
|
||||
const used = metrics?.disk?.usedHuman;
|
||||
@@ -269,12 +354,32 @@ export function Server({
|
||||
const pctText = (typeof pct === 'number') ? `${pct}%` : 'N/A';
|
||||
const usedText = used ?? 'N/A';
|
||||
const totalText = total ?? 'N/A';
|
||||
return `${t('serverStats.rootStorageSpace')} - ${pctText} (${usedText} ${t('serverStats.of')} ${totalText})`;
|
||||
return `${pctText} (${usedText} ${t('serverStats.of')} ${totalText})`;
|
||||
})()}
|
||||
</h1>
|
||||
|
||||
<Progress value={typeof metrics?.disk?.percent === 'number' ? metrics!.disk!.percent! : 0}/>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Progress
|
||||
value={typeof metrics?.disk?.percent === 'number' ? metrics!.disk!.percent! : 0}
|
||||
className="h-2"
|
||||
/>
|
||||
{typeof metrics?.disk?.percent === 'number' && metrics.disk.percent > 90 && (
|
||||
<div className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full animate-pulse"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-gray-500">
|
||||
{(() => {
|
||||
const used = metrics?.disk?.usedHuman;
|
||||
const total = metrics?.disk?.totalHuman;
|
||||
return used && total ? `Available: ${total}` : 'Available: N/A';
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* SSH Tunnels */}
|
||||
|
||||
Reference in New Issue
Block a user