After configuring VPS health
This commit is contained in:
parent
072d64d9ed
commit
a7db8846f4
13
.env.example
13
.env.example
@ -116,6 +116,19 @@ APP_PUBLIC_URL=https://tloto.net:9443
|
|||||||
# SSL_STATUS_WARN_DAYS=30
|
# SSL_STATUS_WARN_DAYS=30
|
||||||
# SSL_STATUS_CRITICAL_DAYS=7
|
# SSL_STATUS_CRITICAL_DAYS=7
|
||||||
# SSL_STATUS_TIMEOUT_MS=8000
|
# SSL_STATUS_TIMEOUT_MS=8000
|
||||||
|
|
||||||
|
# Admin VPS monitoring (profile: monitoring — Prometheus/node-exporter/cAdvisor, no public ports)
|
||||||
|
# PROMETHEUS_URL=http://prometheus:9090
|
||||||
|
# MONITORING_RETENTION=15d
|
||||||
|
# VPS_MONITOR_TIMEOUT_MS=8000
|
||||||
|
# VPS_MONITOR_CPU_WARN=70
|
||||||
|
# VPS_MONITOR_CPU_CRITICAL=90
|
||||||
|
# VPS_MONITOR_MEM_WARN=75
|
||||||
|
# VPS_MONITOR_MEM_CRITICAL=90
|
||||||
|
# VPS_MONITOR_DISK_WARN=75
|
||||||
|
# VPS_MONITOR_DISK_CRITICAL=90
|
||||||
|
# VPS_MONITOR_LOAD_WARN=4
|
||||||
|
# VPS_MONITOR_LOAD_CRITICAL=8
|
||||||
INITIAL_SETUP_TOKEN=your-random-setup-token-min-32-chars
|
INITIAL_SETUP_TOKEN=your-random-setup-token-min-32-chars
|
||||||
# Emergency Super Admin 2FA reset (CLI / Docker only — not an HTTP API). Min 32 chars; distinct from JWT/setup tokens.
|
# Emergency Super Admin 2FA reset (CLI / Docker only — not an HTTP API). Min 32 chars; distinct from JWT/setup tokens.
|
||||||
# Generate: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
|
# Generate: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
|
||||||
|
|||||||
@ -63,6 +63,9 @@ APP_PUBLIC_URL=http://localhost:5173
|
|||||||
# SSL_STATUS_WARN_DAYS=30
|
# SSL_STATUS_WARN_DAYS=30
|
||||||
# SSL_STATUS_CRITICAL_DAYS=7
|
# SSL_STATUS_CRITICAL_DAYS=7
|
||||||
# SSL_STATUS_TIMEOUT_MS=8000
|
# SSL_STATUS_TIMEOUT_MS=8000
|
||||||
|
# Admin VPS monitor (Prometheus internal URL — never expose :9090 publicly)
|
||||||
|
# PROMETHEUS_URL=http://prometheus:9090
|
||||||
|
# VPS_MONITOR_TIMEOUT_MS=8000
|
||||||
# EMAIL_TRANSPORT=console # omit or set smtp when SMTP_* vars are configured
|
# EMAIL_TRANSPORT=console # omit or set smtp when SMTP_* vars are configured
|
||||||
# SMTP_HOST=smtp.gmail.com
|
# SMTP_HOST=smtp.gmail.com
|
||||||
# SMTP_PORT=587
|
# SMTP_PORT=587
|
||||||
|
|||||||
@ -316,4 +316,19 @@ export const config = {
|
|||||||
criticalDays: readEnvInt('SSL_STATUS_CRITICAL_DAYS', 7, 1, 30),
|
criticalDays: readEnvInt('SSL_STATUS_CRITICAL_DAYS', 7, 1, 30),
|
||||||
timeoutMs: readEnvInt('SSL_STATUS_TIMEOUT_MS', 8_000, 1000, 60_000),
|
timeoutMs: readEnvInt('SSL_STATUS_TIMEOUT_MS', 8_000, 1000, 60_000),
|
||||||
},
|
},
|
||||||
|
/** Admin VPS monitor — Prometheus HTTP only (allowlisted PromQL). */
|
||||||
|
vpsMonitor: {
|
||||||
|
prometheusUrl: (process.env.PROMETHEUS_URL || 'http://prometheus:9090').trim(),
|
||||||
|
timeoutMs: readEnvInt('VPS_MONITOR_TIMEOUT_MS', 8_000, 1000, 30_000),
|
||||||
|
thresholds: {
|
||||||
|
cpuWarn: readEnvInt('VPS_MONITOR_CPU_WARN', 70, 1, 100),
|
||||||
|
cpuCritical: readEnvInt('VPS_MONITOR_CPU_CRITICAL', 90, 1, 100),
|
||||||
|
memWarn: readEnvInt('VPS_MONITOR_MEM_WARN', 75, 1, 100),
|
||||||
|
memCritical: readEnvInt('VPS_MONITOR_MEM_CRITICAL', 90, 1, 100),
|
||||||
|
diskWarn: readEnvInt('VPS_MONITOR_DISK_WARN', 75, 1, 100),
|
||||||
|
diskCritical: readEnvInt('VPS_MONITOR_DISK_CRITICAL', 90, 1, 100),
|
||||||
|
loadWarn: readEnvInt('VPS_MONITOR_LOAD_WARN', 4, 1, 256),
|
||||||
|
loadCritical: readEnvInt('VPS_MONITOR_LOAD_CRITICAL', 8, 1, 256),
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
59
backend/src/controllers/vpsMonitorController.ts
Normal file
59
backend/src/controllers/vpsMonitorController.ts
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
/**
|
||||||
|
* Admin VPS monitor — read-only metrics for the back-office.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Response } from 'express';
|
||||||
|
import { AuthRequest } from '../middleware/auth';
|
||||||
|
import * as vpsMonitorService from '../services/vpsMonitorService';
|
||||||
|
|
||||||
|
export async function getOverview(_req: AuthRequest, res: Response): Promise<void> {
|
||||||
|
try {
|
||||||
|
const data = await vpsMonitorService.getOverview();
|
||||||
|
res.json(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
res.status(502).json({ error: e instanceof Error ? e.message : 'VPS overview unavailable' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTimeseries(req: AuthRequest, res: Response): Promise<void> {
|
||||||
|
try {
|
||||||
|
const metric = vpsMonitorService.parseMetric(req.query.metric);
|
||||||
|
const range = vpsMonitorService.parseRange(req.query.range ?? '1h');
|
||||||
|
if (!metric || !range) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: 'Invalid metric or range',
|
||||||
|
allowedMetrics: ['cpu', 'mem', 'disk', 'net_in', 'net_out', 'load1'],
|
||||||
|
allowedRanges: ['1h', '6h', '24h', '7d'],
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await vpsMonitorService.getTimeseries(metric, range);
|
||||||
|
res.json(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
res.status(502).json({ error: e instanceof Error ? e.message : 'Timeseries unavailable' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getContainers(req: AuthRequest, res: Response): Promise<void> {
|
||||||
|
try {
|
||||||
|
const limitRaw = Number(req.query.limit ?? 20);
|
||||||
|
const limit = Number.isFinite(limitRaw) ? limitRaw : 20;
|
||||||
|
const data = await vpsMonitorService.getContainers(limit);
|
||||||
|
res.json(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
res.status(502).json({ error: e instanceof Error ? e.message : 'Container metrics unavailable' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getServices(_req: AuthRequest, res: Response): Promise<void> {
|
||||||
|
try {
|
||||||
|
const data = await vpsMonitorService.getServices();
|
||||||
|
res.json(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
res.status(502).json({ error: e instanceof Error ? e.message : 'Service status unavailable' });
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -122,4 +122,13 @@ export const verificationEmailLimiter = rateLimit({
|
|||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** Stricter limiter for admin VPS monitor metrics (polling-friendly but bounded). */
|
||||||
|
export const vpsMonitorLimiter = rateLimit({
|
||||||
|
windowMs: 60 * 1000,
|
||||||
|
max: 30,
|
||||||
|
message: { error: 'Too many monitoring requests' },
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -210,6 +210,9 @@ export const PERMISSION_CATALOG: PermissionDef[] = [
|
|||||||
p('mobile_releases', 'view', 'View mobile app versions', 'mobile_releases', ['settings.admin']),
|
p('mobile_releases', 'view', 'View mobile app versions', 'mobile_releases', ['settings.admin']),
|
||||||
p('mobile_releases', 'manage', 'Publish and manage mobile APK releases', 'mobile_releases', ['settings.admin']),
|
p('mobile_releases', 'manage', 'Publish and manage mobile APK releases', 'mobile_releases', ['settings.admin']),
|
||||||
|
|
||||||
|
// VPS infrastructure monitor (read-only Prometheus metrics)
|
||||||
|
p('vps_monitor', 'view', 'View VPS and Docker resource metrics', 'vps_monitor'),
|
||||||
|
|
||||||
// RBAC self-management
|
// RBAC self-management
|
||||||
p('rbac', 'view', 'View roles and permissions', 'rbac', ['user.manage_roles']),
|
p('rbac', 'view', 'View roles and permissions', 'rbac', ['user.manage_roles']),
|
||||||
p('rbac', 'manage', 'Create and edit custom roles', 'rbac', ['user.manage_roles']),
|
p('rbac', 'manage', 'Create and edit custom roles', 'rbac', ['user.manage_roles']),
|
||||||
@ -257,6 +260,7 @@ export const DEFAULT_ADMIN_PERMISSION_KEYS = [
|
|||||||
'admin.solo_encouragement.edit',
|
'admin.solo_encouragement.edit',
|
||||||
'admin.mobile_releases.view',
|
'admin.mobile_releases.view',
|
||||||
'admin.mobile_releases.manage',
|
'admin.mobile_releases.manage',
|
||||||
|
'admin.vps_monitor.view',
|
||||||
'admin.rbac.view',
|
'admin.rbac.view',
|
||||||
'admin.rbac.manage',
|
'admin.rbac.manage',
|
||||||
];
|
];
|
||||||
|
|||||||
@ -96,7 +96,13 @@ import {
|
|||||||
uuidParamSchema,
|
uuidParamSchema,
|
||||||
alertIdParamSchema,
|
alertIdParamSchema,
|
||||||
} from '../validation/querySchemas';
|
} from '../validation/querySchemas';
|
||||||
import { apiLimiter, loginLimiter, verificationEmailLimiter, passwordResetLimiter } from '../middleware/rateLimit';
|
import {
|
||||||
|
apiLimiter,
|
||||||
|
loginLimiter,
|
||||||
|
verificationEmailLimiter,
|
||||||
|
passwordResetLimiter,
|
||||||
|
vpsMonitorLimiter,
|
||||||
|
} from '../middleware/rateLimit';
|
||||||
import * as authController from '../controllers/authController';
|
import * as authController from '../controllers/authController';
|
||||||
import * as walletController from '../controllers/walletController';
|
import * as walletController from '../controllers/walletController';
|
||||||
import * as withdrawalController from '../controllers/withdrawalController';
|
import * as withdrawalController from '../controllers/withdrawalController';
|
||||||
@ -122,6 +128,7 @@ import * as soloEncouragementController from '../controllers/soloEncouragementCo
|
|||||||
import * as shareCardController from '../controllers/shareCardController';
|
import * as shareCardController from '../controllers/shareCardController';
|
||||||
import * as mobileAppReleaseController from '../controllers/mobileAppReleaseController';
|
import * as mobileAppReleaseController from '../controllers/mobileAppReleaseController';
|
||||||
import * as sslCertificateController from '../controllers/sslCertificateController';
|
import * as sslCertificateController from '../controllers/sslCertificateController';
|
||||||
|
import * as vpsMonitorController from '../controllers/vpsMonitorController';
|
||||||
import { apkUpload } from '../middleware/apkUpload';
|
import { apkUpload } from '../middleware/apkUpload';
|
||||||
import { requireSupportedAppVersion } from '../middleware/requireSupportedAppVersion';
|
import { requireSupportedAppVersion } from '../middleware/requireSupportedAppVersion';
|
||||||
import {
|
import {
|
||||||
@ -751,6 +758,39 @@ router.get(
|
|||||||
sslCertificateController.getStatus
|
sslCertificateController.getStatus
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/admin/vps-monitor/overview',
|
||||||
|
requireRoles('admin'),
|
||||||
|
requirePermissions('admin.vps_monitor.view'),
|
||||||
|
vpsMonitorLimiter,
|
||||||
|
auditAction('vps_monitor_overview', 'vps_monitor'),
|
||||||
|
vpsMonitorController.getOverview
|
||||||
|
);
|
||||||
|
router.get(
|
||||||
|
'/admin/vps-monitor/timeseries',
|
||||||
|
requireRoles('admin'),
|
||||||
|
requirePermissions('admin.vps_monitor.view'),
|
||||||
|
vpsMonitorLimiter,
|
||||||
|
auditAction('vps_monitor_timeseries', 'vps_monitor'),
|
||||||
|
vpsMonitorController.getTimeseries
|
||||||
|
);
|
||||||
|
router.get(
|
||||||
|
'/admin/vps-monitor/containers',
|
||||||
|
requireRoles('admin'),
|
||||||
|
requirePermissions('admin.vps_monitor.view'),
|
||||||
|
vpsMonitorLimiter,
|
||||||
|
auditAction('vps_monitor_containers', 'vps_monitor'),
|
||||||
|
vpsMonitorController.getContainers
|
||||||
|
);
|
||||||
|
router.get(
|
||||||
|
'/admin/vps-monitor/services',
|
||||||
|
requireRoles('admin'),
|
||||||
|
requirePermissions('admin.vps_monitor.view'),
|
||||||
|
vpsMonitorLimiter,
|
||||||
|
auditAction('vps_monitor_services', 'vps_monitor'),
|
||||||
|
vpsMonitorController.getServices
|
||||||
|
);
|
||||||
|
|
||||||
router.get('/admin/settings', requireRoles('admin'), requirePermissions('settings.admin'), settingsController.getSettings);
|
router.get('/admin/settings', requireRoles('admin'), requirePermissions('settings.admin'), settingsController.getSettings);
|
||||||
router.patch(
|
router.patch(
|
||||||
'/admin/settings',
|
'/admin/settings',
|
||||||
|
|||||||
353
backend/src/services/vpsMonitorService.ts
Normal file
353
backend/src/services/vpsMonitorService.ts
Normal file
@ -0,0 +1,353 @@
|
|||||||
|
/**
|
||||||
|
* Read-only VPS metrics via Prometheus (allowlisted PromQL only).
|
||||||
|
* Never executes shell/Docker commands; never mounts docker.sock.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { config } from '../config';
|
||||||
|
|
||||||
|
export type TimeseriesMetric = 'cpu' | 'mem' | 'disk' | 'net_in' | 'net_out' | 'load1';
|
||||||
|
export type TimeseriesRange = '1h' | '6h' | '24h' | '7d';
|
||||||
|
|
||||||
|
const METRIC_QUERIES: Record<TimeseriesMetric, string> = {
|
||||||
|
cpu: '100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)',
|
||||||
|
mem: '(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100',
|
||||||
|
disk:
|
||||||
|
'(1 - (sum(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs"}) / sum(node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs"}))) * 100',
|
||||||
|
net_in:
|
||||||
|
'sum(rate(node_network_receive_bytes_total{device!~"lo|veth.*|br-.*|docker.*|tunl.*"}[5m]))',
|
||||||
|
net_out:
|
||||||
|
'sum(rate(node_network_transmit_bytes_total{device!~"lo|veth.*|br-.*|docker.*|tunl.*"}[5m]))',
|
||||||
|
load1: 'node_load1',
|
||||||
|
};
|
||||||
|
|
||||||
|
const RANGE_SECONDS: Record<TimeseriesRange, number> = {
|
||||||
|
'1h': 3600,
|
||||||
|
'6h': 6 * 3600,
|
||||||
|
'24h': 24 * 3600,
|
||||||
|
'7d': 7 * 24 * 3600,
|
||||||
|
};
|
||||||
|
|
||||||
|
type PromVectorResult = {
|
||||||
|
status: string;
|
||||||
|
data?: {
|
||||||
|
resultType: string;
|
||||||
|
result: Array<{
|
||||||
|
metric: Record<string, string>;
|
||||||
|
value?: [number, string];
|
||||||
|
values?: Array<[number, string]>;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function baseUrl(): string {
|
||||||
|
return config.vpsMonitor.prometheusUrl.replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function promGet(path: string, search: Record<string, string>): Promise<PromVectorResult> {
|
||||||
|
const url = new URL(path, `${baseUrl()}/`);
|
||||||
|
for (const [k, v] of Object.entries(search)) url.searchParams.set(k, v);
|
||||||
|
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), config.vpsMonitor.timeoutMs);
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'GET',
|
||||||
|
signal: ctrl.signal,
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Prometheus HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return (await res.json()) as PromVectorResult;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function queryInstant(query: string): Promise<number | null> {
|
||||||
|
const body = await promGet('/api/v1/query', { query });
|
||||||
|
if (body.status !== 'success') return null;
|
||||||
|
const v = body.data?.result?.[0]?.value?.[1];
|
||||||
|
if (v == null) return null;
|
||||||
|
const n = Number(v);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function queryRange(
|
||||||
|
query: string,
|
||||||
|
range: TimeseriesRange
|
||||||
|
): Promise<Array<{ t: number; v: number }>> {
|
||||||
|
const end = Math.floor(Date.now() / 1000);
|
||||||
|
const start = end - RANGE_SECONDS[range];
|
||||||
|
const step = range === '7d' ? 900 : range === '24h' ? 120 : range === '6h' ? 60 : 30;
|
||||||
|
const body = await promGet('/api/v1/query_range', {
|
||||||
|
query,
|
||||||
|
start: String(start),
|
||||||
|
end: String(end),
|
||||||
|
step: String(step),
|
||||||
|
});
|
||||||
|
if (body.status !== 'success') return [];
|
||||||
|
const values = body.data?.result?.[0]?.values ?? [];
|
||||||
|
return values
|
||||||
|
.map(([ts, raw]) => ({ t: Number(ts) * 1000, v: Number(raw) }))
|
||||||
|
.filter((p) => Number.isFinite(p.t) && Number.isFinite(p.v));
|
||||||
|
}
|
||||||
|
|
||||||
|
function classify(
|
||||||
|
value: number | null,
|
||||||
|
warn: number,
|
||||||
|
critical: number,
|
||||||
|
higherIsWorse = true
|
||||||
|
): 'ok' | 'warning' | 'critical' | 'unknown' {
|
||||||
|
if (value == null || !Number.isFinite(value)) return 'unknown';
|
||||||
|
if (higherIsWorse) {
|
||||||
|
if (value >= critical) return 'critical';
|
||||||
|
if (value >= warn) return 'warning';
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VpsOverview = {
|
||||||
|
checkedAt: string;
|
||||||
|
prometheusReachable: boolean;
|
||||||
|
cpuPercent: number | null;
|
||||||
|
memPercent: number | null;
|
||||||
|
memUsedBytes: number | null;
|
||||||
|
memTotalBytes: number | null;
|
||||||
|
diskPercent: number | null;
|
||||||
|
diskUsedBytes: number | null;
|
||||||
|
diskTotalBytes: number | null;
|
||||||
|
load1: number | null;
|
||||||
|
load5: number | null;
|
||||||
|
load15: number | null;
|
||||||
|
netReceiveBps: number | null;
|
||||||
|
netTransmitBps: number | null;
|
||||||
|
status: {
|
||||||
|
cpu: 'ok' | 'warning' | 'critical' | 'unknown';
|
||||||
|
mem: 'ok' | 'warning' | 'critical' | 'unknown';
|
||||||
|
disk: 'ok' | 'warning' | 'critical' | 'unknown';
|
||||||
|
load: 'ok' | 'warning' | 'critical' | 'unknown';
|
||||||
|
};
|
||||||
|
thresholds: {
|
||||||
|
cpuWarn: number;
|
||||||
|
cpuCritical: number;
|
||||||
|
memWarn: number;
|
||||||
|
memCritical: number;
|
||||||
|
diskWarn: number;
|
||||||
|
diskCritical: number;
|
||||||
|
loadWarn: number;
|
||||||
|
loadCritical: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getOverview(): Promise<VpsOverview> {
|
||||||
|
const th = config.vpsMonitor.thresholds;
|
||||||
|
const empty = (reachable: boolean): VpsOverview => ({
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
prometheusReachable: reachable,
|
||||||
|
cpuPercent: null,
|
||||||
|
memPercent: null,
|
||||||
|
memUsedBytes: null,
|
||||||
|
memTotalBytes: null,
|
||||||
|
diskPercent: null,
|
||||||
|
diskUsedBytes: null,
|
||||||
|
diskTotalBytes: null,
|
||||||
|
load1: null,
|
||||||
|
load5: null,
|
||||||
|
load15: null,
|
||||||
|
netReceiveBps: null,
|
||||||
|
netTransmitBps: null,
|
||||||
|
status: { cpu: 'unknown', mem: 'unknown', disk: 'unknown', load: 'unknown' },
|
||||||
|
thresholds: {
|
||||||
|
cpuWarn: th.cpuWarn,
|
||||||
|
cpuCritical: th.cpuCritical,
|
||||||
|
memWarn: th.memWarn,
|
||||||
|
memCritical: th.memCritical,
|
||||||
|
diskWarn: th.diskWarn,
|
||||||
|
diskCritical: th.diskCritical,
|
||||||
|
loadWarn: th.loadWarn,
|
||||||
|
loadCritical: th.loadCritical,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [
|
||||||
|
cpuPercent,
|
||||||
|
memPercent,
|
||||||
|
memAvail,
|
||||||
|
memTotal,
|
||||||
|
diskPercent,
|
||||||
|
diskAvail,
|
||||||
|
diskSize,
|
||||||
|
load1,
|
||||||
|
load5,
|
||||||
|
load15,
|
||||||
|
netIn,
|
||||||
|
netOut,
|
||||||
|
] = await Promise.all([
|
||||||
|
queryInstant(METRIC_QUERIES.cpu),
|
||||||
|
queryInstant(METRIC_QUERIES.mem),
|
||||||
|
queryInstant('node_memory_MemAvailable_bytes'),
|
||||||
|
queryInstant('node_memory_MemTotal_bytes'),
|
||||||
|
queryInstant(METRIC_QUERIES.disk),
|
||||||
|
queryInstant('sum(node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs"})'),
|
||||||
|
queryInstant('sum(node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs"})'),
|
||||||
|
queryInstant('node_load1'),
|
||||||
|
queryInstant('node_load5'),
|
||||||
|
queryInstant('node_load15'),
|
||||||
|
queryInstant(METRIC_QUERIES.net_in),
|
||||||
|
queryInstant(METRIC_QUERIES.net_out),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const memUsed =
|
||||||
|
memTotal != null && memAvail != null ? Math.max(0, memTotal - memAvail) : null;
|
||||||
|
const diskUsed =
|
||||||
|
diskSize != null && diskAvail != null ? Math.max(0, diskSize - diskAvail) : null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
prometheusReachable: true,
|
||||||
|
cpuPercent,
|
||||||
|
memPercent,
|
||||||
|
memUsedBytes: memUsed,
|
||||||
|
memTotalBytes: memTotal,
|
||||||
|
diskPercent,
|
||||||
|
diskUsedBytes: diskUsed,
|
||||||
|
diskTotalBytes: diskSize,
|
||||||
|
load1,
|
||||||
|
load5,
|
||||||
|
load15,
|
||||||
|
netReceiveBps: netIn,
|
||||||
|
netTransmitBps: netOut,
|
||||||
|
status: {
|
||||||
|
cpu: classify(cpuPercent, th.cpuWarn, th.cpuCritical),
|
||||||
|
mem: classify(memPercent, th.memWarn, th.memCritical),
|
||||||
|
disk: classify(diskPercent, th.diskWarn, th.diskCritical),
|
||||||
|
load: classify(load1, th.loadWarn, th.loadCritical),
|
||||||
|
},
|
||||||
|
thresholds: {
|
||||||
|
cpuWarn: th.cpuWarn,
|
||||||
|
cpuCritical: th.cpuCritical,
|
||||||
|
memWarn: th.memWarn,
|
||||||
|
memCritical: th.memCritical,
|
||||||
|
diskWarn: th.diskWarn,
|
||||||
|
diskCritical: th.diskCritical,
|
||||||
|
loadWarn: th.loadWarn,
|
||||||
|
loadCritical: th.loadCritical,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return empty(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTimeseries(
|
||||||
|
metric: TimeseriesMetric,
|
||||||
|
range: TimeseriesRange
|
||||||
|
): Promise<{ metric: TimeseriesMetric; range: TimeseriesRange; points: Array<{ t: number; v: number }> }> {
|
||||||
|
const query = METRIC_QUERIES[metric];
|
||||||
|
if (!query) throw new Error('Unknown metric');
|
||||||
|
try {
|
||||||
|
const points = await queryRange(query, range);
|
||||||
|
return { metric, range, points };
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(e instanceof Error ? e.message : 'Prometheus query failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ContainerStat = {
|
||||||
|
name: string;
|
||||||
|
cpuPercent: number | null;
|
||||||
|
memBytes: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getContainers(limit = 20): Promise<{ containers: ContainerStat[] }> {
|
||||||
|
const safeLimit = Math.min(50, Math.max(1, Math.floor(limit)));
|
||||||
|
try {
|
||||||
|
const [cpuBody, memBody] = await Promise.all([
|
||||||
|
promGet('/api/v1/query', {
|
||||||
|
query: `topk(${safeLimit}, sum by (name) (rate(container_cpu_usage_seconds_total{name!=""}[5m])) * 100)`,
|
||||||
|
}),
|
||||||
|
promGet('/api/v1/query', {
|
||||||
|
query: `topk(${safeLimit}, sum by (name) (container_memory_working_set_bytes{name!=""}))`,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const cpuMap = new Map<string, number>();
|
||||||
|
for (const row of cpuBody.data?.result ?? []) {
|
||||||
|
const name = (row.metric?.name || '').trim();
|
||||||
|
if (!name || name === '/') continue;
|
||||||
|
const v = Number(row.value?.[1]);
|
||||||
|
if (Number.isFinite(v)) cpuMap.set(name, v);
|
||||||
|
}
|
||||||
|
const memMap = new Map<string, number>();
|
||||||
|
for (const row of memBody.data?.result ?? []) {
|
||||||
|
const name = (row.metric?.name || '').trim();
|
||||||
|
if (!name || name === '/') continue;
|
||||||
|
const v = Number(row.value?.[1]);
|
||||||
|
if (Number.isFinite(v)) memMap.set(name, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
const names = new Set([...cpuMap.keys(), ...memMap.keys()]);
|
||||||
|
const containers = [...names]
|
||||||
|
.map((name) => ({
|
||||||
|
name,
|
||||||
|
cpuPercent: cpuMap.get(name) ?? null,
|
||||||
|
memBytes: memMap.get(name) ?? null,
|
||||||
|
}))
|
||||||
|
.sort((a, b) => (b.cpuPercent ?? 0) - (a.cpuPercent ?? 0))
|
||||||
|
.slice(0, safeLimit);
|
||||||
|
|
||||||
|
return { containers };
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(e instanceof Error ? e.message : 'Container metrics unavailable');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ScrapeTarget = {
|
||||||
|
job: string;
|
||||||
|
health: string;
|
||||||
|
lastError: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getServices(): Promise<{
|
||||||
|
prometheusReachable: boolean;
|
||||||
|
targets: ScrapeTarget[];
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const url = new URL('/api/v1/targets', `${baseUrl()}/`);
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), config.vpsMonitor.timeoutMs);
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, { signal: ctrl.signal, headers: { Accept: 'application/json' } });
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
if (!res.ok) throw new Error(`Prometheus HTTP ${res.status}`);
|
||||||
|
const body = (await res.json()) as {
|
||||||
|
status: string;
|
||||||
|
data?: { activeTargets?: Array<{ labels?: { job?: string }; health?: string; lastError?: string }> };
|
||||||
|
};
|
||||||
|
const targets = (body.data?.activeTargets ?? []).map((t) => ({
|
||||||
|
job: t.labels?.job || 'unknown',
|
||||||
|
health: t.health || 'unknown',
|
||||||
|
lastError: t.lastError ? String(t.lastError).slice(0, 200) : null,
|
||||||
|
}));
|
||||||
|
return { prometheusReachable: true, targets };
|
||||||
|
} catch {
|
||||||
|
return { prometheusReachable: false, targets: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseMetric(raw: unknown): TimeseriesMetric | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
return raw in METRIC_QUERIES ? (raw as TimeseriesMetric) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseRange(raw: unknown): TimeseriesRange | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
return raw in RANGE_SECONDS ? (raw as TimeseriesRange) : null;
|
||||||
|
}
|
||||||
19
deploy/monitoring/prometheus.yml
Normal file
19
deploy/monitoring/prometheus.yml
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
# Prometheus scrape config — internal Docker network only (no published ports).
|
||||||
|
# Scraped by crypto_wallet_api via allowlisted PromQL (admin VPS monitor page).
|
||||||
|
|
||||||
|
global:
|
||||||
|
scrape_interval: 15s
|
||||||
|
evaluation_interval: 15s
|
||||||
|
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: prometheus
|
||||||
|
static_configs:
|
||||||
|
- targets: ['localhost:9090']
|
||||||
|
|
||||||
|
- job_name: node
|
||||||
|
static_configs:
|
||||||
|
- targets: ['node-exporter:9100']
|
||||||
|
|
||||||
|
- job_name: cadvisor
|
||||||
|
static_configs:
|
||||||
|
- targets: ['cadvisor:8080']
|
||||||
@ -102,6 +102,9 @@ x-backend-common: &backend-common
|
|||||||
SSL_STATUS_WARN_DAYS: ${SSL_STATUS_WARN_DAYS:-30}
|
SSL_STATUS_WARN_DAYS: ${SSL_STATUS_WARN_DAYS:-30}
|
||||||
SSL_STATUS_CRITICAL_DAYS: ${SSL_STATUS_CRITICAL_DAYS:-7}
|
SSL_STATUS_CRITICAL_DAYS: ${SSL_STATUS_CRITICAL_DAYS:-7}
|
||||||
SSL_STATUS_TIMEOUT_MS: ${SSL_STATUS_TIMEOUT_MS:-8000}
|
SSL_STATUS_TIMEOUT_MS: ${SSL_STATUS_TIMEOUT_MS:-8000}
|
||||||
|
# Admin VPS monitor (Prometheus on monitoring-net + prediqo-net; no public ports)
|
||||||
|
PROMETHEUS_URL: ${PROMETHEUS_URL:-http://prometheus:9090}
|
||||||
|
VPS_MONITOR_TIMEOUT_MS: ${VPS_MONITOR_TIMEOUT_MS:-8000}
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
@ -499,9 +502,83 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- prediqo-net
|
- prediqo-net
|
||||||
|
|
||||||
|
# ── VPS monitoring (profile: monitoring) ──────────────────────────────────
|
||||||
|
# No published ports. Backend reads allowlisted metrics via PROMETHEUS_URL.
|
||||||
|
# Exception (documented): cAdvisor mounts docker.sock read-only; backend never does.
|
||||||
|
prometheus:
|
||||||
|
profiles: ['monitoring']
|
||||||
|
image: prom/prometheus:v2.55.1
|
||||||
|
container_name: prediqo_prometheus
|
||||||
|
restart: unless-stopped
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yml
|
||||||
|
- --storage.tsdb.path=/prometheus
|
||||||
|
- --storage.tsdb.retention.time=${MONITORING_RETENTION:-15d}
|
||||||
|
- --web.enable-lifecycle=false
|
||||||
|
- --web.enable-admin-api=false
|
||||||
|
- --web.listen-address=0.0.0.0:9090
|
||||||
|
volumes:
|
||||||
|
- ./deploy/monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
networks:
|
||||||
|
- monitoring-net
|
||||||
|
- prediqo-net
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 0.50
|
||||||
|
# Intentionally no ports: — not reachable from the public internet
|
||||||
|
|
||||||
|
node-exporter:
|
||||||
|
profiles: ['monitoring']
|
||||||
|
image: prom/node-exporter:v1.8.2
|
||||||
|
container_name: prediqo_node_exporter
|
||||||
|
restart: unless-stopped
|
||||||
|
command:
|
||||||
|
- --path.rootfs=/host
|
||||||
|
- --path.procfs=/host/proc
|
||||||
|
- --path.sysfs=/host/sys
|
||||||
|
- --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)
|
||||||
|
volumes:
|
||||||
|
- /proc:/host/proc:ro
|
||||||
|
- /sys:/host/sys:ro
|
||||||
|
- /:/host:ro,rslave
|
||||||
|
networks:
|
||||||
|
- monitoring-net
|
||||||
|
pid: host
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.20
|
||||||
|
# Intentionally no ports:
|
||||||
|
|
||||||
|
cadvisor:
|
||||||
|
profiles: ['monitoring']
|
||||||
|
image: gcr.io/cadvisor/cadvisor:v0.49.1
|
||||||
|
container_name: prediqo_cadvisor
|
||||||
|
restart: unless-stopped
|
||||||
|
command:
|
||||||
|
- --docker_only=true
|
||||||
|
- --housekeeping_interval=30s
|
||||||
|
- --store_container_labels=false
|
||||||
|
- --disable_metrics=advtcp,udp,sched,process,hugetlb,referenced_memory,resctrl,cpu_topology,tcp,memory_numa
|
||||||
|
volumes:
|
||||||
|
- /:/rootfs:ro
|
||||||
|
- /var/run:/var/run:ro
|
||||||
|
- /sys:/sys:ro
|
||||||
|
- /var/lib/docker/:/var/lib/docker:ro
|
||||||
|
- /dev/disk/:/dev/disk:ro
|
||||||
|
# Least privilege for container metrics — RO sock; never mount this on backend/web
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
|
networks:
|
||||||
|
- monitoring-net
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.30
|
||||||
|
# Intentionally no ports:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
prediqo-net:
|
prediqo-net:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
|
monitoring-net:
|
||||||
|
# No host/gateway egress — exporters stay unreachable from the public internet
|
||||||
|
driver: bridge
|
||||||
|
internal: true
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
@ -510,3 +587,4 @@ volumes:
|
|||||||
apk_releases:
|
apk_releases:
|
||||||
letsencrypt:
|
letsencrypt:
|
||||||
certbot-www:
|
certbot-www:
|
||||||
|
prometheus_data:
|
||||||
|
|||||||
@ -953,6 +953,7 @@ Local Docker : `npm run docker:local:break-glass-reset-2fa -- …` (fichier `.en
|
|||||||
| Logs en direct | `npm run phase-b:logs` |
|
| Logs en direct | `npm run phase-b:logs` |
|
||||||
| Redémarrer | `npm run phase-b:restart` |
|
| Redémarrer | `npm run phase-b:restart` |
|
||||||
| Recharger la passerelle 80/443 | `npm run gateway:reload` (si login/API en 502 après rebuild) |
|
| Recharger la passerelle 80/443 | `npm run gateway:reload` (si login/API en 502 après rebuild) |
|
||||||
|
| Démarrer la surveillance VPS | `npm run monitoring:up` (profile `monitoring`, pas de ports publics) |
|
||||||
| Arrêter | `npm run phase-b:down` |
|
| Arrêter | `npm run phase-b:down` |
|
||||||
| Remise à zéro DB | [§4.1](#41-remise-à-zéro--supprimer-et-recréer-la-base-avant-tests-réels) |
|
| Remise à zéro DB | [§4.1](#41-remise-à-zéro--supprimer-et-recréer-la-base-avant-tests-réels) |
|
||||||
| Seed hot wallets (TRON + BSC) | `docker compose run --rm --no-deps backend node dist/scripts/seedHotWallets.js` |
|
| Seed hot wallets (TRON + BSC) | `docker compose run --rm --no-deps backend node dist/scripts/seedHotWallets.js` |
|
||||||
@ -978,6 +979,17 @@ npm run phase-b:up:https
|
|||||||
# Vérifier : curl -sS https://tloto.net/health → doit renvoyer {"status":"ok",...}
|
# Vérifier : curl -sS https://tloto.net/health → doit renvoyer {"status":"ok",...}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Surveillance VPS (back-office)
|
||||||
|
|
||||||
|
Voir [VPS-MONITORING.md](./VPS-MONITORING.md). En bref :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo npm run monitoring:up
|
||||||
|
sudo npm run phase-b:up:https
|
||||||
|
```
|
||||||
|
|
||||||
|
Puis **Options → Surveillance VPS** (permission `admin.vps_monitor.view`).
|
||||||
|
|
||||||
### 502 Bad Gateway après rebuild (passerelle VPS)
|
### 502 Bad Gateway après rebuild (passerelle VPS)
|
||||||
|
|
||||||
Cause fréquente : `vps_gateway_nginx` a résolu `crypto_wallet_api` vers une **ancienne IP Docker**. Le front (`prediqo-web`) peut encore répondre, mais `/api` et `/health` renvoient 502.
|
Cause fréquente : `vps_gateway_nginx` a résolu `crypto_wallet_api` vers une **ancienne IP Docker**. Le front (`prediqo-web`) peut encore répondre, mais `/api` et `/health` renvoient 502.
|
||||||
|
|||||||
72
docs/VPS-MONITORING.md
Normal file
72
docs/VPS-MONITORING.md
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
# Surveillance VPS (back-office Tloto)
|
||||||
|
|
||||||
|
Lecture seule des ressources hôte + conteneurs Docker, affichée dans **Options → Surveillance VPS**.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
Navigateur (HTTPS) → vps-gateway → backend Tloto
|
||||||
|
↓ PROMETHEUS_URL (réseau Docker)
|
||||||
|
prometheus (pas de port public)
|
||||||
|
↓ monitoring-net (internal)
|
||||||
|
node-exporter cadvisor
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Aucun port publié** pour Prometheus, Node Exporter, cAdvisor.
|
||||||
|
- Le backend n’exécute **aucune** commande shell/Docker et **ne monte pas** `/var/run/docker.sock`.
|
||||||
|
- Exception documentée : **cAdvisor** monte `docker.sock` en **lecture seule** uniquement pour les métriques conteneurs.
|
||||||
|
- L’API n’accepte **pas** de PromQL libre : métriques allowlistées (`cpu`, `mem`, `disk`, `net_in`, `net_out`, `load1`).
|
||||||
|
|
||||||
|
## Permission
|
||||||
|
|
||||||
|
- Clé : `admin.vps_monitor.view`
|
||||||
|
- Accordée par défaut au rôle `admin` (sync catalogue) et à `super_admin` (toutes permissions).
|
||||||
|
- Vérifiée côté backend (`requirePermissions`) + UI (`PermissionGate` / Options).
|
||||||
|
- Accès refusés : `logAccessDenied` ; consultations : `audit_logs` (`vps_monitor_*`).
|
||||||
|
|
||||||
|
## Démarrage (VPS)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projects_repository/games-project
|
||||||
|
git pull
|
||||||
|
sudo npm run monitoring:up # profile monitoring
|
||||||
|
sudo npm run phase-b:up:https # rebuild backend + web
|
||||||
|
curl -sS https://tloto.net/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Vérifier qu’aucun port monitoring n’est public :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo docker compose --profile monitoring ps
|
||||||
|
sudo ss -tlnp | grep -E '9090|9100|8080' || echo "OK: ports monitoring non exposés"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Variables d’environnement
|
||||||
|
|
||||||
|
| Variable | Défaut | Rôle |
|
||||||
|
|----------|--------|------|
|
||||||
|
| `PROMETHEUS_URL` | `http://prometheus:9090` | URL interne vue du backend |
|
||||||
|
| `MONITORING_RETENTION` | `15d` | Rétention TSDB Prometheus |
|
||||||
|
| `VPS_MONITOR_TIMEOUT_MS` | `8000` | Timeout appels Prometheus |
|
||||||
|
| `VPS_MONITOR_*_WARN/CRITICAL` | voir `.env.example` | Seuils d’affichage (lecture seule) |
|
||||||
|
|
||||||
|
## Rate limiting
|
||||||
|
|
||||||
|
Les routes `/api/v1/admin/vps-monitor/*` utilisent `vpsMonitorLimiter` (30 req/min) en plus du limiteur API global.
|
||||||
|
|
||||||
|
## Migration vers un autre VPS
|
||||||
|
|
||||||
|
1. Copier le dépôt + `.env` (sans secrets dans Git).
|
||||||
|
2. `docker compose --profile monitoring up -d` puis stack Tloto habituelle.
|
||||||
|
3. Volume `prometheus_data` = historique (optionnel à migrer).
|
||||||
|
4. Ne jamais publier 9090/9100/8080 sur l’hôte.
|
||||||
|
|
||||||
|
## Mise à jour des images
|
||||||
|
|
||||||
|
Versions épinglées dans `docker-compose.yml` (`prom/prometheus:v2.55.1`, `prom/node-exporter:v1.8.2`, `gcr.io/cadvisor/cadvisor:v0.49.1`). Après bump : `sudo npm run monitoring:up` puis tests santé scrape dans la page admin.
|
||||||
|
|
||||||
|
## Hors scope (v1)
|
||||||
|
|
||||||
|
- Grafana public
|
||||||
|
- Restart / exec / SSH depuis le back-office
|
||||||
|
- Édition des seuils depuis l’UI
|
||||||
@ -19,6 +19,9 @@
|
|||||||
"phase-b:restart": "docker compose --profile https-dns restart nginx-https-dns backend backend-engine backend-ws backend-worker-bets prediqo-web",
|
"phase-b:restart": "docker compose --profile https-dns restart nginx-https-dns backend backend-engine backend-ws backend-worker-bets prediqo-web",
|
||||||
"phase-b:status": "docker compose ps",
|
"phase-b:status": "docker compose ps",
|
||||||
"gateway:reload": "docker restart vps_gateway_nginx",
|
"gateway:reload": "docker restart vps_gateway_nginx",
|
||||||
|
"monitoring:up": "docker compose --profile monitoring up -d",
|
||||||
|
"monitoring:down": "docker compose --profile monitoring stop prometheus node-exporter cadvisor",
|
||||||
|
"monitoring:logs": "docker compose logs -f prometheus node-exporter cadvisor",
|
||||||
"ssl:init": "docker compose --profile ssl-init run --rm certbot-init",
|
"ssl:init": "docker compose --profile ssl-init run --rm certbot-init",
|
||||||
"ssl:dns-init": "docker compose --profile dns-init run --rm -it certbot-dns-init",
|
"ssl:dns-init": "docker compose --profile dns-init run --rm -it certbot-dns-init",
|
||||||
"ssl:dns-renew": "docker compose --profile dns-renew run --rm -it certbot-dns-renew",
|
"ssl:dns-renew": "docker compose --profile dns-renew run --rm -it certbot-dns-renew",
|
||||||
|
|||||||
@ -233,6 +233,11 @@ export const SslCertificatesAdminPage = lazyNamed(
|
|||||||
() => import('../../features/ssl-certificates/SslCertificatesAdminPage'),
|
() => import('../../features/ssl-certificates/SslCertificatesAdminPage'),
|
||||||
'SslCertificatesAdminPage'
|
'SslCertificatesAdminPage'
|
||||||
);
|
);
|
||||||
|
export const VpsMonitorAdminPage = lazyNamed(
|
||||||
|
'VpsMonitorAdminPage',
|
||||||
|
() => import('../../features/vps-monitor/VpsMonitorAdminPage'),
|
||||||
|
'VpsMonitorAdminPage'
|
||||||
|
);
|
||||||
|
|
||||||
/** Exact path → page preload. Longest match wins for nested paths. */
|
/** Exact path → page preload. Longest match wins for nested paths. */
|
||||||
const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
||||||
@ -274,6 +279,7 @@ const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
|||||||
{ path: '/admin/admin-users', preload: AdminUsersPage.preload },
|
{ path: '/admin/admin-users', preload: AdminUsersPage.preload },
|
||||||
{ path: '/admin/mobile-versions', preload: MobileVersionsAdminPage.preload },
|
{ path: '/admin/mobile-versions', preload: MobileVersionsAdminPage.preload },
|
||||||
{ path: '/admin/ssl-certificates', preload: SslCertificatesAdminPage.preload },
|
{ path: '/admin/ssl-certificates', preload: SslCertificatesAdminPage.preload },
|
||||||
|
{ path: '/admin/vps-monitor', preload: VpsMonitorAdminPage.preload },
|
||||||
].sort((a, b) => b.path.length - a.path.length);
|
].sort((a, b) => b.path.length - a.path.length);
|
||||||
|
|
||||||
/** Warm the JS chunk for a destination before navigation. */
|
/** Warm the JS chunk for a destination before navigation. */
|
||||||
|
|||||||
@ -50,6 +50,7 @@ import {
|
|||||||
AdminUserPermissionsPage,
|
AdminUserPermissionsPage,
|
||||||
MobileVersionsAdminPage,
|
MobileVersionsAdminPage,
|
||||||
SslCertificatesAdminPage,
|
SslCertificatesAdminPage,
|
||||||
|
VpsMonitorAdminPage,
|
||||||
} from './routePrefetch';
|
} from './routePrefetch';
|
||||||
|
|
||||||
function RouteFallback() {
|
function RouteFallback() {
|
||||||
@ -353,6 +354,14 @@ export const router = createBrowserRouter([
|
|||||||
</L>
|
</L>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'admin/vps-monitor',
|
||||||
|
element: (
|
||||||
|
<L>
|
||||||
|
<VpsMonitorAdminPage />
|
||||||
|
</L>
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'admin/solo-encouragement',
|
path: 'admin/solo-encouragement',
|
||||||
element: (
|
element: (
|
||||||
|
|||||||
@ -24,6 +24,7 @@ import ManageAccountsRoundedIcon from '@mui/icons-material/ManageAccountsRounded
|
|||||||
import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded';
|
import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded';
|
||||||
import PhoneAndroidRoundedIcon from '@mui/icons-material/PhoneAndroidRounded';
|
import PhoneAndroidRoundedIcon from '@mui/icons-material/PhoneAndroidRounded';
|
||||||
import VerifiedUserRoundedIcon from '@mui/icons-material/VerifiedUserRounded';
|
import VerifiedUserRoundedIcon from '@mui/icons-material/VerifiedUserRounded';
|
||||||
|
import MonitorHeartRoundedIcon from '@mui/icons-material/MonitorHeartRounded';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useAuth } from '../../shared/auth/AuthContext';
|
import { useAuth } from '../../shared/auth/AuthContext';
|
||||||
@ -51,7 +52,8 @@ type OptionCardKey =
|
|||||||
| 'rbac'
|
| 'rbac'
|
||||||
| 'adminUsers'
|
| 'adminUsers'
|
||||||
| 'mobileVersions'
|
| 'mobileVersions'
|
||||||
| 'sslCertificates';
|
| 'sslCertificates'
|
||||||
|
| 'vpsMonitor';
|
||||||
|
|
||||||
type OptionCardConfig = {
|
type OptionCardConfig = {
|
||||||
key: OptionCardKey;
|
key: OptionCardKey;
|
||||||
@ -254,6 +256,15 @@ const OPTION_CARDS: OptionCardConfig[] = [
|
|||||||
bg: 'rgba(59,130,246,0.14)',
|
bg: 'rgba(59,130,246,0.14)',
|
||||||
border: 'rgba(59,130,246,0.28)',
|
border: 'rgba(59,130,246,0.28)',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'vpsMonitor',
|
||||||
|
path: '/admin/vps-monitor',
|
||||||
|
icon: MonitorHeartRoundedIcon,
|
||||||
|
badgeKey: 'vps',
|
||||||
|
badgeColor: 'warning',
|
||||||
|
bg: 'rgba(245,158,11,0.14)',
|
||||||
|
border: 'rgba(245,158,11,0.28)',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Landing page for administrative tools and configuration shortcuts. */
|
/** Landing page for administrative tools and configuration shortcuts. */
|
||||||
|
|||||||
401
prediqo_web/src/features/vps-monitor/VpsMonitorAdminPage.tsx
Normal file
401
prediqo_web/src/features/vps-monitor/VpsMonitorAdminPage.tsx
Normal file
@ -0,0 +1,401 @@
|
|||||||
|
/**
|
||||||
|
* Admin page: read-only VPS / Docker resource metrics (via backend → Prometheus).
|
||||||
|
*/
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
Chip,
|
||||||
|
LinearProgress,
|
||||||
|
MenuItem,
|
||||||
|
Stack,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
TextField,
|
||||||
|
Typography,
|
||||||
|
} from '@mui/material';
|
||||||
|
import MonitorHeartRoundedIcon from '@mui/icons-material/MonitorHeartRounded';
|
||||||
|
import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
CartesianGrid,
|
||||||
|
Legend,
|
||||||
|
Line,
|
||||||
|
LineChart,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from 'recharts';
|
||||||
|
import { PermissionGate } from '../../shared/auth/PermissionGate';
|
||||||
|
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||||
|
import { apiErrorMessage } from '../../shared/utils/apiError';
|
||||||
|
import {
|
||||||
|
fetchVpsContainers,
|
||||||
|
fetchVpsOverview,
|
||||||
|
fetchVpsServices,
|
||||||
|
fetchVpsTimeseries,
|
||||||
|
type MetricStatus,
|
||||||
|
type TimeseriesMetric,
|
||||||
|
type TimeseriesRange,
|
||||||
|
} from './api/vpsMonitorApi';
|
||||||
|
|
||||||
|
function statusColor(s: MetricStatus): 'success' | 'warning' | 'error' | 'default' {
|
||||||
|
if (s === 'ok') return 'success';
|
||||||
|
if (s === 'warning') return 'warning';
|
||||||
|
if (s === 'critical') return 'error';
|
||||||
|
return 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtPct(n: number | null): string {
|
||||||
|
if (n == null || !Number.isFinite(n)) return '—';
|
||||||
|
return `${n.toFixed(1)}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtBytes(n: number | null): string {
|
||||||
|
if (n == null || !Number.isFinite(n)) return '—';
|
||||||
|
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
let v = n;
|
||||||
|
let i = 0;
|
||||||
|
while (v >= 1024 && i < units.length - 1) {
|
||||||
|
v /= 1024;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtBps(n: number | null): string {
|
||||||
|
if (n == null || !Number.isFinite(n)) return '—';
|
||||||
|
return `${fmtBytes(n)}/s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function MetricCard({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
hint,
|
||||||
|
status,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
hint?: string;
|
||||||
|
status: MetricStatus;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 2,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'divider',
|
||||||
|
bgcolor: 'background.paper',
|
||||||
|
minWidth: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Stack direction="row" justifyContent="space-between" alignItems="center" gap={1}>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
{label}
|
||||||
|
</Typography>
|
||||||
|
<Chip size="small" color={statusColor(status)} label={status} />
|
||||||
|
</Stack>
|
||||||
|
<Typography variant="h5" fontWeight={800} sx={{ mt: 0.75 }}>
|
||||||
|
{value}
|
||||||
|
</Typography>
|
||||||
|
{hint && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{hint}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{status !== 'unknown' && value.endsWith('%') && (
|
||||||
|
<LinearProgress
|
||||||
|
variant="determinate"
|
||||||
|
value={Math.min(100, Math.max(0, Number(value.replace('%', '')) || 0))}
|
||||||
|
color={statusColor(status) === 'default' ? 'primary' : statusColor(status)}
|
||||||
|
sx={{ mt: 1.25, height: 6, borderRadius: 1 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function VpsMonitorAdminPage() {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const [metric, setMetric] = useState<TimeseriesMetric>('cpu');
|
||||||
|
const [range, setRange] = useState<TimeseriesRange>('1h');
|
||||||
|
|
||||||
|
const overviewQ = useQuery({
|
||||||
|
queryKey: ['admin', 'vps-monitor', 'overview'],
|
||||||
|
queryFn: fetchVpsOverview,
|
||||||
|
refetchInterval: 20_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
const seriesQ = useQuery({
|
||||||
|
queryKey: ['admin', 'vps-monitor', 'timeseries', metric, range],
|
||||||
|
queryFn: () => fetchVpsTimeseries(metric, range),
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
const containersQ = useQuery({
|
||||||
|
queryKey: ['admin', 'vps-monitor', 'containers'],
|
||||||
|
queryFn: fetchVpsContainers,
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
const servicesQ = useQuery({
|
||||||
|
queryKey: ['admin', 'vps-monitor', 'services'],
|
||||||
|
queryFn: fetchVpsServices,
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const chartData = useMemo(() => {
|
||||||
|
const pts = seriesQ.data?.points ?? [];
|
||||||
|
return pts.map((p) => ({
|
||||||
|
time: new Date(p.t).toLocaleTimeString(i18n.language, {
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
}),
|
||||||
|
value: Number(p.v.toFixed(3)),
|
||||||
|
}));
|
||||||
|
}, [seriesQ.data, i18n.language]);
|
||||||
|
|
||||||
|
const o = overviewQ.data;
|
||||||
|
const refreshAll = () => {
|
||||||
|
void overviewQ.refetch();
|
||||||
|
void seriesQ.refetch();
|
||||||
|
void containersQ.refetch();
|
||||||
|
void servicesQ.refetch();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PermissionGate permission="admin.vps_monitor.view">
|
||||||
|
<Box sx={{ maxWidth: 1200, mx: 'auto', px: { xs: 1.5, md: 2 }, py: 2 }}>
|
||||||
|
<Stack direction="row" alignItems="flex-start" justifyContent="space-between" gap={2} flexWrap="wrap">
|
||||||
|
<Stack direction="row" spacing={1.5} alignItems="center">
|
||||||
|
<MonitorHeartRoundedIcon color="primary" />
|
||||||
|
<Box>
|
||||||
|
<Typography variant="h5" fontWeight={800}>
|
||||||
|
{t('admin.vpsMonitor.title')}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
{t('admin.vpsMonitor.subtitle')}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
<Button startIcon={<RefreshRoundedIcon />} variant="outlined" onClick={refreshAll}>
|
||||||
|
{t('admin.vpsMonitor.refresh')}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{overviewQ.isError && (
|
||||||
|
<Alert severity="error" sx={{ mt: 2 }}>
|
||||||
|
{apiErrorMessage(overviewQ.error, t('admin.vpsMonitor.loadError'))}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{o && !o.prometheusReachable && (
|
||||||
|
<Alert severity="warning" sx={{ mt: 2 }}>
|
||||||
|
{t('admin.vpsMonitor.prometheusDown')}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{o && (
|
||||||
|
<Typography variant="caption" color="text.secondary" display="block" sx={{ mt: 1.5 }}>
|
||||||
|
{t('admin.vpsMonitor.checkedAt', {
|
||||||
|
at: new Date(o.checkedAt).toLocaleString(i18n.language),
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
mt: 2,
|
||||||
|
display: 'grid',
|
||||||
|
gap: 1.5,
|
||||||
|
gridTemplateColumns: { xs: '1fr', sm: '1fr 1fr', md: 'repeat(4, 1fr)' },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.cpu')}
|
||||||
|
value={fmtPct(o?.cpuPercent ?? null)}
|
||||||
|
status={o?.status.cpu ?? 'unknown'}
|
||||||
|
/>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.memory')}
|
||||||
|
value={fmtPct(o?.memPercent ?? null)}
|
||||||
|
hint={`${fmtBytes(o?.memUsedBytes ?? null)} / ${fmtBytes(o?.memTotalBytes ?? null)}`}
|
||||||
|
status={o?.status.mem ?? 'unknown'}
|
||||||
|
/>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.disk')}
|
||||||
|
value={fmtPct(o?.diskPercent ?? null)}
|
||||||
|
hint={`${fmtBytes(o?.diskUsedBytes ?? null)} / ${fmtBytes(o?.diskTotalBytes ?? null)}`}
|
||||||
|
status={o?.status.disk ?? 'unknown'}
|
||||||
|
/>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.load')}
|
||||||
|
value={
|
||||||
|
o?.load1 == null
|
||||||
|
? '—'
|
||||||
|
: `${o.load1.toFixed(2)} / ${(o.load5 ?? 0).toFixed(2)} / ${(o.load15 ?? 0).toFixed(2)}`
|
||||||
|
}
|
||||||
|
hint={t('admin.vpsMonitor.loadHint')}
|
||||||
|
status={o?.status.load ?? 'unknown'}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
mt: 1.5,
|
||||||
|
display: 'grid',
|
||||||
|
gap: 1.5,
|
||||||
|
gridTemplateColumns: { xs: '1fr', sm: '1fr 1fr' },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.netIn')}
|
||||||
|
value={fmtBps(o?.netReceiveBps ?? null)}
|
||||||
|
status="ok"
|
||||||
|
/>
|
||||||
|
<MetricCard
|
||||||
|
label={t('admin.vpsMonitor.netOut')}
|
||||||
|
value={fmtBps(o?.netTransmitBps ?? null)}
|
||||||
|
status="ok"
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ mt: 3, p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
|
||||||
|
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ mb: 1.5 }}>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
label={t('admin.vpsMonitor.metric')}
|
||||||
|
value={metric}
|
||||||
|
onChange={(e) => setMetric(e.target.value as TimeseriesMetric)}
|
||||||
|
sx={{ minWidth: 160 }}
|
||||||
|
>
|
||||||
|
{(['cpu', 'mem', 'disk', 'net_in', 'net_out', 'load1'] as TimeseriesMetric[]).map((m) => (
|
||||||
|
<MenuItem key={m} value={m}>
|
||||||
|
{t(`admin.vpsMonitor.metrics.${m}`)}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
<TextField
|
||||||
|
select
|
||||||
|
size="small"
|
||||||
|
label={t('admin.vpsMonitor.range')}
|
||||||
|
value={range}
|
||||||
|
onChange={(e) => setRange(e.target.value as TimeseriesRange)}
|
||||||
|
sx={{ minWidth: 140 }}
|
||||||
|
>
|
||||||
|
{(['1h', '6h', '24h', '7d'] as TimeseriesRange[]).map((r) => (
|
||||||
|
<MenuItem key={r} value={r}>
|
||||||
|
{t(`admin.vpsMonitor.ranges.${r}`)}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</TextField>
|
||||||
|
</Stack>
|
||||||
|
<Box sx={{ width: '100%', height: 280 }}>
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<LineChart data={chartData} margin={{ top: 8, right: 12, left: 0, bottom: 0 }}>
|
||||||
|
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.08)" />
|
||||||
|
<XAxis dataKey="time" tick={{ fontSize: 11 }} />
|
||||||
|
<YAxis tick={{ fontSize: 11 }} width={56} />
|
||||||
|
<Tooltip
|
||||||
|
contentStyle={{ background: '#1a1a24', border: '1px solid rgba(255,255,255,0.1)' }}
|
||||||
|
/>
|
||||||
|
<Legend />
|
||||||
|
<Line
|
||||||
|
type="monotone"
|
||||||
|
dataKey="value"
|
||||||
|
name={t(`admin.vpsMonitor.metrics.${metric}`)}
|
||||||
|
stroke="#4ade80"
|
||||||
|
dot={false}
|
||||||
|
strokeWidth={2}
|
||||||
|
/>
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Typography variant="h6" fontWeight={800} sx={{ mt: 3, mb: 1 }}>
|
||||||
|
{t('admin.vpsMonitor.servicesTitle')}
|
||||||
|
</Typography>
|
||||||
|
<ScrollableTable>
|
||||||
|
<Table size="small">
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.job')}</TableCell>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.health')}</TableCell>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.lastError')}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{(servicesQ.data?.targets ?? []).map((row) => (
|
||||||
|
<TableRow key={`${row.job}-${row.health}-${row.lastError ?? ''}`}>
|
||||||
|
<TableCell>{row.job}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Chip
|
||||||
|
size="small"
|
||||||
|
color={row.health === 'up' ? 'success' : 'error'}
|
||||||
|
label={row.health}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Typography variant="caption" color="error">
|
||||||
|
{row.lastError || '—'}
|
||||||
|
</Typography>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
{!servicesQ.isLoading && !(servicesQ.data?.targets?.length) && (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={3}>{t('admin.vpsMonitor.noTargets')}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</ScrollableTable>
|
||||||
|
|
||||||
|
<Typography variant="h6" fontWeight={800} sx={{ mt: 3, mb: 1 }}>
|
||||||
|
{t('admin.vpsMonitor.containersTitle')}
|
||||||
|
</Typography>
|
||||||
|
<ScrollableTable>
|
||||||
|
<Table size="small">
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.container')}</TableCell>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.cpu')}</TableCell>
|
||||||
|
<TableCell>{t('admin.vpsMonitor.memory')}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{(containersQ.data?.containers ?? []).map((c) => (
|
||||||
|
<TableRow key={c.name}>
|
||||||
|
<TableCell>
|
||||||
|
<Typography fontWeight={700}>{c.name}</Typography>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{fmtPct(c.cpuPercent)}</TableCell>
|
||||||
|
<TableCell>{fmtBytes(c.memBytes)}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
{!containersQ.isLoading && !(containersQ.data?.containers?.length) && (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={3}>{t('admin.vpsMonitor.noContainers')}</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</ScrollableTable>
|
||||||
|
|
||||||
|
<Alert severity="info" sx={{ mt: 3 }}>
|
||||||
|
{t('admin.vpsMonitor.readOnlyNote')}
|
||||||
|
</Alert>
|
||||||
|
</Box>
|
||||||
|
</PermissionGate>
|
||||||
|
);
|
||||||
|
}
|
||||||
90
prediqo_web/src/features/vps-monitor/api/vpsMonitorApi.ts
Normal file
90
prediqo_web/src/features/vps-monitor/api/vpsMonitorApi.ts
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
/**
|
||||||
|
* Admin VPS monitor API (read-only Prometheus-backed metrics).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { api } from '../../../shared/services/api';
|
||||||
|
|
||||||
|
export type MetricStatus = 'ok' | 'warning' | 'critical' | 'unknown';
|
||||||
|
export type TimeseriesMetric = 'cpu' | 'mem' | 'disk' | 'net_in' | 'net_out' | 'load1';
|
||||||
|
export type TimeseriesRange = '1h' | '6h' | '24h' | '7d';
|
||||||
|
|
||||||
|
export type VpsOverview = {
|
||||||
|
checkedAt: string;
|
||||||
|
prometheusReachable: boolean;
|
||||||
|
cpuPercent: number | null;
|
||||||
|
memPercent: number | null;
|
||||||
|
memUsedBytes: number | null;
|
||||||
|
memTotalBytes: number | null;
|
||||||
|
diskPercent: number | null;
|
||||||
|
diskUsedBytes: number | null;
|
||||||
|
diskTotalBytes: number | null;
|
||||||
|
load1: number | null;
|
||||||
|
load5: number | null;
|
||||||
|
load15: number | null;
|
||||||
|
netReceiveBps: number | null;
|
||||||
|
netTransmitBps: number | null;
|
||||||
|
status: {
|
||||||
|
cpu: MetricStatus;
|
||||||
|
mem: MetricStatus;
|
||||||
|
disk: MetricStatus;
|
||||||
|
load: MetricStatus;
|
||||||
|
};
|
||||||
|
thresholds: {
|
||||||
|
cpuWarn: number;
|
||||||
|
cpuCritical: number;
|
||||||
|
memWarn: number;
|
||||||
|
memCritical: number;
|
||||||
|
diskWarn: number;
|
||||||
|
diskCritical: number;
|
||||||
|
loadWarn: number;
|
||||||
|
loadCritical: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TimeseriesResult = {
|
||||||
|
metric: TimeseriesMetric;
|
||||||
|
range: TimeseriesRange;
|
||||||
|
points: Array<{ t: number; v: number }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ContainerStat = {
|
||||||
|
name: string;
|
||||||
|
cpuPercent: number | null;
|
||||||
|
memBytes: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ScrapeTarget = {
|
||||||
|
job: string;
|
||||||
|
health: string;
|
||||||
|
lastError: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function fetchVpsOverview(): Promise<VpsOverview> {
|
||||||
|
const { data } = await api.get<VpsOverview>('/api/v1/admin/vps-monitor/overview');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchVpsTimeseries(
|
||||||
|
metric: TimeseriesMetric,
|
||||||
|
range: TimeseriesRange
|
||||||
|
): Promise<TimeseriesResult> {
|
||||||
|
const { data } = await api.get<TimeseriesResult>('/api/v1/admin/vps-monitor/timeseries', {
|
||||||
|
params: { metric, range },
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchVpsContainers(): Promise<{ containers: ContainerStat[] }> {
|
||||||
|
const { data } = await api.get<{ containers: ContainerStat[] }>('/api/v1/admin/vps-monitor/containers');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchVpsServices(): Promise<{
|
||||||
|
prometheusReachable: boolean;
|
||||||
|
targets: ScrapeTarget[];
|
||||||
|
}> {
|
||||||
|
const { data } = await api.get<{ prometheusReachable: boolean; targets: ScrapeTarget[] }>(
|
||||||
|
'/api/v1/admin/vps-monitor/services'
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@ -84,6 +84,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record<string, string> = {
|
|||||||
'/admin/faq': 'admin.faq.view',
|
'/admin/faq': 'admin.faq.view',
|
||||||
'/admin/mobile-versions': 'admin.mobile_releases.view',
|
'/admin/mobile-versions': 'admin.mobile_releases.view',
|
||||||
'/admin/ssl-certificates': 'admin.settings.view',
|
'/admin/ssl-certificates': 'admin.settings.view',
|
||||||
|
'/admin/vps-monitor': 'admin.vps_monitor.view',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
||||||
@ -109,4 +110,5 @@ export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
|||||||
adminUsers: 'admin.rbac.view',
|
adminUsers: 'admin.rbac.view',
|
||||||
mobileVersions: 'admin.mobile_releases.view',
|
mobileVersions: 'admin.mobile_releases.view',
|
||||||
sslCertificates: 'admin.settings.view',
|
sslCertificates: 'admin.settings.view',
|
||||||
|
vpsMonitor: 'admin.vps_monitor.view',
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1065,6 +1065,7 @@ export const en = {
|
|||||||
accessControl: 'Access control',
|
accessControl: 'Access control',
|
||||||
apk: 'APK / Android',
|
apk: 'APK / Android',
|
||||||
ssl: 'SSL / TLS',
|
ssl: 'SSL / TLS',
|
||||||
|
vps: 'VPS / Docker',
|
||||||
},
|
},
|
||||||
options: {
|
options: {
|
||||||
title: 'Options',
|
title: 'Options',
|
||||||
@ -1155,8 +1156,54 @@ export const en = {
|
|||||||
title: 'SSL certificates',
|
title: 'SSL certificates',
|
||||||
description: 'See HTTPS certificate expiry dates and plan Let’s Encrypt renewals.',
|
description: 'See HTTPS certificate expiry dates and plan Let’s Encrypt renewals.',
|
||||||
},
|
},
|
||||||
|
vpsMonitor: {
|
||||||
|
title: 'VPS monitoring',
|
||||||
|
description: 'Live CPU, RAM, disk, network, and Docker container metrics for the host.',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
vpsMonitor: {
|
||||||
|
title: 'VPS monitoring',
|
||||||
|
subtitle: 'Read-only host and container metrics — no shell, no Docker control.',
|
||||||
|
refresh: 'Refresh',
|
||||||
|
loadError: 'Could not load VPS metrics.',
|
||||||
|
prometheusDown:
|
||||||
|
'Prometheus is unreachable. Start the monitoring profile: docker compose --profile monitoring up -d',
|
||||||
|
checkedAt: 'Last check: {{at}}',
|
||||||
|
cpu: 'CPU',
|
||||||
|
memory: 'Memory',
|
||||||
|
disk: 'Disk',
|
||||||
|
load: 'Load average',
|
||||||
|
loadHint: '1 / 5 / 15 minutes',
|
||||||
|
netIn: 'Network in',
|
||||||
|
netOut: 'Network out',
|
||||||
|
metric: 'Metric',
|
||||||
|
range: 'Range',
|
||||||
|
metrics: {
|
||||||
|
cpu: 'CPU %',
|
||||||
|
mem: 'Memory %',
|
||||||
|
disk: 'Disk %',
|
||||||
|
net_in: 'Network in',
|
||||||
|
net_out: 'Network out',
|
||||||
|
load1: 'Load (1m)',
|
||||||
|
},
|
||||||
|
ranges: {
|
||||||
|
'1h': '1 hour',
|
||||||
|
'6h': '6 hours',
|
||||||
|
'24h': '24 hours',
|
||||||
|
'7d': '7 days',
|
||||||
|
},
|
||||||
|
servicesTitle: 'Scrape targets',
|
||||||
|
job: 'Job',
|
||||||
|
health: 'Health',
|
||||||
|
lastError: 'Last error',
|
||||||
|
noTargets: 'No scrape targets reported.',
|
||||||
|
containersTitle: 'Containers (top by CPU)',
|
||||||
|
container: 'Container',
|
||||||
|
noContainers: 'No container metrics yet.',
|
||||||
|
readOnlyNote:
|
||||||
|
'This page is consultation-only. Prometheus, Node Exporter, and cAdvisor are not exposed on the public internet; the API never mounts the Docker socket.',
|
||||||
|
},
|
||||||
sslCertificates: {
|
sslCertificates: {
|
||||||
title: 'SSL certificates',
|
title: 'SSL certificates',
|
||||||
subtitle: 'Live TLS status for public hosts — plan renewals before expiry.',
|
subtitle: 'Live TLS status for public hosts — plan renewals before expiry.',
|
||||||
|
|||||||
@ -1079,6 +1079,7 @@ export const fr = {
|
|||||||
accessControl: 'Contrôle d’accès',
|
accessControl: 'Contrôle d’accès',
|
||||||
apk: 'APK / Android',
|
apk: 'APK / Android',
|
||||||
ssl: 'SSL / TLS',
|
ssl: 'SSL / TLS',
|
||||||
|
vps: 'VPS / Docker',
|
||||||
},
|
},
|
||||||
options: {
|
options: {
|
||||||
title: 'Options',
|
title: 'Options',
|
||||||
@ -1173,8 +1174,54 @@ export const fr = {
|
|||||||
title: 'Certificats SSL',
|
title: 'Certificats SSL',
|
||||||
description: 'Consulter les dates d’expiration HTTPS et planifier le renouvellement Let’s Encrypt.',
|
description: 'Consulter les dates d’expiration HTTPS et planifier le renouvellement Let’s Encrypt.',
|
||||||
},
|
},
|
||||||
|
vpsMonitor: {
|
||||||
|
title: 'Surveillance VPS',
|
||||||
|
description: 'Métriques live CPU, RAM, disque, réseau et conteneurs Docker de l’hôte.',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
vpsMonitor: {
|
||||||
|
title: 'Surveillance VPS',
|
||||||
|
subtitle: 'Métriques hôte et conteneurs en lecture seule — pas de shell, pas de contrôle Docker.',
|
||||||
|
refresh: 'Actualiser',
|
||||||
|
loadError: 'Impossible de charger les métriques VPS.',
|
||||||
|
prometheusDown:
|
||||||
|
'Prometheus est injoignable. Démarrez le profil monitoring : docker compose --profile monitoring up -d',
|
||||||
|
checkedAt: 'Dernière vérif. : {{at}}',
|
||||||
|
cpu: 'CPU',
|
||||||
|
memory: 'Mémoire',
|
||||||
|
disk: 'Disque',
|
||||||
|
load: 'Charge moyenne',
|
||||||
|
loadHint: '1 / 5 / 15 minutes',
|
||||||
|
netIn: 'Réseau entrant',
|
||||||
|
netOut: 'Réseau sortant',
|
||||||
|
metric: 'Métrique',
|
||||||
|
range: 'Période',
|
||||||
|
metrics: {
|
||||||
|
cpu: 'CPU %',
|
||||||
|
mem: 'Mémoire %',
|
||||||
|
disk: 'Disque %',
|
||||||
|
net_in: 'Réseau entrant',
|
||||||
|
net_out: 'Réseau sortant',
|
||||||
|
load1: 'Charge (1 min)',
|
||||||
|
},
|
||||||
|
ranges: {
|
||||||
|
'1h': '1 heure',
|
||||||
|
'6h': '6 heures',
|
||||||
|
'24h': '24 heures',
|
||||||
|
'7d': '7 jours',
|
||||||
|
},
|
||||||
|
servicesTitle: 'Cibles de scrape',
|
||||||
|
job: 'Job',
|
||||||
|
health: 'Santé',
|
||||||
|
lastError: 'Dernière erreur',
|
||||||
|
noTargets: 'Aucune cible de scrape signalée.',
|
||||||
|
containersTitle: 'Conteneurs (top CPU)',
|
||||||
|
container: 'Conteneur',
|
||||||
|
noContainers: 'Pas encore de métriques conteneurs.',
|
||||||
|
readOnlyNote:
|
||||||
|
'Page en consultation uniquement. Prometheus, Node Exporter et cAdvisor ne sont pas exposés sur Internet ; l’API ne monte jamais le socket Docker.',
|
||||||
|
},
|
||||||
sslCertificates: {
|
sslCertificates: {
|
||||||
title: 'Certificats SSL',
|
title: 'Certificats SSL',
|
||||||
subtitle: 'État TLS en direct des hôtes publics — planifiez le renouvellement avant expiration.',
|
subtitle: 'État TLS en direct des hôtes publics — planifiez le renouvellement avant expiration.',
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user