diff --git a/.env.example b/.env.example index dd319aa7..76c9cb83 100644 --- a/.env.example +++ b/.env.example @@ -116,6 +116,19 @@ APP_PUBLIC_URL=https://tloto.net:9443 # SSL_STATUS_WARN_DAYS=30 # SSL_STATUS_CRITICAL_DAYS=7 # 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 # 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'))" diff --git a/backend/.env.example b/backend/.env.example index b15cab45..7afc0d6e 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -63,6 +63,9 @@ APP_PUBLIC_URL=http://localhost:5173 # SSL_STATUS_WARN_DAYS=30 # SSL_STATUS_CRITICAL_DAYS=7 # 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 # SMTP_HOST=smtp.gmail.com # SMTP_PORT=587 diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index ed042af0..d4fb6845 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -316,4 +316,19 @@ export const config = { criticalDays: readEnvInt('SSL_STATUS_CRITICAL_DAYS', 7, 1, 30), 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), + }, + }, }; diff --git a/backend/src/controllers/vpsMonitorController.ts b/backend/src/controllers/vpsMonitorController.ts new file mode 100644 index 00000000..d6fdd7f0 --- /dev/null +++ b/backend/src/controllers/vpsMonitorController.ts @@ -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 { + 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 { + 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 { + 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 { + 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' }); + } +} diff --git a/backend/src/middleware/rateLimit.ts b/backend/src/middleware/rateLimit.ts index 1ff69dd3..f8701e17 100644 --- a/backend/src/middleware/rateLimit.ts +++ b/backend/src/middleware/rateLimit.ts @@ -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, +}); + diff --git a/backend/src/rbac/permissionCatalog.ts b/backend/src/rbac/permissionCatalog.ts index 23983902..7a3e1f5a 100644 --- a/backend/src/rbac/permissionCatalog.ts +++ b/backend/src/rbac/permissionCatalog.ts @@ -210,6 +210,9 @@ export const PERMISSION_CATALOG: PermissionDef[] = [ 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']), + // VPS infrastructure monitor (read-only Prometheus metrics) + p('vps_monitor', 'view', 'View VPS and Docker resource metrics', 'vps_monitor'), + // RBAC self-management p('rbac', 'view', 'View roles and permissions', '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.mobile_releases.view', 'admin.mobile_releases.manage', + 'admin.vps_monitor.view', 'admin.rbac.view', 'admin.rbac.manage', ]; diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index cd1c9216..74902bac 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -96,7 +96,13 @@ import { uuidParamSchema, alertIdParamSchema, } 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 walletController from '../controllers/walletController'; import * as withdrawalController from '../controllers/withdrawalController'; @@ -122,6 +128,7 @@ import * as soloEncouragementController from '../controllers/soloEncouragementCo import * as shareCardController from '../controllers/shareCardController'; import * as mobileAppReleaseController from '../controllers/mobileAppReleaseController'; import * as sslCertificateController from '../controllers/sslCertificateController'; +import * as vpsMonitorController from '../controllers/vpsMonitorController'; import { apkUpload } from '../middleware/apkUpload'; import { requireSupportedAppVersion } from '../middleware/requireSupportedAppVersion'; import { @@ -751,6 +758,39 @@ router.get( 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.patch( '/admin/settings', diff --git a/backend/src/services/vpsMonitorService.ts b/backend/src/services/vpsMonitorService.ts new file mode 100644 index 00000000..cdfccce1 --- /dev/null +++ b/backend/src/services/vpsMonitorService.ts @@ -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 = { + 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 = { + '1h': 3600, + '6h': 6 * 3600, + '24h': 24 * 3600, + '7d': 7 * 24 * 3600, +}; + +type PromVectorResult = { + status: string; + data?: { + resultType: string; + result: Array<{ + metric: Record; + value?: [number, string]; + values?: Array<[number, string]>; + }>; + }; + error?: string; +}; + +function baseUrl(): string { + return config.vpsMonitor.prometheusUrl.replace(/\/$/, ''); +} + +async function promGet(path: string, search: Record): Promise { + 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 { + 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> { + 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 { + 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(); + 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(); + 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; +} diff --git a/deploy/monitoring/prometheus.yml b/deploy/monitoring/prometheus.yml new file mode 100644 index 00000000..8626aeea --- /dev/null +++ b/deploy/monitoring/prometheus.yml @@ -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'] diff --git a/docker-compose.yml b/docker-compose.yml index 01aebddd..b78257a6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -102,6 +102,9 @@ x-backend-common: &backend-common SSL_STATUS_WARN_DAYS: ${SSL_STATUS_WARN_DAYS:-30} SSL_STATUS_CRITICAL_DAYS: ${SSL_STATUS_CRITICAL_DAYS:-7} 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: postgres: @@ -499,9 +502,83 @@ services: networks: - 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: prediqo-net: driver: bridge + monitoring-net: + # No host/gateway egress — exporters stay unreachable from the public internet + driver: bridge + internal: true volumes: postgres_data: @@ -510,3 +587,4 @@ volumes: apk_releases: letsencrypt: certbot-www: + prometheus_data: diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index 27aaba1a..d53f518c 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -953,6 +953,7 @@ Local Docker : `npm run docker:local:break-glass-reset-2fa -- …` (fichier `.en | Logs en direct | `npm run phase-b:logs` | | Redémarrer | `npm run phase-b:restart` | | 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` | | 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` | @@ -978,6 +979,17 @@ npm run phase-b:up:https # 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) 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. diff --git a/docs/VPS-MONITORING.md b/docs/VPS-MONITORING.md new file mode 100644 index 00000000..685b0371 --- /dev/null +++ b/docs/VPS-MONITORING.md @@ -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 diff --git a/package.json b/package.json index ab65eaa7..9b1c91a0 100644 --- a/package.json +++ b/package.json @@ -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:status": "docker compose ps", "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: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", diff --git a/prediqo_web/src/app/router/routePrefetch.ts b/prediqo_web/src/app/router/routePrefetch.ts index 49310725..f87eccfb 100644 --- a/prediqo_web/src/app/router/routePrefetch.ts +++ b/prediqo_web/src/app/router/routePrefetch.ts @@ -233,6 +233,11 @@ export const SslCertificatesAdminPage = lazyNamed( () => import('../../features/ssl-certificates/SslCertificatesAdminPage'), 'SslCertificatesAdminPage' ); +export const VpsMonitorAdminPage = lazyNamed( + 'VpsMonitorAdminPage', + () => import('../../features/vps-monitor/VpsMonitorAdminPage'), + 'VpsMonitorAdminPage' +); /** Exact path → page preload. Longest match wins for nested paths. */ const PATH_PRELOAD: Array<{ path: string; preload: () => Promise }> = [ @@ -274,6 +279,7 @@ const PATH_PRELOAD: Array<{ path: string; preload: () => Promise }> = [ { path: '/admin/admin-users', preload: AdminUsersPage.preload }, { path: '/admin/mobile-versions', preload: MobileVersionsAdminPage.preload }, { path: '/admin/ssl-certificates', preload: SslCertificatesAdminPage.preload }, + { path: '/admin/vps-monitor', preload: VpsMonitorAdminPage.preload }, ].sort((a, b) => b.path.length - a.path.length); /** Warm the JS chunk for a destination before navigation. */ diff --git a/prediqo_web/src/app/router/router.tsx b/prediqo_web/src/app/router/router.tsx index 71ce439a..fa01473a 100644 --- a/prediqo_web/src/app/router/router.tsx +++ b/prediqo_web/src/app/router/router.tsx @@ -50,6 +50,7 @@ import { AdminUserPermissionsPage, MobileVersionsAdminPage, SslCertificatesAdminPage, + VpsMonitorAdminPage, } from './routePrefetch'; function RouteFallback() { @@ -353,6 +354,14 @@ export const router = createBrowserRouter([ ), }, + { + path: 'admin/vps-monitor', + element: ( + + + + ), + }, { path: 'admin/solo-encouragement', element: ( diff --git a/prediqo_web/src/features/options/OptionsPage.tsx b/prediqo_web/src/features/options/OptionsPage.tsx index 477a6352..258fa071 100644 --- a/prediqo_web/src/features/options/OptionsPage.tsx +++ b/prediqo_web/src/features/options/OptionsPage.tsx @@ -24,6 +24,7 @@ import ManageAccountsRoundedIcon from '@mui/icons-material/ManageAccountsRounded import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded'; import PhoneAndroidRoundedIcon from '@mui/icons-material/PhoneAndroidRounded'; import VerifiedUserRoundedIcon from '@mui/icons-material/VerifiedUserRounded'; +import MonitorHeartRoundedIcon from '@mui/icons-material/MonitorHeartRounded'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useAuth } from '../../shared/auth/AuthContext'; @@ -51,7 +52,8 @@ type OptionCardKey = | 'rbac' | 'adminUsers' | 'mobileVersions' - | 'sslCertificates'; + | 'sslCertificates' + | 'vpsMonitor'; type OptionCardConfig = { key: OptionCardKey; @@ -254,6 +256,15 @@ const OPTION_CARDS: OptionCardConfig[] = [ bg: 'rgba(59,130,246,0.14)', 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. */ diff --git a/prediqo_web/src/features/vps-monitor/VpsMonitorAdminPage.tsx b/prediqo_web/src/features/vps-monitor/VpsMonitorAdminPage.tsx new file mode 100644 index 00000000..25d9335d --- /dev/null +++ b/prediqo_web/src/features/vps-monitor/VpsMonitorAdminPage.tsx @@ -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 ( + + + + {label} + + + + + {value} + + {hint && ( + + {hint} + + )} + {status !== 'unknown' && value.endsWith('%') && ( + + )} + + ); +} + +export function VpsMonitorAdminPage() { + const { t, i18n } = useTranslation(); + const [metric, setMetric] = useState('cpu'); + const [range, setRange] = useState('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 ( + + + + + + + + {t('admin.vpsMonitor.title')} + + + {t('admin.vpsMonitor.subtitle')} + + + + + + + {overviewQ.isError && ( + + {apiErrorMessage(overviewQ.error, t('admin.vpsMonitor.loadError'))} + + )} + + {o && !o.prometheusReachable && ( + + {t('admin.vpsMonitor.prometheusDown')} + + )} + + {o && ( + + {t('admin.vpsMonitor.checkedAt', { + at: new Date(o.checkedAt).toLocaleString(i18n.language), + })} + + )} + + + + + + + + + + + + + + + + setMetric(e.target.value as TimeseriesMetric)} + sx={{ minWidth: 160 }} + > + {(['cpu', 'mem', 'disk', 'net_in', 'net_out', 'load1'] as TimeseriesMetric[]).map((m) => ( + + {t(`admin.vpsMonitor.metrics.${m}`)} + + ))} + + setRange(e.target.value as TimeseriesRange)} + sx={{ minWidth: 140 }} + > + {(['1h', '6h', '24h', '7d'] as TimeseriesRange[]).map((r) => ( + + {t(`admin.vpsMonitor.ranges.${r}`)} + + ))} + + + + + + + + + + + + + + + + + + {t('admin.vpsMonitor.servicesTitle')} + + + + + + {t('admin.vpsMonitor.job')} + {t('admin.vpsMonitor.health')} + {t('admin.vpsMonitor.lastError')} + + + + {(servicesQ.data?.targets ?? []).map((row) => ( + + {row.job} + + + + + + {row.lastError || '—'} + + + + ))} + {!servicesQ.isLoading && !(servicesQ.data?.targets?.length) && ( + + {t('admin.vpsMonitor.noTargets')} + + )} + +
+
+ + + {t('admin.vpsMonitor.containersTitle')} + + + + + + {t('admin.vpsMonitor.container')} + {t('admin.vpsMonitor.cpu')} + {t('admin.vpsMonitor.memory')} + + + + {(containersQ.data?.containers ?? []).map((c) => ( + + + {c.name} + + {fmtPct(c.cpuPercent)} + {fmtBytes(c.memBytes)} + + ))} + {!containersQ.isLoading && !(containersQ.data?.containers?.length) && ( + + {t('admin.vpsMonitor.noContainers')} + + )} + +
+
+ + + {t('admin.vpsMonitor.readOnlyNote')} + +
+
+ ); +} diff --git a/prediqo_web/src/features/vps-monitor/api/vpsMonitorApi.ts b/prediqo_web/src/features/vps-monitor/api/vpsMonitorApi.ts new file mode 100644 index 00000000..1b474bd2 --- /dev/null +++ b/prediqo_web/src/features/vps-monitor/api/vpsMonitorApi.ts @@ -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 { + const { data } = await api.get('/api/v1/admin/vps-monitor/overview'); + return data; +} + +export async function fetchVpsTimeseries( + metric: TimeseriesMetric, + range: TimeseriesRange +): Promise { + const { data } = await api.get('/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; +} diff --git a/prediqo_web/src/shared/auth/permissions.ts b/prediqo_web/src/shared/auth/permissions.ts index 63e831ab..7f5cd9a0 100644 --- a/prediqo_web/src/shared/auth/permissions.ts +++ b/prediqo_web/src/shared/auth/permissions.ts @@ -84,6 +84,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record = { '/admin/faq': 'admin.faq.view', '/admin/mobile-versions': 'admin.mobile_releases.view', '/admin/ssl-certificates': 'admin.settings.view', + '/admin/vps-monitor': 'admin.vps_monitor.view', }; export const OPTIONS_CARD_PERMISSIONS: Record = { @@ -109,4 +110,5 @@ export const OPTIONS_CARD_PERMISSIONS: Record = { adminUsers: 'admin.rbac.view', mobileVersions: 'admin.mobile_releases.view', sslCertificates: 'admin.settings.view', + vpsMonitor: 'admin.vps_monitor.view', }; diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index f82bcbb5..9839af38 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -1065,6 +1065,7 @@ export const en = { accessControl: 'Access control', apk: 'APK / Android', ssl: 'SSL / TLS', + vps: 'VPS / Docker', }, options: { title: 'Options', @@ -1155,8 +1156,54 @@ export const en = { title: 'SSL certificates', 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: { title: 'SSL certificates', subtitle: 'Live TLS status for public hosts — plan renewals before expiry.', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index 4d241207..5e3e8b73 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -1079,6 +1079,7 @@ export const fr = { accessControl: 'Contrôle d’accès', apk: 'APK / Android', ssl: 'SSL / TLS', + vps: 'VPS / Docker', }, options: { title: 'Options', @@ -1173,8 +1174,54 @@ export const fr = { title: 'Certificats SSL', 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: { title: 'Certificats SSL', subtitle: 'État TLS en direct des hôtes publics — planifiez le renouvellement avant expiration.',